blob: 9a64a7e002e0685d5d1b65f147e36a4bab54ea98 [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 Hackbornf51f6122013-02-04 18:23:34 -080021import android.app.AppOpsManager;
Dianne Hackborn860755f2010-06-03 18:47:52 -070022import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070024import com.android.internal.os.ProcessStats;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import com.android.server.AppOpsService;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070026import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.IntentResolver;
28import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import com.android.server.SystemServer;
30import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070031import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070032import com.android.server.pm.UserManagerService;
Craig Mautner4b71aa12012-12-27 17:20:01 -080033import com.android.server.wm.AppTransition;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080034import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
Dianne Hackborndd71fc82009-12-16 19:24:32 -080036import dalvik.system.Zygote;
37
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.Activity;
39import android.app.ActivityManager;
Craig Mautnercae015f2013-02-08 14:31:27 -080040import android.app.ActivityManager.RunningTaskInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070042import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.ActivityThread;
44import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070045import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020046import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070048import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.IApplicationThread;
50import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070051import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070052import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070054import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.app.IThumbnailReceiver;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080056import android.app.IUiAutomationConnection;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070057import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070059import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070060import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080062import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020063import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080064import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080065import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070066import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070068import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.content.ContentResolver;
70import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020071import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070072import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070073import android.content.IIntentReceiver;
74import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070075import android.content.Intent;
76import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070077import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.ActivityInfo;
79import android.content.pm.ApplicationInfo;
80import android.content.pm.ConfigurationInfo;
81import android.content.pm.IPackageDataObserver;
82import android.content.pm.IPackageManager;
83import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080084import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070086import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070087import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070088import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.content.pm.ProviderInfo;
90import android.content.pm.ResolveInfo;
91import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040092import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.content.res.Configuration;
94import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070095import android.net.Proxy;
96import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.net.Uri;
98import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080099import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -0800100import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700101import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -0800102import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800104import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.FileUtils;
106import android.os.Handler;
107import android.os.IBinder;
108import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700109import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700110import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.Looper;
112import android.os.Message;
113import android.os.Parcel;
114import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700116import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400118import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700120import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.os.SystemClock;
122import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700123import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700124import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700126import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800128import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700129import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700131import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700133import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import android.view.Gravity;
135import android.view.LayoutInflater;
136import android.view.View;
137import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.BufferedInputStream;
140import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700141import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700142import java.io.DataInputStream;
143import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.File;
145import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700146import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700148import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200149import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800150import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700152import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.lang.ref.WeakReference;
154import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700155import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700156import java.util.Collections;
157import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.util.HashMap;
159import java.util.HashSet;
160import java.util.Iterator;
161import java.util.List;
162import java.util.Locale;
163import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700164import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700165import java.util.concurrent.atomic.AtomicBoolean;
166import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800168public final class ActivityManagerService extends ActivityManagerNative
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700169 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700170 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700172 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400174 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SWITCH = localLOGV || false;
176 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700177 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_PAUSE = localLOGV || false;
179 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
180 static final boolean DEBUG_TRANSITION = localLOGV || false;
181 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800182 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700183 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700185 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 static final boolean DEBUG_VISBILITY = localLOGV || false;
187 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700188 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700189 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700190 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800191 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700193 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700194 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700195 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700196 static final boolean DEBUG_POWER = localLOGV || false;
197 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700198 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700199 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800200 static final boolean VALIDATE_TOKENS = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 static final boolean SHOW_ACTIVITY_START_TIME = true;
202
203 // Control over CPU and battery monitoring.
204 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
205 static final boolean MONITOR_CPU_USAGE = true;
206 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
207 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
208 static final boolean MONITOR_THREAD_CPU_USAGE = false;
209
Dianne Hackborn1655be42009-05-08 14:29:01 -0700210 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700211 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700212
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800213 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700215 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 // Maximum number of recent tasks that we can remember.
218 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700219
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700220 // Amount of time after a call to stopAppSwitches() during which we will
221 // prevent further untrusted switches from happening.
222 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223
224 // 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.
226 static final int PROC_START_TIMEOUT = 10*1000;
227
Jeff Brown3f9dd282011-07-08 20:02:19 -0700228 // How long we wait for a launched process to attach to the activity manager
229 // before we decide it's never going to come up for real, when the process was
230 // started with a wrapper for instrumentation (such as Valgrind) because it
231 // could take much longer than usual.
232 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 // How long to wait after going idle before forcing apps to GC.
235 static final int GC_TIMEOUT = 5*1000;
236
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700237 // The minimum amount of time between successive GC requests for a process.
238 static final int GC_MIN_INTERVAL = 60*1000;
239
Dianne Hackborn287952c2010-09-22 22:34:31 -0700240 // The rate at which we check for apps using excessive power -- 15 mins.
241 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
242
243 // The minimum sample duration we will allow before deciding we have
244 // enough data on wake locks to start killing things.
245 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
246
247 // The minimum sample duration we will allow before deciding we have
248 // enough data on CPU usage to start killing things.
249 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800252 static final int BROADCAST_FG_TIMEOUT = 10*1000;
253 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // How long we wait until we timeout on key dispatching.
256 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // How long we wait until we timeout on key dispatching during instrumentation.
259 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
260
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700261 // Amount of time we wait for observers to handle a user switch before
262 // giving up on them and unfreezing the screen.
263 static final int USER_SWITCH_TIMEOUT = 2*1000;
264
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700265 // Maximum number of users we allow to be running at a time.
266 static final int MAX_RUNNING_USERS = 3;
267
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800268 // How long to wait in getTopActivityExtras for the activity to respond with the result.
269 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000;
270
Dan Egnor42471dd2010-01-07 17:25:22 -0800271 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272
273 static final String[] EMPTY_STRING_ARRAY = new String[0];
274
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700275 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700276
277 private final boolean mHeadless;
278
Joe Onorato54a4a412011-11-02 20:50:08 -0700279 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
280 // default actuion automatically. Important for devices without direct input
281 // devices.
282 private boolean mShowDialogs = true;
283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800284 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700285 * Description of a request to start a new activity, which has been held
286 * due to app switches being disabled.
287 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700288 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700289 ActivityRecord r;
290 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700291 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700292 }
293
294 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
295 = new ArrayList<PendingActivityLaunch>();
296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800298 BroadcastQueue mFgBroadcastQueue;
299 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800300 // Convenient for easy iteration over the queues. Foreground is first
301 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800302 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800303
304 BroadcastQueue broadcastQueueForIntent(Intent intent) {
305 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
306 if (DEBUG_BACKGROUND_BROADCAST) {
307 Slog.i(TAG, "Broadcast intent " + intent + " on "
308 + (isFg ? "foreground" : "background")
309 + " queue");
310 }
311 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
312 }
313
314 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
315 for (BroadcastQueue queue : mBroadcastQueues) {
316 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
317 if (r != null) {
318 return r;
319 }
320 }
321 return null;
322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
324 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 * Activity we have told the window manager to have key focus.
326 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700327 ActivityRecord mFocusedActivity = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800328
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700329 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 * List of intents that were used to start the most recent tasks.
331 */
Craig Mautnercae015f2013-02-08 14:31:27 -0800332 private final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800334 public class PendingActivityExtras extends Binder implements Runnable {
335 public final ActivityRecord activity;
336 public boolean haveResult = false;
337 public Bundle result = null;
338 public PendingActivityExtras(ActivityRecord _activity) {
339 activity = _activity;
340 }
341 @Override
342 public void run() {
343 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity);
344 synchronized (this) {
345 haveResult = true;
346 notifyAll();
347 }
348 }
349 }
350
351 final ArrayList<PendingActivityExtras> mPendingActivityExtras
352 = new ArrayList<PendingActivityExtras>();
353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700355 * Process management.
356 */
357 final ProcessList mProcessList = new ProcessList();
358
359 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800360 * All of the applications we currently have running organized by name.
361 * The keys are strings of the application package name (as
362 * returned by the package manager), and the keys are ApplicationRecord
363 * objects.
364 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700365 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
367 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800368 * The currently running isolated processes.
369 */
370 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
371
372 /**
373 * Counter for assigning isolated process uids, to avoid frequently reusing the
374 * same ones.
375 */
376 int mNextIsolatedProcessUid = 0;
377
378 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700379 * The currently running heavy-weight process, if any.
380 */
381 ProcessRecord mHeavyWeightProcess = null;
382
383 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800384 * The last time that various processes have crashed.
385 */
386 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
387
388 /**
389 * Set of applications that we consider to be bad, and will reject
390 * incoming broadcasts from (which the user has no control over).
391 * Processes are added to this set when they have crashed twice within
392 * a minimum amount of time; they are removed from it when they are
393 * later restarted (hopefully due to some user action). The value is the
394 * time it was added to the list.
395 */
396 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
397
398 /**
399 * All of the processes we currently have running organized by pid.
400 * The keys are the pid running the application.
401 *
402 * <p>NOTE: This object is protected by its own lock, NOT the global
403 * activity manager lock!
404 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700405 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
407 /**
408 * All of the processes that have been forced to be foreground. The key
409 * is the pid of the caller who requested it (we hold a death
410 * link on it).
411 */
412 abstract class ForegroundToken implements IBinder.DeathRecipient {
413 int pid;
414 IBinder token;
415 }
416 final SparseArray<ForegroundToken> mForegroundProcesses
417 = new SparseArray<ForegroundToken>();
418
419 /**
420 * List of records for processes that someone had tried to start before the
421 * system was ready. We don't start them at that point, but ensure they
422 * are started by the time booting is complete.
423 */
424 final ArrayList<ProcessRecord> mProcessesOnHold
425 = new ArrayList<ProcessRecord>();
426
427 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 * List of persistent applications that are in the process
429 * of being started.
430 */
431 final ArrayList<ProcessRecord> mPersistentStartingProcesses
432 = new ArrayList<ProcessRecord>();
433
434 /**
435 * Processes that are being forcibly torn down.
436 */
437 final ArrayList<ProcessRecord> mRemovedProcesses
438 = new ArrayList<ProcessRecord>();
439
440 /**
441 * List of running applications, sorted by recent usage.
442 * The first entry in the list is the least recently used.
443 * It contains ApplicationRecord objects. This list does NOT include
444 * any persistent application records (since we never want to exit them).
445 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800446 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 = new ArrayList<ProcessRecord>();
448
449 /**
450 * List of processes that should gc as soon as things are idle.
451 */
452 final ArrayList<ProcessRecord> mProcessesToGc
453 = new ArrayList<ProcessRecord>();
454
455 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800456 * This is the process holding what we currently consider to be
457 * the "home" activity.
458 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700459 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800460
461 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700462 * This is the process holding the activity the user last visited that
463 * is in a different process from the one they are currently in.
464 */
465 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800466
467 /**
468 * The time at which the previous process was last visible.
469 */
470 long mPreviousProcessVisibleTime;
471
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700472 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700473 * Which uses have been started, so are allowed to run code.
474 */
475 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
476
477 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700478 * LRU list of history of current users. Most recently current is at the end.
479 */
480 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
481
482 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700483 * Constant array of the users that are currently started.
484 */
485 int[] mStartedUserArray = new int[] { 0 };
486
487 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700488 * Registered observers of the user switching mechanics.
489 */
490 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
491 = new RemoteCallbackList<IUserSwitchObserver>();
492
493 /**
494 * Currently active user switch.
495 */
496 Object mCurUserSwitchCallback;
497
498 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400499 * Packages that the user has asked to have run in screen size
500 * compatibility mode instead of filling the screen.
501 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700502 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400503
504 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 * Set of PendingResultRecord objects that are currently active.
506 */
507 final HashSet mPendingResultRecords = new HashSet();
508
509 /**
510 * Set of IntentSenderRecord objects that are currently active.
511 */
512 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
513 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
514
515 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800516 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700517 * already logged DropBox entries for. Guarded by itself. If
518 * something (rogue user app) forces this over
519 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
520 */
521 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
522 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
523
524 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700525 * Strict Mode background batched logging state.
526 *
527 * The string buffer is guarded by itself, and its lock is also
528 * used to determine if another batched write is already
529 * in-flight.
530 */
531 private final StringBuilder mStrictModeBuffer = new StringBuilder();
532
533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 * Keeps track of all IIntentReceivers that have been registered for
535 * broadcasts. Hash keys are the receiver IBinder, hash value is
536 * a ReceiverList.
537 */
538 final HashMap mRegisteredReceivers = new HashMap();
539
540 /**
541 * Resolver for broadcast intents to registered receivers.
542 * Holds BroadcastFilter (subclass of IntentFilter).
543 */
544 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
545 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
546 @Override
547 protected boolean allowFilterResult(
548 BroadcastFilter filter, List<BroadcastFilter> dest) {
549 IBinder target = filter.receiverList.receiver.asBinder();
550 for (int i=dest.size()-1; i>=0; i--) {
551 if (dest.get(i).receiverList.receiver.asBinder() == target) {
552 return false;
553 }
554 }
555 return true;
556 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700557
558 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700559 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700560 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
561 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700562 return super.newResult(filter, match, userId);
563 }
564 return null;
565 }
566
567 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700568 protected BroadcastFilter[] newArray(int size) {
569 return new BroadcastFilter[size];
570 }
571
572 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700573 protected String packageForFilter(BroadcastFilter filter) {
574 return filter.packageName;
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 };
577
578 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700579 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700581 * that action (which should usually be one). The SparseArray is keyed
582 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
583 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700585 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
586 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700588 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589
590 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700591 * Backup/restore process management
592 */
593 String mBackupAppName = null;
594 BackupRecord mBackupTarget = null;
595
596 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800597 * List of PendingThumbnailsRecord objects of clients who are still
598 * waiting to receive all of the thumbnails for a task.
599 */
Craig Mautnercae015f2013-02-08 14:31:27 -0800600 final ArrayList<PendingThumbnailsRecord> mPendingThumbnails =
601 new ArrayList<PendingThumbnailsRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700603 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 /**
606 * List of content providers who have clients waiting for them. The
607 * application is currently being launched and the provider will be
608 * removed from this list once it is published.
609 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700610 final ArrayList<ContentProviderRecord> mLaunchingProviders
611 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612
613 /**
614 * Global set of specific Uri permissions that have been granted.
615 */
616 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
617 = new SparseArray<HashMap<Uri, UriPermission>>();
618
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800619 CoreSettingsObserver mCoreSettingsObserver;
620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 /**
622 * Thread-local storage used to carry caller permissions over through
623 * indirect content-provider access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 */
625 private class Identity {
626 public int pid;
627 public int uid;
628
629 Identity(int _pid, int _uid) {
630 pid = _pid;
631 uid = _uid;
632 }
633 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800635 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
636
637 /**
638 * All information we have collected about the runtime performance of
639 * any user id that can impact battery performance.
640 */
641 final BatteryStatsService mBatteryStatsService;
642
643 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800644 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 */
646 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800647
648 /**
649 * Information about and control over application operations
650 */
651 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652
653 /**
654 * Current configuration information. HistoryRecord objects are given
655 * a reference to this object to indicate which configuration they are
656 * currently running in, so this object must be kept immutable.
657 */
658 Configuration mConfiguration = new Configuration();
659
660 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800661 * Current sequencing integer of the configuration, for skipping old
662 * configurations.
663 */
664 int mConfigurationSeq = 0;
665
666 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700667 * Hardware-reported OpenGLES version.
668 */
669 final int GL_ES_VERSION;
670
671 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 * List of initialization arguments to pass to all processes when binding applications to them.
673 * For example, references to the commonly used services.
674 */
675 HashMap<String, IBinder> mAppBindArgs;
676
677 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700678 * Temporary to avoid allocations. Protected by main lock.
679 */
680 final StringBuilder mStringBuilder = new StringBuilder(256);
681
682 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683 * Used to control how we initialize the service.
684 */
685 boolean mStartRunning = false;
686 ComponentName mTopComponent;
687 String mTopAction;
688 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700689 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 boolean mSystemReady = false;
691 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700692 boolean mWaitingUpdate = false;
693 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700694 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700695 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696
697 Context mContext;
698
699 int mFactoryTest;
700
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700701 boolean mCheckedForSetup;
702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700704 * The time at which we will allow normal application switches again,
705 * after a call to {@link #stopAppSwitches()}.
706 */
707 long mAppSwitchesAllowedTime;
708
709 /**
710 * This is set to true after the first switch after mAppSwitchesAllowedTime
711 * is set; any switches after that will clear the time.
712 */
713 boolean mDidAppSwitch;
714
715 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700716 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700717 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700718 long mLastPowerCheckRealtime;
719
720 /**
721 * Last time (in uptime) at which we checked for power usage.
722 */
723 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * Set while we are wanting to sleep, to prevent any
727 * activities from being started/resumed.
728 */
729 boolean mSleeping = false;
730
731 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700732 * State of external calls telling us if the device is asleep.
733 */
734 boolean mWentToSleep = false;
735
736 /**
737 * State of external call telling us if the lock screen is shown.
738 */
739 boolean mLockScreenShown = false;
740
741 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700742 * Set if we are shutting down the system, similar to sleeping.
743 */
744 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745
746 /**
747 * Task identifier that activities are currently being started
748 * in. Incremented each time a new task is created.
749 * todo: Replace this with a TokenSpace class that generates non-repeating
750 * integers that won't wrap.
751 */
752 int mCurTask = 1;
753
754 /**
755 * Current sequence id for oom_adj computation traversal.
756 */
757 int mAdjSeq = 0;
758
759 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700760 * Current sequence id for process LRU updating.
761 */
762 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763
764 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700765 * Keep track of the non-hidden/empty process we last found, to help
766 * determine how to distribute hidden/empty processes next time.
767 */
768 int mNumNonHiddenProcs = 0;
769
770 /**
771 * Keep track of the number of hidden procs, to balance oom adj
772 * distribution between those and empty procs.
773 */
774 int mNumHiddenProcs = 0;
775
776 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700777 * Keep track of the number of service processes we last found, to
778 * determine on the next iteration which should be B services.
779 */
780 int mNumServiceProcs = 0;
781 int mNewNumServiceProcs = 0;
782
783 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 * System monitoring: number of processes that died since the last
785 * N procs were started.
786 */
787 int[] mProcDeaths = new int[20];
788
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700789 /**
790 * This is set if we had to do a delayed dexopt of an app before launching
791 * it, to increasing the ANR timeouts in that case.
792 */
793 boolean mDidDexOpt;
794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795 String mDebugApp = null;
796 boolean mWaitForDebugger = false;
797 boolean mDebugTransient = false;
798 String mOrigDebugApp = null;
799 boolean mOrigWaitForDebugger = false;
800 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700801 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700802 String mProfileApp = null;
803 ProcessRecord mProfileProc = null;
804 String mProfileFile;
805 ParcelFileDescriptor mProfileFd;
806 int mProfileType = 0;
807 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800808 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700810 static class ProcessChangeItem {
811 static final int CHANGE_ACTIVITIES = 1<<0;
812 static final int CHANGE_IMPORTANCE= 1<<1;
813 int changes;
814 int uid;
815 int pid;
816 int importance;
817 boolean foregroundActivities;
818 }
819
Jeff Sharkeya4620792011-05-20 15:29:23 -0700820 final RemoteCallbackList<IProcessObserver> mProcessObservers
821 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700822 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
823
824 final ArrayList<ProcessChangeItem> mPendingProcessChanges
825 = new ArrayList<ProcessChangeItem>();
826 final ArrayList<ProcessChangeItem> mAvailProcessChanges
827 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 * Runtime statistics collection thread. This object's lock is used to
831 * protect all related state.
832 */
833 final Thread mProcessStatsThread;
834
835 /**
836 * Used to collect process stats when showing not responding dialog.
837 * Protected by mProcessStatsThread.
838 */
839 final ProcessStats mProcessStats = new ProcessStats(
840 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700841 final AtomicLong mLastCpuTime = new AtomicLong(0);
842 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 long mLastWriteTime = 0;
845
846 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700847 * Used to retain an update lock when the foreground activity is in
848 * immersive mode.
849 */
850 final UpdateLock mUpdateLock = new UpdateLock("immersive");
851
852 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 * Set to true after the system has finished booting.
854 */
855 boolean mBooted = false;
856
Dianne Hackborn7d608422011-08-07 16:24:18 -0700857 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700858 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859
860 WindowManagerService mWindowManager;
861
862 static ActivityManagerService mSelf;
863 static ActivityThread mSystemThread;
864
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700865 private int mCurrentUserId = 0;
866 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700867 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 private final class AppDeathRecipient implements IBinder.DeathRecipient {
870 final ProcessRecord mApp;
871 final int mPid;
872 final IApplicationThread mAppThread;
873
874 AppDeathRecipient(ProcessRecord app, int pid,
875 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 TAG, "New death recipient " + this
878 + " for thread " + thread.asBinder());
879 mApp = app;
880 mPid = pid;
881 mAppThread = thread;
882 }
883
884 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800885 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 TAG, "Death received in " + this
887 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 synchronized(ActivityManagerService.this) {
889 appDiedLocked(mApp, mPid, mAppThread);
890 }
891 }
892 }
893
894 static final int SHOW_ERROR_MSG = 1;
895 static final int SHOW_NOT_RESPONDING_MSG = 2;
896 static final int SHOW_FACTORY_ERROR_MSG = 3;
897 static final int UPDATE_CONFIGURATION_MSG = 4;
898 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
899 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 static final int SERVICE_TIMEOUT_MSG = 12;
901 static final int UPDATE_TIME_ZONE = 13;
902 static final int SHOW_UID_ERROR_MSG = 14;
903 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700905 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700906 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800907 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700908 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
909 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700910 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700911 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700912 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700913 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700914 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700915 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700916 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700917 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700918 static final int REPORT_USER_SWITCH_MSG = 34;
919 static final int CONTINUE_USER_SWITCH_MSG = 35;
920 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700921 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800923 static final int FIRST_ACTIVITY_STACK_MSG = 100;
924 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
925 static final int FIRST_COMPAT_MODE_MSG = 300;
926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700928 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700929 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930
931 final Handler mHandler = new Handler() {
932 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800933 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 //}
935
936 public void handleMessage(Message msg) {
937 switch (msg.what) {
938 case SHOW_ERROR_MSG: {
939 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700940 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
941 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 synchronized (ActivityManagerService.this) {
943 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800946 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700947 if (res != null) {
948 res.set(0);
949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 return;
951 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700952 if (!showBackground && UserHandle.getAppId(proc.uid)
953 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
954 && proc.pid != MY_PID) {
955 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
956 if (res != null) {
957 res.set(0);
958 }
959 return;
960 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700961 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700962 Dialog d = new AppErrorDialog(mContext,
963 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 d.show();
965 proc.crashDialog = d;
966 } else {
967 // The device is asleep, so just pretend that the user
968 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700969 if (res != null) {
970 res.set(0);
971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 }
973 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700974
975 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } break;
977 case SHOW_NOT_RESPONDING_MSG: {
978 synchronized (ActivityManagerService.this) {
979 HashMap data = (HashMap) msg.obj;
980 ProcessRecord proc = (ProcessRecord)data.get("app");
981 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800982 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 return;
984 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800985
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700986 Intent intent = new Intent("android.intent.action.ANR");
987 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800988 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
989 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700990 }
991 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -0800992 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -0700993 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800994
Justin Kohbc52ca22012-03-29 15:11:44 -0700995 if (mShowDialogs) {
996 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700997 mContext, proc, (ActivityRecord)data.get("activity"),
998 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -0700999 d.show();
1000 proc.anrDialog = d;
1001 } else {
1002 // Just kill the app if there is no dialog to be shown.
1003 killAppAtUsersRequest(proc, null);
1004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001006
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001007 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001009 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1010 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1011 synchronized (ActivityManagerService.this) {
1012 ProcessRecord proc = (ProcessRecord) data.get("app");
1013 if (proc == null) {
1014 Slog.e(TAG, "App not found when showing strict mode dialog.");
1015 break;
1016 }
1017 if (proc.crashDialog != null) {
1018 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1019 return;
1020 }
1021 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001022 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001023 Dialog d = new StrictModeViolationDialog(mContext,
1024 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001025 d.show();
1026 proc.crashDialog = d;
1027 } else {
1028 // The device is asleep, so just pretend that the user
1029 // saw a crash dialog and hit "force quit".
1030 res.set(0);
1031 }
1032 }
1033 ensureBootCompleted();
1034 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 case SHOW_FACTORY_ERROR_MSG: {
1036 Dialog d = new FactoryErrorDialog(
1037 mContext, msg.getData().getCharSequence("msg"));
1038 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001039 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 } break;
1041 case UPDATE_CONFIGURATION_MSG: {
1042 final ContentResolver resolver = mContext.getContentResolver();
1043 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1044 } break;
1045 case GC_BACKGROUND_PROCESSES_MSG: {
1046 synchronized (ActivityManagerService.this) {
1047 performAppGcsIfAppropriateLocked();
1048 }
1049 } break;
1050 case WAIT_FOR_DEBUGGER_MSG: {
1051 synchronized (ActivityManagerService.this) {
1052 ProcessRecord app = (ProcessRecord)msg.obj;
1053 if (msg.arg1 != 0) {
1054 if (!app.waitedForDebugger) {
1055 Dialog d = new AppWaitingForDebuggerDialog(
1056 ActivityManagerService.this,
1057 mContext, app);
1058 app.waitDialog = d;
1059 app.waitedForDebugger = true;
1060 d.show();
1061 }
1062 } else {
1063 if (app.waitDialog != null) {
1064 app.waitDialog.dismiss();
1065 app.waitDialog = null;
1066 }
1067 }
1068 }
1069 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001071 if (mDidDexOpt) {
1072 mDidDexOpt = false;
1073 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1074 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001075 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001076 return;
1077 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001078 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 } break;
1080 case UPDATE_TIME_ZONE: {
1081 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001082 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1083 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 if (r.thread != null) {
1085 try {
1086 r.thread.updateTimeZone();
1087 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001088 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 }
1090 }
1091 }
1092 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001093 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001094 case CLEAR_DNS_CACHE: {
1095 synchronized (ActivityManagerService.this) {
1096 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1097 ProcessRecord r = mLruProcesses.get(i);
1098 if (r.thread != null) {
1099 try {
1100 r.thread.clearDnsCache();
1101 } catch (RemoteException ex) {
1102 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1103 }
1104 }
1105 }
1106 }
1107 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001108 case UPDATE_HTTP_PROXY: {
1109 ProxyProperties proxy = (ProxyProperties)msg.obj;
1110 String host = "";
1111 String port = "";
1112 String exclList = "";
1113 if (proxy != null) {
1114 host = proxy.getHost();
1115 port = Integer.toString(proxy.getPort());
1116 exclList = proxy.getExclusionList();
1117 }
1118 synchronized (ActivityManagerService.this) {
1119 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1120 ProcessRecord r = mLruProcesses.get(i);
1121 if (r.thread != null) {
1122 try {
1123 r.thread.setHttpProxy(host, port, exclList);
1124 } catch (RemoteException ex) {
1125 Slog.w(TAG, "Failed to update http proxy for: " +
1126 r.info.processName);
1127 }
1128 }
1129 }
1130 }
1131 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001133 String title = "System UIDs Inconsistent";
1134 String text = "UIDs on the system are inconsistent, you need to wipe your"
1135 + " data partition or your device will be unstable.";
1136 Log.e(TAG, title + ": " + text);
1137 if (mShowDialogs) {
1138 // XXX This is a temporary dialog, no need to localize.
1139 AlertDialog d = new BaseErrorDialog(mContext);
1140 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1141 d.setCancelable(false);
1142 d.setTitle(title);
1143 d.setMessage(text);
1144 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1145 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1146 mUidAlert = d;
1147 d.show();
1148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 } break;
1150 case IM_FEELING_LUCKY_MSG: {
1151 if (mUidAlert != null) {
1152 mUidAlert.dismiss();
1153 mUidAlert = null;
1154 }
1155 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001157 if (mDidDexOpt) {
1158 mDidDexOpt = false;
1159 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1160 nmsg.obj = msg.obj;
1161 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1162 return;
1163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 ProcessRecord app = (ProcessRecord)msg.obj;
1165 synchronized (ActivityManagerService.this) {
1166 processStartTimedOutLocked(app);
1167 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001168 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001169 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1170 synchronized (ActivityManagerService.this) {
1171 doPendingActivityLaunchesLocked(true);
1172 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001173 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001174 case KILL_APPLICATION_MSG: {
1175 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001176 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001177 boolean restart = (msg.arg2 == 1);
1178 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001179 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1180 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001181 }
1182 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001183 case FINALIZE_PENDING_INTENT_MSG: {
1184 ((PendingIntentRecord)msg.obj).completeFinalize();
1185 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001186 case POST_HEAVY_NOTIFICATION_MSG: {
1187 INotificationManager inm = NotificationManager.getService();
1188 if (inm == null) {
1189 return;
1190 }
1191
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001192 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001193 ProcessRecord process = root.app;
1194 if (process == null) {
1195 return;
1196 }
1197
1198 try {
1199 Context context = mContext.createPackageContext(process.info.packageName, 0);
1200 String text = mContext.getString(R.string.heavy_weight_notification,
1201 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1202 Notification notification = new Notification();
1203 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1204 notification.when = 0;
1205 notification.flags = Notification.FLAG_ONGOING_EVENT;
1206 notification.tickerText = text;
1207 notification.defaults = 0; // please be quiet
1208 notification.sound = null;
1209 notification.vibrate = null;
1210 notification.setLatestEventInfo(context, text,
1211 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001212 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1213 PendingIntent.FLAG_CANCEL_CURRENT, null,
1214 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001215
1216 try {
1217 int[] outId = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001218 inm.enqueueNotificationWithTag("android", "android", null,
Dianne Hackborn41203752012-08-31 14:05:51 -07001219 R.string.heavy_weight_notification,
1220 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001221 } catch (RuntimeException e) {
1222 Slog.w(ActivityManagerService.TAG,
1223 "Error showing notification for heavy-weight app", e);
1224 } catch (RemoteException e) {
1225 }
1226 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001227 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001228 }
1229 } break;
1230 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1231 INotificationManager inm = NotificationManager.getService();
1232 if (inm == null) {
1233 return;
1234 }
1235 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001236 inm.cancelNotificationWithTag("android", null,
1237 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001238 } catch (RuntimeException e) {
1239 Slog.w(ActivityManagerService.TAG,
1240 "Error canceling notification for service", e);
1241 } catch (RemoteException e) {
1242 }
1243 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001244 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1245 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001246 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001247 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001248 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1249 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001250 }
1251 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001252 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1253 synchronized (ActivityManagerService.this) {
1254 ActivityRecord ar = (ActivityRecord)msg.obj;
1255 if (mCompatModeDialog != null) {
1256 if (mCompatModeDialog.mAppInfo.packageName.equals(
1257 ar.info.applicationInfo.packageName)) {
1258 return;
1259 }
1260 mCompatModeDialog.dismiss();
1261 mCompatModeDialog = null;
1262 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001263 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001264 if (mCompatModePackages.getPackageAskCompatModeLocked(
1265 ar.packageName)) {
1266 int mode = mCompatModePackages.computeCompatModeLocked(
1267 ar.info.applicationInfo);
1268 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1269 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1270 mCompatModeDialog = new CompatModeDialog(
1271 ActivityManagerService.this, mContext,
1272 ar.info.applicationInfo);
1273 mCompatModeDialog.show();
1274 }
1275 }
1276 }
1277 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001278 break;
1279 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001280 case DISPATCH_PROCESSES_CHANGED: {
1281 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001282 break;
1283 }
1284 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001285 final int pid = msg.arg1;
1286 final int uid = msg.arg2;
1287 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001288 break;
1289 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001290 case REPORT_MEM_USAGE: {
1291 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1292 if (!isDebuggable) {
1293 return;
1294 }
1295 synchronized (ActivityManagerService.this) {
1296 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001297 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1298 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001299 // avoid spamming.
1300 return;
1301 }
1302 mLastMemUsageReportTime = now;
1303 }
1304 Thread thread = new Thread() {
1305 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001306 StringBuilder dropBuilder = new StringBuilder(1024);
1307 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001308 StringWriter oomSw = new StringWriter();
1309 PrintWriter oomPw = new PrintWriter(oomSw);
1310 StringWriter catSw = new StringWriter();
1311 PrintWriter catPw = new PrintWriter(catSw);
1312 String[] emptyArgs = new String[] { };
1313 StringBuilder tag = new StringBuilder(128);
1314 StringBuilder stack = new StringBuilder(128);
1315 tag.append("Low on memory -- ");
1316 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1317 tag, stack);
1318 dropBuilder.append(stack);
1319 dropBuilder.append('\n');
1320 dropBuilder.append('\n');
1321 String oomString = oomSw.toString();
1322 dropBuilder.append(oomString);
1323 dropBuilder.append('\n');
1324 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001325 try {
1326 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1327 "procrank", });
1328 final InputStreamReader converter = new InputStreamReader(
1329 proc.getInputStream());
1330 BufferedReader in = new BufferedReader(converter);
1331 String line;
1332 while (true) {
1333 line = in.readLine();
1334 if (line == null) {
1335 break;
1336 }
1337 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001338 logBuilder.append(line);
1339 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001340 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001341 dropBuilder.append(line);
1342 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001343 }
1344 converter.close();
1345 } catch (IOException e) {
1346 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001347 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001348 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001349 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001350 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001351 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1352 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001353 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001354 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001355 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001356 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001357 addErrorToDropBox("lowmem", null, "system_server", null,
1358 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001359 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001360 synchronized (ActivityManagerService.this) {
1361 long now = SystemClock.uptimeMillis();
1362 if (mLastMemUsageReportTime < now) {
1363 mLastMemUsageReportTime = now;
1364 }
1365 }
1366 }
1367 };
1368 thread.start();
1369 break;
1370 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001371 case REPORT_USER_SWITCH_MSG: {
1372 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1373 break;
1374 }
1375 case CONTINUE_USER_SWITCH_MSG: {
1376 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1377 break;
1378 }
1379 case USER_SWITCH_TIMEOUT_MSG: {
1380 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1381 break;
1382 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001383 case IMMERSIVE_MODE_LOCK_MSG: {
1384 final boolean nextState = (msg.arg1 != 0);
1385 if (mUpdateLock.isHeld() != nextState) {
1386 if (DEBUG_IMMERSIVE) {
1387 final ActivityRecord r = (ActivityRecord) msg.obj;
1388 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1389 }
1390 if (nextState) {
1391 mUpdateLock.acquire();
1392 } else {
1393 mUpdateLock.release();
1394 }
1395 }
1396 break;
1397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
1399 }
1400 };
1401
1402 public static void setSystemProcess() {
1403 try {
1404 ActivityManagerService m = mSelf;
1405
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001406 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001408 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001409 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 if (MONITOR_CPU_USAGE) {
1411 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1412 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 ServiceManager.addService("permission", new PermissionController(m));
1414
1415 ApplicationInfo info =
1416 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001417 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001418 mSystemThread.installSystemApplicationInfo(info);
1419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 synchronized (mSelf) {
1421 ProcessRecord app = mSelf.newProcessRecordLocked(
1422 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001423 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001425 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001426 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001427 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 synchronized (mSelf.mPidsSelfLocked) {
1429 mSelf.mPidsSelfLocked.put(app.pid, app);
1430 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001431 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 } catch (PackageManager.NameNotFoundException e) {
1434 throw new RuntimeException(
1435 "Unable to find android system package", e);
1436 }
1437 }
1438
1439 public void setWindowManager(WindowManagerService wm) {
1440 mWindowManager = wm;
1441 }
1442
1443 public static final Context main(int factoryTest) {
1444 AThread thr = new AThread();
1445 thr.start();
1446
1447 synchronized (thr) {
1448 while (thr.mService == null) {
1449 try {
1450 thr.wait();
1451 } catch (InterruptedException e) {
1452 }
1453 }
1454 }
1455
1456 ActivityManagerService m = thr.mService;
1457 mSelf = m;
1458 ActivityThread at = ActivityThread.systemMain();
1459 mSystemThread = at;
1460 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001461 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 m.mContext = context;
1463 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001464 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465
1466 m.mBatteryStatsService.publish(context);
1467 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001468 m.mAppOpsService.publish(context);
1469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 synchronized (thr) {
1471 thr.mReady = true;
1472 thr.notifyAll();
1473 }
1474
1475 m.startRunning(null, null, null, null);
1476
1477 return context;
1478 }
1479
1480 public static ActivityManagerService self() {
1481 return mSelf;
1482 }
1483
1484 static class AThread extends Thread {
1485 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001486 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 boolean mReady = false;
1488
1489 public AThread() {
1490 super("ActivityManager");
1491 }
1492
1493 public void run() {
1494 Looper.prepare();
1495
1496 android.os.Process.setThreadPriority(
1497 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001498 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499
1500 ActivityManagerService m = new ActivityManagerService();
1501
1502 synchronized (this) {
1503 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001504 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 notifyAll();
1506 }
1507
1508 synchronized (this) {
1509 while (!mReady) {
1510 try {
1511 wait();
1512 } catch (InterruptedException e) {
1513 }
1514 }
1515 }
1516
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001517 // For debug builds, log event loop stalls to dropbox for analysis.
1518 if (StrictMode.conditionallyEnableDebugLogging()) {
1519 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1520 }
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 Looper.loop();
1523 }
1524 }
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 static class MemBinder extends Binder {
1527 ActivityManagerService mActivityManagerService;
1528 MemBinder(ActivityManagerService activityManagerService) {
1529 mActivityManagerService = activityManagerService;
1530 }
1531
1532 @Override
1533 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001534 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1535 != PackageManager.PERMISSION_GRANTED) {
1536 pw.println("Permission Denial: can't dump meminfo from from pid="
1537 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1538 + " without permission " + android.Manifest.permission.DUMP);
1539 return;
1540 }
1541
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001542 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001543 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
1545 }
1546
Chet Haase9c1e23b2011-03-24 10:51:31 -07001547 static class GraphicsBinder extends Binder {
1548 ActivityManagerService mActivityManagerService;
1549 GraphicsBinder(ActivityManagerService activityManagerService) {
1550 mActivityManagerService = activityManagerService;
1551 }
1552
1553 @Override
1554 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001555 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1556 != PackageManager.PERMISSION_GRANTED) {
1557 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1558 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1559 + " without permission " + android.Manifest.permission.DUMP);
1560 return;
1561 }
1562
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001563 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001564 }
1565 }
1566
Jeff Brown6754ba22011-12-14 20:20:01 -08001567 static class DbBinder extends Binder {
1568 ActivityManagerService mActivityManagerService;
1569 DbBinder(ActivityManagerService activityManagerService) {
1570 mActivityManagerService = activityManagerService;
1571 }
1572
1573 @Override
1574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1575 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1576 != PackageManager.PERMISSION_GRANTED) {
1577 pw.println("Permission Denial: can't dump dbinfo from from pid="
1578 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1579 + " without permission " + android.Manifest.permission.DUMP);
1580 return;
1581 }
1582
1583 mActivityManagerService.dumpDbInfo(fd, pw, args);
1584 }
1585 }
1586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 static class CpuBinder extends Binder {
1588 ActivityManagerService mActivityManagerService;
1589 CpuBinder(ActivityManagerService activityManagerService) {
1590 mActivityManagerService = activityManagerService;
1591 }
1592
1593 @Override
1594 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001595 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1596 != PackageManager.PERMISSION_GRANTED) {
1597 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1598 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1599 + " without permission " + android.Manifest.permission.DUMP);
1600 return;
1601 }
1602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001604 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1605 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1606 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608 }
1609 }
1610
1611 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001612 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001613
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001614 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1615 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1616 mBroadcastQueues[0] = mFgBroadcastQueue;
1617 mBroadcastQueues[1] = mBgBroadcastQueue;
1618
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001619 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001620 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 File dataDir = Environment.getDataDirectory();
1623 File systemDir = new File(dataDir, "system");
1624 systemDir.mkdirs();
1625 mBatteryStatsService = new BatteryStatsService(new File(
1626 systemDir, "batterystats.bin").toString());
1627 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001628 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001629 mOnBattery = DEBUG_POWER ? true
1630 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001631 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001632
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001633 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001634 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001635 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001636 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001638 // User 0 is the first and only user that runs at boot.
1639 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001640 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001641 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001642
Jack Palevichb90d28c2009-07-22 15:35:24 -07001643 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1644 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1645
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001646 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001647 mConfiguration.setLocale(Locale.getDefault());
1648
Dianne Hackborn813075a62011-11-14 17:45:19 -08001649 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 mProcessStats.init();
1651
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001652 mCompatModePackages = new CompatModePackages(this, systemDir);
1653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 // Add ourself to the Watchdog monitors.
1655 Watchdog.getInstance().addMonitor(this);
1656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 mProcessStatsThread = new Thread("ProcessStats") {
1658 public void run() {
1659 while (true) {
1660 try {
1661 try {
1662 synchronized(this) {
1663 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001664 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001666 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 // + ", write delay=" + nextWriteDelay);
1668 if (nextWriteDelay < nextCpuDelay) {
1669 nextCpuDelay = nextWriteDelay;
1670 }
1671 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001672 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 this.wait(nextCpuDelay);
1674 }
1675 }
1676 } catch (InterruptedException e) {
1677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 updateCpuStatsNow();
1679 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001680 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 }
1683 }
1684 };
1685 mProcessStatsThread.start();
1686 }
1687
1688 @Override
1689 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1690 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001691 if (code == SYSPROPS_TRANSACTION) {
1692 // We need to tell all apps about the system property change.
1693 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1694 synchronized(this) {
1695 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1696 final int NA = apps.size();
1697 for (int ia=0; ia<NA; ia++) {
1698 ProcessRecord app = apps.valueAt(ia);
1699 if (app.thread != null) {
1700 procs.add(app.thread.asBinder());
1701 }
1702 }
1703 }
1704 }
1705
1706 int N = procs.size();
1707 for (int i=0; i<N; i++) {
1708 Parcel data2 = Parcel.obtain();
1709 try {
1710 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1711 } catch (RemoteException e) {
1712 }
1713 data2.recycle();
1714 }
1715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 try {
1717 return super.onTransact(code, data, reply, flags);
1718 } catch (RuntimeException e) {
1719 // The activity manager only throws security exceptions, so let's
1720 // log all others.
1721 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001722 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723 }
1724 throw e;
1725 }
1726 }
1727
1728 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001729 final long now = SystemClock.uptimeMillis();
1730 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1731 return;
1732 }
1733 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1734 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 mProcessStatsThread.notify();
1736 }
1737 }
1738 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 void updateCpuStatsNow() {
1741 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001742 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 final long now = SystemClock.uptimeMillis();
1744 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001747 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1748 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 haveNewCpuStats = true;
1750 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001751 //Slog.i(TAG, mProcessStats.printCurrentState());
1752 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 // + mProcessStats.getTotalCpuPercent() + "%");
1754
Joe Onorato8a9b2202010-02-26 18:56:32 -08001755 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if ("true".equals(SystemProperties.get("events.cpu"))) {
1757 int user = mProcessStats.getLastUserTime();
1758 int system = mProcessStats.getLastSystemTime();
1759 int iowait = mProcessStats.getLastIoWaitTime();
1760 int irq = mProcessStats.getLastIrqTime();
1761 int softIrq = mProcessStats.getLastSoftIrqTime();
1762 int idle = mProcessStats.getLastIdleTime();
1763
1764 int total = user + system + iowait + irq + softIrq + idle;
1765 if (total == 0) total = 1;
1766
Doug Zongker2bec3d42009-12-04 12:52:44 -08001767 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 ((user+system+iowait+irq+softIrq) * 100) / total,
1769 (user * 100) / total,
1770 (system * 100) / total,
1771 (iowait * 100) / total,
1772 (irq * 100) / total,
1773 (softIrq * 100) / total);
1774 }
1775 }
1776
Amith Yamasanie43530a2009-08-21 13:11:37 -07001777 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001778 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001779 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 synchronized(mPidsSelfLocked) {
1781 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001782 if (mOnBattery) {
1783 int perc = bstats.startAddingCpuLocked();
1784 int totalUTime = 0;
1785 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001786 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001788 ProcessStats.Stats st = mProcessStats.getStats(i);
1789 if (!st.working) {
1790 continue;
1791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001793 int otherUTime = (st.rel_utime*perc)/100;
1794 int otherSTime = (st.rel_stime*perc)/100;
1795 totalUTime += otherUTime;
1796 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 if (pr != null) {
1798 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001799 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1800 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001801 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001802 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001803 } else {
1804 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001805 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001806 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001807 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1808 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001809 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001813 bstats.finishAddingCpuLocked(perc, totalUTime,
1814 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
1817 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1820 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001821 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 }
1824 }
1825 }
1826
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001827 @Override
1828 public void batteryNeedsCpuUpdate() {
1829 updateCpuStatsNow();
1830 }
1831
1832 @Override
1833 public void batteryPowerChanged(boolean onBattery) {
1834 // When plugging in, update the CPU stats first before changing
1835 // the plug state.
1836 updateCpuStatsNow();
1837 synchronized (this) {
1838 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001839 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001840 }
1841 }
1842 }
1843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 /**
1845 * Initialize the application bind args. These are passed to each
1846 * process when the bindApplication() IPC is sent to the process. They're
1847 * lazily setup to make sure the services are running when they're asked for.
1848 */
1849 private HashMap<String, IBinder> getCommonServicesLocked() {
1850 if (mAppBindArgs == null) {
1851 mAppBindArgs = new HashMap<String, IBinder>();
1852
1853 // Setup the application init args
1854 mAppBindArgs.put("package", ServiceManager.getService("package"));
1855 mAppBindArgs.put("window", ServiceManager.getService("window"));
1856 mAppBindArgs.put(Context.ALARM_SERVICE,
1857 ServiceManager.getService(Context.ALARM_SERVICE));
1858 }
1859 return mAppBindArgs;
1860 }
1861
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001862 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 if (mFocusedActivity != r) {
1864 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001865 if (r != null) {
1866 mWindowManager.setFocusedApp(r.appToken, true);
1867 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001868 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
1870 }
1871
Christopher Tate73c2aee2012-03-15 16:27:14 -07001872 final void applyUpdateLockStateLocked(ActivityRecord r) {
1873 // Modifications to the UpdateLock state are done on our handler, outside
1874 // the activity manager's locks. The new state is determined based on the
1875 // state *now* of the relevant activity record. The object is passed to
1876 // the handler solely for logging detail, not to be consulted/modified.
1877 final boolean nextState = r != null && r.immersive;
1878 mHandler.sendMessage(
1879 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1880 }
1881
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001882 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001884 int lrui = mLruProcesses.indexOf(app);
1885 if (lrui >= 0) mLruProcesses.remove(lrui);
1886
1887 int i = mLruProcesses.size()-1;
1888 int skipTop = 0;
1889
Dianne Hackborn906497c2010-05-10 15:57:38 -07001890 app.lruSeq = mLruSeq;
1891
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001892 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001893 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001894 if (app.activities.size() > 0) {
1895 // If this process has activities, we more strongly want to keep
1896 // it around.
1897 app.lruWeight = app.lastActivityTime;
1898 } else if (app.pubProviders.size() > 0) {
1899 // If this process contains content providers, we want to keep
1900 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001901 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001902 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001903 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001904 } else {
1905 // If this process doesn't have activities, we less strongly
1906 // want to keep it around, and generally want to avoid getting
1907 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001908 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001909 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001910 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001911 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001912
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001913 while (i >= 0) {
1914 ProcessRecord p = mLruProcesses.get(i);
1915 // If this app shouldn't be in front of the first N background
1916 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001917 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001918 skipTop--;
1919 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001920 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001921 mLruProcesses.add(i+1, app);
1922 break;
1923 }
1924 i--;
1925 }
1926 if (i < 0) {
1927 mLruProcesses.add(0, app);
1928 }
1929
Dianne Hackborn906497c2010-05-10 15:57:38 -07001930 // If the app is currently using a content provider or service,
1931 // bump those processes as well.
1932 if (app.connections.size() > 0) {
1933 for (ConnectionRecord cr : app.connections) {
1934 if (cr.binding != null && cr.binding.service != null
1935 && cr.binding.service.app != null
1936 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001937 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001938 }
1939 }
1940 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001941 for (int j=app.conProviders.size()-1; j>=0; j--) {
1942 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1943 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001944 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001945 }
1946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001949 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001950 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001951 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001952 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001953
1954 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1955 if (oomAdj) {
1956 updateOomAdjLocked();
1957 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001958 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001959
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001960 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001962 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001963 // The system gets to run in any process. If there are multiple
1964 // processes with the same uid, just pick the first (this
1965 // should never happen).
1966 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1967 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001968 if (procs == null) return null;
1969 final int N = procs.size();
1970 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001971 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
1974 ProcessRecord proc = mProcessNames.get(processName, uid);
1975 return proc;
1976 }
1977
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001978 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001979 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001980 try {
1981 if (pm.performDexOpt(packageName)) {
1982 mDidDexOpt = true;
1983 }
1984 } catch (RemoteException e) {
1985 }
1986 }
1987
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001988 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08001990 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
1991 || transit == AppTransition.TRANSIT_TASK_OPEN
1992 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001995 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001997 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1998 boolean isolated) {
1999 ProcessRecord app;
2000 if (!isolated) {
2001 app = getProcessRecordLocked(processName, info.uid);
2002 } else {
2003 // If this is an isolated process, it can't re-use an existing process.
2004 app = null;
2005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 // We don't have to do anything more if:
2007 // (1) There is an existing application record; and
2008 // (2) The caller doesn't think it is dead, OR there is no thread
2009 // object attached to it so we know it couldn't have crashed; and
2010 // (3) There is a pid assigned to it, so it is either starting or
2011 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002012 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 + " app=" + app + " knownToBeDead=" + knownToBeDead
2014 + " thread=" + (app != null ? app.thread : null)
2015 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002016 if (app != null && app.pid > 0) {
2017 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002018 // We already have the app running, or are waiting for it to
2019 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002020 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002021 // If this is a new package in the process, add the package to the list
2022 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002023 return app;
2024 } else {
2025 // An application record is attached to a previous process,
2026 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002027 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002028 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 String hostingNameStr = hostingName != null
2033 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002034
2035 if (!isolated) {
2036 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2037 // If we are in the background, then check to see if this process
2038 // is bad. If so, we will just silently fail.
2039 if (mBadProcesses.get(info.processName, info.uid) != null) {
2040 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2041 + "/" + info.processName);
2042 return null;
2043 }
2044 } else {
2045 // When the user is explicitly starting a process, then clear its
2046 // crash count so that we won't make it bad until they see at
2047 // least one crash dialog again, and make the process good again
2048 // if it had been bad.
2049 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002050 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002051 mProcessCrashTimes.remove(info.processName, info.uid);
2052 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002053 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2054 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002055 info.processName);
2056 mBadProcesses.remove(info.processName, info.uid);
2057 if (app != null) {
2058 app.bad = false;
2059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002065 app = newProcessRecordLocked(null, info, processName, isolated);
2066 if (app == null) {
2067 Slog.w(TAG, "Failed making new process record for "
2068 + processName + "/" + info.uid + " isolated=" + isolated);
2069 return null;
2070 }
2071 mProcessNames.put(processName, app.uid, app);
2072 if (isolated) {
2073 mIsolatedProcesses.put(app.uid, app);
2074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 } else {
2076 // If this is a new package in the process, add the package to the list
2077 app.addPackage(info.packageName);
2078 }
2079
2080 // If the system is not ready yet, then hold off on starting this
2081 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002082 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002083 && !isAllowedWhileBooting(info)
2084 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 if (!mProcessesOnHold.contains(app)) {
2086 mProcessesOnHold.add(app);
2087 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002088 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 return app;
2090 }
2091
2092 startProcessLocked(app, hostingType, hostingNameStr);
2093 return (app.pid != 0) ? app : null;
2094 }
2095
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002096 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2097 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2098 }
2099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 private final void startProcessLocked(ProcessRecord app,
2101 String hostingType, String hostingNameStr) {
2102 if (app.pid > 0 && app.pid != MY_PID) {
2103 synchronized (mPidsSelfLocked) {
2104 mPidsSelfLocked.remove(app.pid);
2105 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2106 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002107 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002110 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2111 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 mProcessesOnHold.remove(app);
2113
2114 updateCpuStats();
2115
2116 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2117 mProcDeaths[0] = 0;
2118
2119 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002120 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002122 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002123 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002124 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002125 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002126 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002127 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002128 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002129
2130 if (Environment.isExternalStorageEmulated()) {
2131 if (pm.checkPermission(
2132 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2133 app.info.packageName) == PERMISSION_GRANTED) {
2134 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2135 } else {
2136 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2137 }
2138 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002139 } catch (PackageManager.NameNotFoundException e) {
2140 Slog.w(TAG, "Unable to retrieve gids", e);
2141 }
Kenny Roote091f222012-09-11 15:01:26 -07002142
2143 /*
2144 * Add shared application GID so applications can share some
2145 * resources like shared libraries
2146 */
2147 if (permGids == null) {
2148 gids = new int[1];
2149 } else {
2150 gids = new int[permGids.length + 1];
2151 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2152 }
2153 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2156 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2157 && mTopComponent != null
2158 && app.processName.equals(mTopComponent.getPackageName())) {
2159 uid = 0;
2160 }
2161 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2162 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2163 uid = 0;
2164 }
2165 }
2166 int debugFlags = 0;
2167 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2168 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002169 // Also turn on CheckJNI for debuggable apps. It's quite
2170 // awkward to turn on otherwise.
2171 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002172 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002173 // Run the app in safe mode if its manifest requests so or the
2174 // system is booted in safe mode.
2175 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2176 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002177 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2180 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2181 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002182 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2183 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 if ("1".equals(SystemProperties.get("debug.assert"))) {
2186 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2187 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002188
2189 // Start the process. It will either succeed and return a result containing
2190 // the PID of the new process, or else throw a RuntimeException.
2191 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002192 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002193 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2196 synchronized (bs) {
2197 if (bs.isOnBattery()) {
2198 app.batteryStats.incStartsLocked();
2199 }
2200 }
2201
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002202 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2203 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 app.processName, hostingType,
2205 hostingNameStr != null ? hostingNameStr : "");
2206
2207 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002208 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 }
2210
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002211 StringBuilder buf = mStringBuilder;
2212 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 buf.append("Start proc ");
2214 buf.append(app.processName);
2215 buf.append(" for ");
2216 buf.append(hostingType);
2217 if (hostingNameStr != null) {
2218 buf.append(" ");
2219 buf.append(hostingNameStr);
2220 }
2221 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002222 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 buf.append(" uid=");
2224 buf.append(uid);
2225 buf.append(" gids={");
2226 if (gids != null) {
2227 for (int gi=0; gi<gids.length; gi++) {
2228 if (gi != 0) buf.append(", ");
2229 buf.append(gids[gi]);
2230
2231 }
2232 }
2233 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002234 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002235 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002236 app.usingWrapper = startResult.usingWrapper;
2237 app.removed = false;
2238 synchronized (mPidsSelfLocked) {
2239 this.mPidsSelfLocked.put(startResult.pid, app);
2240 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2241 msg.obj = app;
2242 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2243 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245 } catch (RuntimeException e) {
2246 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002247 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002248 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002249 }
2250 }
2251
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002252 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 if (resumed) {
2254 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2255 } else {
2256 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2257 }
2258 }
2259
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002260 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002261 if (mHeadless) {
2262 // Added because none of the other calls to ensureBootCompleted seem to fire
2263 // when running headless.
2264 ensureBootCompleted();
2265 return false;
2266 }
2267
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002268 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2269 && mTopAction == null) {
2270 // We are running in factory test mode, but unable to find
2271 // the factory test app, so just sit around displaying the
2272 // error message and don't try to start anything.
2273 return false;
2274 }
2275 Intent intent = new Intent(
2276 mTopAction,
2277 mTopData != null ? Uri.parse(mTopData) : null);
2278 intent.setComponent(mTopComponent);
2279 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2280 intent.addCategory(Intent.CATEGORY_HOME);
2281 }
2282 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002283 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002284 if (aInfo != null) {
2285 intent.setComponent(new ComponentName(
2286 aInfo.applicationInfo.packageName, aInfo.name));
2287 // Don't do this if the home app is currently being
2288 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002289 aInfo = new ActivityInfo(aInfo);
2290 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002291 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2292 aInfo.applicationInfo.uid);
2293 if (app == null || app.instrumentationClass == null) {
2294 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002295 mMainStack.startActivityLocked(null, intent, null, aInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002296 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002297 }
2298 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002299
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002300 return true;
2301 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002302
Amith Yamasani259d5e52012-08-31 15:11:01 -07002303 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2304 ActivityInfo ai = null;
2305 ComponentName comp = intent.getComponent();
2306 try {
2307 if (comp != null) {
2308 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2309 } else {
2310 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2311 intent,
2312 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2313 flags, userId);
2314
2315 if (info != null) {
2316 ai = info.activityInfo;
2317 }
2318 }
2319 } catch (RemoteException e) {
2320 // ignore
2321 }
2322
2323 return ai;
2324 }
2325
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002326 /**
2327 * Starts the "new version setup screen" if appropriate.
2328 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002329 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002330 // Only do this once per boot.
2331 if (mCheckedForSetup) {
2332 return;
2333 }
2334
2335 // We will show this screen if the current one is a different
2336 // version than the last one shown, and we are not running in
2337 // low-level factory test mode.
2338 final ContentResolver resolver = mContext.getContentResolver();
2339 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002340 Settings.Global.getInt(resolver,
2341 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002342 mCheckedForSetup = true;
2343
2344 // See if we should be showing the platform update setup UI.
2345 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2346 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2347 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2348
2349 // We don't allow third party apps to replace this.
2350 ResolveInfo ri = null;
2351 for (int i=0; ris != null && i<ris.size(); i++) {
2352 if ((ris.get(i).activityInfo.applicationInfo.flags
2353 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2354 ri = ris.get(i);
2355 break;
2356 }
2357 }
2358
2359 if (ri != null) {
2360 String vers = ri.activityInfo.metaData != null
2361 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2362 : null;
2363 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2364 vers = ri.activityInfo.applicationInfo.metaData.getString(
2365 Intent.METADATA_SETUP_VERSION);
2366 }
2367 String lastVers = Settings.Secure.getString(
2368 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2369 if (vers != null && !vers.equals(lastVers)) {
2370 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2371 intent.setComponent(new ComponentName(
2372 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002373 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002374 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002375 }
2376 }
2377 }
2378 }
2379
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002380 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002381 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002382 }
2383
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002384 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002385 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002386 throw new SecurityException("Isolated process not allowed to call " + caller);
2387 }
2388 }
2389
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002390 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002391 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002392 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002393 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2394 }
2395 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002396
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002397 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002398 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2399 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002400 synchronized (this) {
2401 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2402 }
2403 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002404
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002405 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002407 synchronized (this) {
2408 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2409 }
2410 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002411
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002412 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002413 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2414 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002415 synchronized (this) {
2416 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002417 }
2418 }
2419
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002420 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002421 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002422 synchronized (this) {
2423 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2424 }
2425 }
2426
2427 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002428 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2429 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002430 synchronized (this) {
2431 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2432 }
2433 }
2434
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002436 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002437 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002440 private void dispatchProcessesChanged() {
2441 int N;
2442 synchronized (this) {
2443 N = mPendingProcessChanges.size();
2444 if (mActiveProcessChanges.length < N) {
2445 mActiveProcessChanges = new ProcessChangeItem[N];
2446 }
2447 mPendingProcessChanges.toArray(mActiveProcessChanges);
2448 mAvailProcessChanges.addAll(mPendingProcessChanges);
2449 mPendingProcessChanges.clear();
2450 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2451 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002452 int i = mProcessObservers.beginBroadcast();
2453 while (i > 0) {
2454 i--;
2455 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2456 if (observer != null) {
2457 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002458 for (int j=0; j<N; j++) {
2459 ProcessChangeItem item = mActiveProcessChanges[j];
2460 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2461 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2462 + item.pid + " uid=" + item.uid + ": "
2463 + item.foregroundActivities);
2464 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2465 item.foregroundActivities);
2466 }
2467 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2468 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2469 + item.pid + " uid=" + item.uid + ": " + item.importance);
2470 observer.onImportanceChanged(item.pid, item.uid,
2471 item.importance);
2472 }
2473 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002474 } catch (RemoteException e) {
2475 }
2476 }
2477 }
2478 mProcessObservers.finishBroadcast();
2479 }
2480
2481 private void dispatchProcessDied(int pid, int uid) {
2482 int i = mProcessObservers.beginBroadcast();
2483 while (i > 0) {
2484 i--;
2485 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2486 if (observer != null) {
2487 try {
2488 observer.onProcessDied(pid, uid);
2489 } catch (RemoteException e) {
2490 }
2491 }
2492 }
2493 mProcessObservers.finishBroadcast();
2494 }
2495
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002496 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002497 final int N = mPendingActivityLaunches.size();
2498 if (N <= 0) {
2499 return;
2500 }
2501 for (int i=0; i<N; i++) {
2502 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002504 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002505 }
2506 mPendingActivityLaunches.clear();
2507 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002508
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002509 public final int startActivity(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002510 Intent intent, String resolvedType, IBinder resultTo,
2511 String resultWho, int requestCode, int startFlags,
2512 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002513 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
2514 resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002515 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002516 }
2517
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002518 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Amith Yamasani82644082012-08-03 13:09:11 -07002519 Intent intent, String resolvedType, IBinder resultTo,
2520 String resultWho, int requestCode, int startFlags,
2521 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002522 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002523 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002524 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002525 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002526 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2527 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002528 }
2529
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002530 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002531 Intent intent, String resolvedType, IBinder resultTo,
2532 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002533 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002534 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002535 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002536 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002537 WaitResult res = new WaitResult();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002538 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002539 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002540 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002541 return res;
2542 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002543
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002544 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002545 Intent intent, String resolvedType, IBinder resultTo,
2546 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002547 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002548 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002549 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002550 false, true, "startActivityWithConfig", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002551 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002552 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002553 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002554 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002555 }
2556
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002557 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002558 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002559 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002560 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002561 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002562 // Refuse possible leaked file descriptors
2563 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2564 throw new IllegalArgumentException("File descriptors passed in Intent");
2565 }
2566
2567 IIntentSender sender = intent.getTarget();
2568 if (!(sender instanceof PendingIntentRecord)) {
2569 throw new IllegalArgumentException("Bad PendingIntent object");
2570 }
2571
2572 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002573
2574 synchronized (this) {
2575 // If this is coming from the currently resumed activity, it is
2576 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 if (mMainStack.mResumedActivity != null
2578 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002579 Binder.getCallingUid()) {
2580 mAppSwitchesAllowedTime = 0;
2581 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002582 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002583 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2584 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002585 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002586 }
2587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002589 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 // Refuse possible leaked file descriptors
2591 if (intent != null && intent.hasFileDescriptors() == true) {
2592 throw new IllegalArgumentException("File descriptors passed in Intent");
2593 }
2594
2595 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002596 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2597 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002598 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 return false;
2600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 if (r.app == null || r.app.thread == null) {
2602 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002603 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 return false;
2605 }
2606 intent = new Intent(intent);
2607 // The caller is not allowed to change the data.
2608 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2609 // And we are resetting to find the next component...
2610 intent.setComponent(null);
2611
2612 ActivityInfo aInfo = null;
2613 try {
2614 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002615 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002617 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002618 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619
2620 // Look for the original activity in the list...
2621 final int N = resolves != null ? resolves.size() : 0;
2622 for (int i=0; i<N; i++) {
2623 ResolveInfo rInfo = resolves.get(i);
2624 if (rInfo.activityInfo.packageName.equals(r.packageName)
2625 && rInfo.activityInfo.name.equals(r.info.name)) {
2626 // We found the current one... the next matching is
2627 // after it.
2628 i++;
2629 if (i<N) {
2630 aInfo = resolves.get(i).activityInfo;
2631 }
2632 break;
2633 }
2634 }
2635 } catch (RemoteException e) {
2636 }
2637
2638 if (aInfo == null) {
2639 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002640 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641 return false;
2642 }
2643
2644 intent.setComponent(new ComponentName(
2645 aInfo.applicationInfo.packageName, aInfo.name));
2646 intent.setFlags(intent.getFlags()&~(
2647 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2648 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2649 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2650 Intent.FLAG_ACTIVITY_NEW_TASK));
2651
2652 // Okay now we need to start the new activity, replacing the
2653 // currently running activity. This is a little tricky because
2654 // we want to start the new one as if the current one is finished,
2655 // but not finish the current one first so that there is no flicker.
2656 // And thus...
2657 final boolean wasFinishing = r.finishing;
2658 r.finishing = true;
2659
2660 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002661 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 final String resultWho = r.resultWho;
2663 final int requestCode = r.requestCode;
2664 r.resultTo = null;
2665 if (resultTo != null) {
2666 resultTo.removeResultsLocked(r, resultWho, requestCode);
2667 }
2668
2669 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002670 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002671 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002672 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002673 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 Binder.restoreCallingIdentity(origId);
2675
2676 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002677 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 return false;
2679 }
2680 return true;
2681 }
2682 }
2683
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002684 final int startActivityInPackage(int uid, String callingPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002686 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2687
Dianne Hackborn139748f2012-09-24 11:36:57 -07002688 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002689 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002691 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002692 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002693 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002694 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002695 }
2696
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002697 public final int startActivities(IApplicationThread caller, String callingPackage,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002698 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2699 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002700 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002701 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002702 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002703 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents,
2704 resolvedTypes, resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002705 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002706 }
2707
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002708 final int startActivitiesInPackage(int uid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002709 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002710 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002711
Dianne Hackborn139748f2012-09-24 11:36:57 -07002712 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002713 false, true, "startActivityInPackage", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002714 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes,
2715 resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002716 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002717 }
2718
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002719 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002721 // Quick case: check if the top-most recent task is the same.
2722 if (N > 0 && mRecentTasks.get(0) == task) {
2723 return;
2724 }
2725 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 for (int i=0; i<N; i++) {
2727 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002728 if (task.userId == tr.userId
2729 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2730 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 mRecentTasks.remove(i);
2732 i--;
2733 N--;
2734 if (task.intent == null) {
2735 // If the new recent task we are adding is not fully
2736 // specified, then replace it with the existing recent task.
2737 task = tr;
2738 }
2739 }
2740 }
2741 if (N >= MAX_RECENT_TASKS) {
2742 mRecentTasks.remove(N-1);
2743 }
2744 mRecentTasks.add(0, task);
2745 }
2746
2747 public void setRequestedOrientation(IBinder token,
2748 int requestedOrientation) {
2749 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002750 ActivityRecord r = mMainStack.isInStackLocked(token);
2751 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 return;
2753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002754 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002755 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002757 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002758 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 if (config != null) {
2760 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002761 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002762 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 }
2764 }
2765 Binder.restoreCallingIdentity(origId);
2766 }
2767 }
2768
2769 public int getRequestedOrientation(IBinder token) {
2770 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002771 ActivityRecord r = mMainStack.isInStackLocked(token);
2772 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2774 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002775 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
2777 }
2778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 /**
2780 * This is the internal entry point for handling Activity.finish().
2781 *
2782 * @param token The Binder token referencing the Activity we want to finish.
2783 * @param resultCode Result code, if any, from this Activity.
2784 * @param resultData Result data (Intent), if any, from this Activity.
2785 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002786 * @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 -08002787 */
2788 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2789 // Refuse possible leaked file descriptors
2790 if (resultData != null && resultData.hasFileDescriptors() == true) {
2791 throw new IllegalArgumentException("File descriptors passed in Intent");
2792 }
2793
2794 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002795 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002797 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002798 if (next != null) {
2799 // ask watcher if this is allowed
2800 boolean resumeOK = true;
2801 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002802 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002804 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 }
2806
2807 if (!resumeOK) {
2808 return false;
2809 }
2810 }
2811 }
2812 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002813 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002814 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 Binder.restoreCallingIdentity(origId);
2816 return res;
2817 }
2818 }
2819
Dianne Hackborn860755f2010-06-03 18:47:52 -07002820 public final void finishHeavyWeightApp() {
2821 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2822 != PackageManager.PERMISSION_GRANTED) {
2823 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2824 + Binder.getCallingPid()
2825 + ", uid=" + Binder.getCallingUid()
2826 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2827 Slog.w(TAG, msg);
2828 throw new SecurityException(msg);
2829 }
2830
2831 synchronized(this) {
2832 if (mHeavyWeightProcess == null) {
2833 return;
2834 }
2835
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002836 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002837 mHeavyWeightProcess.activities);
2838 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002839 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002840 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002841 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002842 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002843 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002844 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002845 }
2846 }
2847 }
2848
Dianne Hackborn41203752012-08-31 14:05:51 -07002849 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2850 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002851 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002852 }
2853 }
2854
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002855 public void crashApplication(int uid, int initialPid, String packageName,
2856 String message) {
2857 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2858 != PackageManager.PERMISSION_GRANTED) {
2859 String msg = "Permission Denial: crashApplication() from pid="
2860 + Binder.getCallingPid()
2861 + ", uid=" + Binder.getCallingUid()
2862 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2863 Slog.w(TAG, msg);
2864 throw new SecurityException(msg);
2865 }
2866
2867 synchronized(this) {
2868 ProcessRecord proc = null;
2869
2870 // Figure out which process to kill. We don't trust that initialPid
2871 // still has any relation to current pids, so must scan through the
2872 // list.
2873 synchronized (mPidsSelfLocked) {
2874 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2875 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002876 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002877 continue;
2878 }
2879 if (p.pid == initialPid) {
2880 proc = p;
2881 break;
2882 }
2883 for (String str : p.pkgList) {
2884 if (str.equals(packageName)) {
2885 proc = p;
2886 }
2887 }
2888 }
2889 }
2890
2891 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002892 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002893 + " initialPid=" + initialPid
2894 + " packageName=" + packageName);
2895 return;
2896 }
2897
2898 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002899 if (proc.pid == Process.myPid()) {
2900 Log.w(TAG, "crashApplication: trying to crash self!");
2901 return;
2902 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002903 long ident = Binder.clearCallingIdentity();
2904 try {
2905 proc.thread.scheduleCrash(message);
2906 } catch (RemoteException e) {
2907 }
2908 Binder.restoreCallingIdentity(ident);
2909 }
2910 }
2911 }
2912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 public final void finishSubActivity(IBinder token, String resultWho,
2914 int requestCode) {
2915 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002917 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 Binder.restoreCallingIdentity(origId);
2919 }
2920 }
2921
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002922 public boolean finishActivityAffinity(IBinder token) {
2923 synchronized(this) {
2924 final long origId = Binder.clearCallingIdentity();
2925 boolean res = mMainStack.finishActivityAffinityLocked(token);
2926 Binder.restoreCallingIdentity(origId);
2927 return res;
2928 }
2929 }
2930
Craig Mautnercae015f2013-02-08 14:31:27 -08002931 @Override
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002932 public boolean willActivityBeVisible(IBinder token) {
2933 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08002934 return mMainStack.willActivityBeVisibleLocked(token);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002935 }
2936 }
Craig Mautnercae015f2013-02-08 14:31:27 -08002937
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002938 public void overridePendingTransition(IBinder token, String packageName,
2939 int enterAnim, int exitAnim) {
2940 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002941 ActivityRecord self = mMainStack.isInStackLocked(token);
2942 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002943 return;
2944 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002945
2946 final long origId = Binder.clearCallingIdentity();
2947
2948 if (self.state == ActivityState.RESUMED
2949 || self.state == ActivityState.PAUSING) {
2950 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002951 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002952 }
2953
2954 Binder.restoreCallingIdentity(origId);
2955 }
2956 }
2957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 * Main function for removing an existing process from the activity manager
2960 * as a result of that process going away. Clears out all connections
2961 * to the process.
2962 */
2963 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002964 boolean restarting, boolean allowRestart) {
2965 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002967 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 }
2969
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002970 if (mProfileProc == app) {
2971 clearProfilerLocked();
2972 }
2973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002975 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002976 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2977 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002978 mMainStack.mPausingActivity = null;
2979 }
2980 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2981 mMainStack.mLastPausedActivity = null;
2982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983
2984 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002985 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986
2987 app.activities.clear();
2988
2989 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002990 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 + " running instrumentation " + app.instrumentationClass);
2992 Bundle info = new Bundle();
2993 info.putString("shortMsg", "Process crashed.");
2994 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2995 }
2996
2997 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002998 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 // If there was nothing to resume, and we are not already
3000 // restarting this process, but there is a visible activity that
3001 // is hosted by the process... then make sure all visible
3002 // activities are running, taking care of restarting this
3003 // process.
3004 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
3007 }
3008 }
3009 }
3010
3011 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3012 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003014 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3015 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3017 return i;
3018 }
3019 }
3020 return -1;
3021 }
3022
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003023 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 IApplicationThread thread) {
3025 if (thread == null) {
3026 return null;
3027 }
3028
3029 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003030 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003033 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 IApplicationThread thread) {
3035
3036 mProcDeaths[0]++;
3037
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003038 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3039 synchronized (stats) {
3040 stats.noteProcessDiedLocked(app.info.uid, pid);
3041 }
3042
Magnus Edlund7bb25812010-02-24 15:45:06 +01003043 // Clean up already done if the process has been re-started.
3044 if (app.pid == pid && app.thread != null &&
3045 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003046 if (!app.killedBackground) {
3047 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3048 + ") has died.");
3049 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003050 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003051 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 TAG, "Dying app: " + app + ", pid: " + pid
3053 + ", thread: " + thread.asBinder());
3054 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003055 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056
3057 if (doLowMem) {
3058 // If there are no longer any background processes running,
3059 // and the app that died was not running instrumentation,
3060 // then tell everyone we are now low on memory.
3061 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003062 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3063 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003064 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 haveBg = true;
3066 break;
3067 }
3068 }
3069
3070 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003071 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003072 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003073 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3074 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003075 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003076 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3077 // The low memory report is overriding any current
3078 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003079 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003080 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003081 rec.lastRequestedGc = 0;
3082 } else {
3083 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003085 rec.reportLowMemory = true;
3086 rec.lastLowMemory = now;
3087 mProcessesToGc.remove(rec);
3088 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 }
3090 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003091 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003092 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
3094 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003095 } else if (app.pid != pid) {
3096 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003097 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003098 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003099 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003100 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003101 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 + thread.asBinder());
3103 }
3104 }
3105
Dan Egnor42471dd2010-01-07 17:25:22 -08003106 /**
3107 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003108 * @param clearTraces causes the dump file to be erased prior to the new
3109 * traces being written, if true; when false, the new traces will be
3110 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003111 * @param firstPids of dalvik VM processes to dump stack traces for first
3112 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003113 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 * @return file containing stack traces, or null if no dump file is configured
3115 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003116 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003117 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003118 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3119 if (tracesPath == null || tracesPath.length() == 0) {
3120 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003122
3123 File tracesFile = new File(tracesPath);
3124 try {
3125 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003126 if (!tracesDir.exists()) {
3127 tracesFile.mkdirs();
3128 if (!SELinux.restorecon(tracesDir)) {
3129 return null;
3130 }
3131 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003132 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3133
Christopher Tate6ee412d2010-05-28 12:01:56 -07003134 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003135 tracesFile.createNewFile();
3136 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3137 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003138 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003139 return null;
3140 }
3141
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003142 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003143 return tracesFile;
3144 }
3145
3146 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003147 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 // Use a FileObserver to detect when traces finish writing.
3149 // The order of traces is considered important to maintain for legibility.
3150 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3151 public synchronized void onEvent(int event, String path) { notify(); }
3152 };
3153
3154 try {
3155 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003156
3157 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003158 if (firstPids != null) {
3159 try {
3160 int num = firstPids.size();
3161 for (int i = 0; i < num; i++) {
3162 synchronized (observer) {
3163 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3164 observer.wait(200); // Wait for write-close, give up after 200msec
3165 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003166 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003167 } catch (InterruptedException e) {
3168 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003169 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003170 }
3171
3172 // Next measure CPU usage.
3173 if (processStats != null) {
3174 processStats.init();
3175 System.gc();
3176 processStats.update();
3177 try {
3178 synchronized (processStats) {
3179 processStats.wait(500); // measure over 1/2 second.
3180 }
3181 } catch (InterruptedException e) {
3182 }
3183 processStats.update();
3184
3185 // We'll take the stack crawls of just the top apps using CPU.
3186 final int N = processStats.countWorkingStats();
3187 int numProcs = 0;
3188 for (int i=0; i<N && numProcs<5; i++) {
3189 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3190 if (lastPids.indexOfKey(stats.pid) >= 0) {
3191 numProcs++;
3192 try {
3193 synchronized (observer) {
3194 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3195 observer.wait(200); // Wait for write-close, give up after 200msec
3196 }
3197 } catch (InterruptedException e) {
3198 Log.wtf(TAG, e);
3199 }
3200
3201 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003202 }
3203 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003204
Dan Egnor42471dd2010-01-07 17:25:22 -08003205 } finally {
3206 observer.stopWatching();
3207 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003208
3209 if (nativeProcs != null) {
3210 int[] pids = Process.getPidsForCommands(nativeProcs);
3211 if (pids != null) {
3212 for (int pid : pids) {
3213 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3214 }
3215 }
3216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003217 }
3218
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003219 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003220 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003221 return;
3222 }
3223 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3224 if (tracesPath == null || tracesPath.length() == 0) {
3225 return;
3226 }
3227
3228 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3229 StrictMode.allowThreadDiskWrites();
3230 try {
3231 final File tracesFile = new File(tracesPath);
3232 final File tracesDir = tracesFile.getParentFile();
3233 final File tracesTmp = new File(tracesDir, "__tmp__");
3234 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003235 if (!tracesDir.exists()) {
3236 tracesFile.mkdirs();
3237 if (!SELinux.restorecon(tracesDir.getPath())) {
3238 return;
3239 }
3240 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003241 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3242
3243 if (tracesFile.exists()) {
3244 tracesTmp.delete();
3245 tracesFile.renameTo(tracesTmp);
3246 }
3247 StringBuilder sb = new StringBuilder();
3248 Time tobj = new Time();
3249 tobj.set(System.currentTimeMillis());
3250 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3251 sb.append(": ");
3252 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3253 sb.append(" since ");
3254 sb.append(msg);
3255 FileOutputStream fos = new FileOutputStream(tracesFile);
3256 fos.write(sb.toString().getBytes());
3257 if (app == null) {
3258 fos.write("\n*** No application process!".getBytes());
3259 }
3260 fos.close();
3261 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3262 } catch (IOException e) {
3263 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3264 return;
3265 }
3266
3267 if (app != null) {
3268 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3269 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003270 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003271 }
3272
3273 File lastTracesFile = null;
3274 File curTracesFile = null;
3275 for (int i=9; i>=0; i--) {
3276 String name = String.format("slow%02d.txt", i);
3277 curTracesFile = new File(tracesDir, name);
3278 if (curTracesFile.exists()) {
3279 if (lastTracesFile != null) {
3280 curTracesFile.renameTo(lastTracesFile);
3281 } else {
3282 curTracesFile.delete();
3283 }
3284 }
3285 lastTracesFile = curTracesFile;
3286 }
3287 tracesFile.renameTo(curTracesFile);
3288 if (tracesTmp.exists()) {
3289 tracesTmp.renameTo(tracesFile);
3290 }
3291 } finally {
3292 StrictMode.setThreadPolicy(oldPolicy);
3293 }
3294 }
3295
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003296 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003297 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003298 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3299 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3300
Dianne Hackborn287952c2010-09-22 22:34:31 -07003301 if (mController != null) {
3302 try {
3303 // 0 == continue, -1 = kill process immediately
3304 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3305 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3306 } catch (RemoteException e) {
3307 mController = null;
3308 }
3309 }
3310
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003311 long anrTime = SystemClock.uptimeMillis();
3312 if (MONITOR_CPU_USAGE) {
3313 updateCpuStatsNow();
3314 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003315
3316 synchronized (this) {
3317 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3318 if (mShuttingDown) {
3319 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3320 return;
3321 } else if (app.notResponding) {
3322 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3323 return;
3324 } else if (app.crashing) {
3325 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3326 return;
3327 }
3328
3329 // In case we come through here for the same app before completing
3330 // this one, mark as anring now so we will bail out.
3331 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003332
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003333 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003334 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3335 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003336
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003337 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003338 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003339
3340 int parentPid = app.pid;
3341 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003342 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003343
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003344 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003345
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003346 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3347 ProcessRecord r = mLruProcesses.get(i);
3348 if (r != null && r.thread != null) {
3349 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003350 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3351 if (r.persistent) {
3352 firstPids.add(pid);
3353 } else {
3354 lastPids.put(pid, Boolean.TRUE);
3355 }
3356 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 }
3359 }
3360
Dan Egnor42471dd2010-01-07 17:25:22 -08003361 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003362 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003363 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003364 info.append("ANR in ").append(app.processName);
3365 if (activity != null && activity.shortComponentName != null) {
3366 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003367 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003368 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003370 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003372 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003373 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375
Dianne Hackborn287952c2010-09-22 22:34:31 -07003376 final ProcessStats processStats = new ProcessStats(true);
3377
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003378 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003379
Dan Egnor42471dd2010-01-07 17:25:22 -08003380 String cpuInfo = null;
3381 if (MONITOR_CPU_USAGE) {
3382 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003383 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003384 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003385 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003386 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003387 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 }
3389
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003390 info.append(processStats.printCurrentState(anrTime));
3391
Joe Onorato8a9b2202010-02-26 18:56:32 -08003392 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003393 if (tracesFile == null) {
3394 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3395 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3396 }
3397
Jeff Sharkeya353d262011-10-28 11:12:06 -07003398 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3399 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003400
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003401 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003403 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3404 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003406 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3407 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
3409 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003410 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 }
3412 }
3413
Dan Egnor42471dd2010-01-07 17:25:22 -08003414 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3415 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3416 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003417
3418 synchronized (this) {
3419 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003420 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003421 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003422 app.processName, app.setAdj, "background ANR");
3423 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003424 return;
3425 }
3426
3427 // Set the app's notResponding state, and look up the errorReportReceiver
3428 makeAppNotRespondingLocked(app,
3429 activity != null ? activity.shortComponentName : null,
3430 annotation != null ? "ANR " + annotation : "ANR",
3431 info.toString());
3432
3433 // Bring up the infamous App Not Responding dialog
3434 Message msg = Message.obtain();
3435 HashMap map = new HashMap();
3436 msg.what = SHOW_NOT_RESPONDING_MSG;
3437 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003438 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003439 map.put("app", app);
3440 if (activity != null) {
3441 map.put("activity", activity);
3442 }
3443
3444 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 }
3447
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003448 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3449 if (!mLaunchWarningShown) {
3450 mLaunchWarningShown = true;
3451 mHandler.post(new Runnable() {
3452 @Override
3453 public void run() {
3454 synchronized (ActivityManagerService.this) {
3455 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3456 d.show();
3457 mHandler.postDelayed(new Runnable() {
3458 @Override
3459 public void run() {
3460 synchronized (ActivityManagerService.this) {
3461 d.dismiss();
3462 mLaunchWarningShown = false;
3463 }
3464 }
3465 }, 4000);
3466 }
3467 }
3468 });
3469 }
3470 }
3471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003473 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003474 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 int uid = Binder.getCallingUid();
3476 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003477 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003478 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 long callingId = Binder.clearCallingIdentity();
3480 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003481 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 int pkgUid = -1;
3483 synchronized(this) {
3484 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003485 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 } catch (RemoteException e) {
3487 }
3488 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003489 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 return false;
3491 }
3492 if (uid == pkgUid || checkComponentPermission(
3493 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003494 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003496 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 } else {
3498 throw new SecurityException(pid+" does not have permission:"+
3499 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3500 "for process:"+packageName);
3501 }
3502 }
3503
3504 try {
3505 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003506 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3508 Uri.fromParts("package", packageName, null));
3509 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003510 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003511 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 } catch (RemoteException e) {
3513 }
3514 } finally {
3515 Binder.restoreCallingIdentity(callingId);
3516 }
3517 return true;
3518 }
3519
Dianne Hackborn1676c852012-09-10 14:52:30 -07003520 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003521 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3522 != PackageManager.PERMISSION_GRANTED &&
3523 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3524 != PackageManager.PERMISSION_GRANTED) {
3525 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 + Binder.getCallingPid()
3527 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003528 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003529 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 throw new SecurityException(msg);
3531 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003532
Dianne Hackborn139748f2012-09-24 11:36:57 -07003533 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003534 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 long callingId = Binder.clearCallingIdentity();
3536 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003537 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003539 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003541 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 } catch (RemoteException e) {
3543 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003544 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003545 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 return;
3547 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003548 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003549 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3550 }
3551 } finally {
3552 Binder.restoreCallingIdentity(callingId);
3553 }
3554 }
3555
3556 public void killAllBackgroundProcesses() {
3557 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3558 != PackageManager.PERMISSION_GRANTED) {
3559 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3560 + Binder.getCallingPid()
3561 + ", uid=" + Binder.getCallingUid()
3562 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3563 Slog.w(TAG, msg);
3564 throw new SecurityException(msg);
3565 }
3566
3567 long callingId = Binder.clearCallingIdentity();
3568 try {
3569 synchronized(this) {
3570 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3571 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3572 final int NA = apps.size();
3573 for (int ia=0; ia<NA; ia++) {
3574 ProcessRecord app = apps.valueAt(ia);
3575 if (app.persistent) {
3576 // we don't kill persistent processes
3577 continue;
3578 }
3579 if (app.removed) {
3580 procs.add(app);
3581 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3582 app.removed = true;
3583 procs.add(app);
3584 }
3585 }
3586 }
3587
3588 int N = procs.size();
3589 for (int i=0; i<N; i++) {
3590 removeProcessLocked(procs.get(i), false, true, "kill all background");
3591 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003592 }
3593 } finally {
3594 Binder.restoreCallingIdentity(callingId);
3595 }
3596 }
3597
Dianne Hackborn1676c852012-09-10 14:52:30 -07003598 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003599 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3600 != PackageManager.PERMISSION_GRANTED) {
3601 String msg = "Permission Denial: forceStopPackage() from pid="
3602 + Binder.getCallingPid()
3603 + ", uid=" + Binder.getCallingUid()
3604 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003605 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003606 throw new SecurityException(msg);
3607 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003608 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003609 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003610 long callingId = Binder.clearCallingIdentity();
3611 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003612 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003614 int[] users = userId == UserHandle.USER_ALL
3615 ? getUsersLocked() : new int[] { userId };
3616 for (int user : users) {
3617 int pkgUid = -1;
3618 try {
3619 pkgUid = pm.getPackageUid(packageName, user);
3620 } catch (RemoteException e) {
3621 }
3622 if (pkgUid == -1) {
3623 Slog.w(TAG, "Invalid packageName: " + packageName);
3624 continue;
3625 }
3626 try {
3627 pm.setPackageStoppedState(packageName, true, user);
3628 } catch (RemoteException e) {
3629 } catch (IllegalArgumentException e) {
3630 Slog.w(TAG, "Failed trying to unstop package "
3631 + packageName + ": " + e);
3632 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003633 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003634 forceStopPackageLocked(packageName, pkgUid);
3635 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
3638 } finally {
3639 Binder.restoreCallingIdentity(callingId);
3640 }
3641 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003642
3643 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003644 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003645 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003646 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003647 if (pkg == null) {
3648 return;
3649 }
3650 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003651 if (appid < 0) {
3652 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003653 return;
3654 }
3655 int callerUid = Binder.getCallingUid();
3656 // Only the system server can kill an application
3657 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003658 // Post an aysnc message to kill the application
3659 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003660 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003661 msg.arg2 = 0;
3662 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003663 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003664 } else {
3665 throw new SecurityException(callerUid + " cannot kill pkg: " +
3666 pkg);
3667 }
3668 }
3669
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003670 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003671 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003672
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003673 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003674 final int uid = Binder.getCallingUid();
3675 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003676 try {
3677 synchronized (this) {
3678 // Only allow this from foreground processes, so that background
3679 // applications can't abuse it to prevent system UI from being shown.
3680 if (uid >= Process.FIRST_APPLICATION_UID) {
3681 ProcessRecord proc;
3682 synchronized (mPidsSelfLocked) {
3683 proc = mPidsSelfLocked.get(pid);
3684 }
3685 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3686 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3687 + " from background process " + proc);
3688 return;
3689 }
3690 }
3691 closeSystemDialogsLocked(reason);
3692 }
3693 } finally {
3694 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003695 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003696 }
3697
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003698 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003699 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003700 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3701 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003702 if (reason != null) {
3703 intent.putExtra("reason", reason);
3704 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003705 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003706
Craig Mautnercae015f2013-02-08 14:31:27 -08003707 mMainStack.closeSystemDialogsLocked();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003708
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003709 broadcastIntentLocked(null, null, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003710 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003711 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003712 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003713
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003714 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003715 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003716 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003717 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3718 for (int i=pids.length-1; i>=0; i--) {
3719 infos[i] = new Debug.MemoryInfo();
3720 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003721 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003722 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003723 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003724
Dianne Hackbornb437e092011-08-05 17:50:29 -07003725 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003726 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003727 long[] pss = new long[pids.length];
3728 for (int i=pids.length-1; i>=0; i--) {
3729 pss[i] = Debug.getPss(pids[i]);
3730 }
3731 return pss;
3732 }
3733
Christopher Tate5e1ab332009-09-01 20:32:49 -07003734 public void killApplicationProcess(String processName, int uid) {
3735 if (processName == null) {
3736 return;
3737 }
3738
3739 int callerUid = Binder.getCallingUid();
3740 // Only the system server can kill an application
3741 if (callerUid == Process.SYSTEM_UID) {
3742 synchronized (this) {
3743 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003744 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003745 try {
3746 app.thread.scheduleSuicide();
3747 } catch (RemoteException e) {
3748 // If the other end already died, then our work here is done.
3749 }
3750 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003751 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003752 + processName + " / " + uid);
3753 }
3754 }
3755 } else {
3756 throw new SecurityException(callerUid + " cannot kill app process: " +
3757 processName);
3758 }
3759 }
3760
Dianne Hackborn03abb812010-01-04 18:43:19 -08003761 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003762 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3763 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3765 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003766 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003767 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3768 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003771 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003772 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003773 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -07003774 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003775 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003777
3778 private void forceStopUserLocked(int userId) {
3779 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3780 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003781 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3782 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003783 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3784 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003785 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003786 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003787 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003788 }
3789
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003790 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003791 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3792 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003793 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794
Dianne Hackborn03abb812010-01-04 18:43:19 -08003795 // Remove all processes this package may have touched: all with the
3796 // same UID (except for the system or root user), and all whose name
3797 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003798 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003799 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3800 final int NA = apps.size();
3801 for (int ia=0; ia<NA; ia++) {
3802 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003803 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003804 // we don't kill persistent processes
3805 continue;
3806 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003807 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003808 if (doit) {
3809 procs.add(app);
3810 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003811 continue;
3812 }
3813
3814 // Skip process if it doesn't meet our oom adj requirement.
3815 if (app.setAdj < minOomAdj) {
3816 continue;
3817 }
3818
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003819 // If no package is specified, we call all processes under the
3820 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003821 if (packageName == null) {
3822 if (app.userId != userId) {
3823 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003824 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003825 // Package has been specified, we want to hit all processes
3826 // that match it. We need to qualify this by the processes
3827 // that are running under the specified app and user ID.
3828 } else {
3829 if (UserHandle.getAppId(app.uid) != appId) {
3830 continue;
3831 }
3832 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3833 continue;
3834 }
3835 if (!app.pkgList.contains(packageName)) {
3836 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003837 }
3838 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003839
3840 // Process has passed all conditions, kill it!
3841 if (!doit) {
3842 return true;
3843 }
3844 app.removed = true;
3845 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003846 }
3847 }
3848
3849 int N = procs.size();
3850 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003851 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003852 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003853 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003854 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003855
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003856 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003857 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003858 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003859 int i;
3860 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003862 if (userId == UserHandle.USER_ALL && name == null) {
3863 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3864 }
3865
3866 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003868 appId = UserHandle.getAppId(
3869 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 } catch (RemoteException e) {
3871 }
3872 }
3873
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003874 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003875 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003876 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3877 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003878 } else {
3879 Slog.i(TAG, "Force stopping user " + userId);
3880 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003881
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003882 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3883 while (badApps.hasNext()) {
3884 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003885 for (i=ba.size()-1; i>=0; i--) {
3886 boolean remove = false;
3887 final int entUid = ba.keyAt(i);
3888 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003889 if (userId == UserHandle.USER_ALL) {
3890 if (UserHandle.getAppId(entUid) == appId) {
3891 remove = true;
3892 }
3893 } else {
3894 if (entUid == UserHandle.getUid(userId, appId)) {
3895 remove = true;
3896 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003897 }
3898 } else if (UserHandle.getUserId(entUid) == userId) {
3899 remove = true;
3900 }
3901 if (remove) {
3902 ba.removeAt(i);
3903 }
3904 }
3905 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003906 badApps.remove();
3907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003910
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003911 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003912 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003913 name == null ? ("force stop user " + userId) : ("force stop " + name));
Craig Mautnercae015f2013-02-08 14:31:27 -08003914
3915 if (mMainStack.forceStopPackageLocked(name, doit, evenPersistent, userId)) {
3916 if (!doit) {
3917 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003919 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003922 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3923 if (!doit) {
3924 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003926 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003928
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003929 if (name == null) {
3930 // Remove all sticky broadcasts from this user.
3931 mStickyBroadcasts.remove(userId);
3932 }
3933
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003934 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003935 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3936 userId, providers)) {
3937 if (!doit) {
3938 return true;
3939 }
3940 didSomething = true;
3941 }
3942 N = providers.size();
3943 for (i=0; i<N; i++) {
3944 removeDyingProviderLocked(null, providers.get(i), true);
3945 }
3946
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003947 if (name == null) {
3948 // Remove pending intents. For now we only do this when force
3949 // stopping users, because we have some problems when doing this
3950 // for packages -- app widgets are not currently cleaned up for
3951 // such packages, so they can be left with bad pending intents.
3952 if (mIntentSenderRecords.size() > 0) {
3953 Iterator<WeakReference<PendingIntentRecord>> it
3954 = mIntentSenderRecords.values().iterator();
3955 while (it.hasNext()) {
3956 WeakReference<PendingIntentRecord> wpir = it.next();
3957 if (wpir == null) {
3958 it.remove();
3959 continue;
3960 }
3961 PendingIntentRecord pir = wpir.get();
3962 if (pir == null) {
3963 it.remove();
3964 continue;
3965 }
3966 if (name == null) {
3967 // Stopping user, remove all objects for the user.
3968 if (pir.key.userId != userId) {
3969 // Not the same user, skip it.
3970 continue;
3971 }
3972 } else {
3973 if (UserHandle.getAppId(pir.uid) != appId) {
3974 // Different app id, skip it.
3975 continue;
3976 }
3977 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3978 // Different user, skip it.
3979 continue;
3980 }
3981 if (!pir.key.packageName.equals(name)) {
3982 // Different package, skip it.
3983 continue;
3984 }
3985 }
3986 if (!doit) {
3987 return true;
3988 }
3989 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003990 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003991 pir.canceled = true;
3992 if (pir.key.activity != null) {
3993 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003994 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003995 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003996 }
3997 }
3998
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003999 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004000 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004001 AttributeCache ac = AttributeCache.instance();
4002 if (ac != null) {
4003 ac.removePackage(name);
4004 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004005 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004006 if (mBooted) {
4007 mMainStack.resumeTopActivityLocked(null);
4008 mMainStack.scheduleIdleLocked();
4009 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004010 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004011
4012 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
4014
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004015 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004016 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004018 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004019 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004020 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 + "/" + uid + ")");
4022
4023 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004024 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004025 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004026 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4027 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004028 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 boolean needRestart = false;
4031 if (app.pid > 0 && app.pid != MY_PID) {
4032 int pid = app.pid;
4033 synchronized (mPidsSelfLocked) {
4034 mPidsSelfLocked.remove(pid);
4035 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4036 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004037 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004038 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004039 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004040 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004042 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004044 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 } else {
4046 needRestart = true;
4047 }
4048 }
4049 } else {
4050 mRemovedProcesses.add(app);
4051 }
4052
4053 return needRestart;
4054 }
4055
4056 private final void processStartTimedOutLocked(ProcessRecord app) {
4057 final int pid = app.pid;
4058 boolean gone = false;
4059 synchronized (mPidsSelfLocked) {
4060 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4061 if (knownApp != null && knownApp.thread == null) {
4062 mPidsSelfLocked.remove(pid);
4063 gone = true;
4064 }
4065 }
4066
4067 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004068 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004069 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4070 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004071 mProcessNames.remove(app.processName, app.uid);
4072 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004073 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004074 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4075 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004076 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004077 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004078 // Take care of any launching providers waiting for this process.
4079 checkAppInLaunchingProvidersLocked(app, true);
4080 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004081 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004082 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004083 app.processName, app.setAdj, "start timeout");
4084 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004085 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004086 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004087 try {
4088 IBackupManager bm = IBackupManager.Stub.asInterface(
4089 ServiceManager.getService(Context.BACKUP_SERVICE));
4090 bm.agentDisconnected(app.info.packageName);
4091 } catch (RemoteException e) {
4092 // Can't happen; the backup manager is local
4093 }
4094 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004095 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004096 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004097 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004100 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 }
4102 }
4103
4104 private final boolean attachApplicationLocked(IApplicationThread thread,
4105 int pid) {
4106
4107 // Find the application record that is being attached... either via
4108 // the pid if we are running in multiple processes, or just pull the
4109 // next app record if we are emulating process with anonymous threads.
4110 ProcessRecord app;
4111 if (pid != MY_PID && pid >= 0) {
4112 synchronized (mPidsSelfLocked) {
4113 app = mPidsSelfLocked.get(pid);
4114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 } else {
4116 app = null;
4117 }
4118
4119 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004120 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004122 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004124 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 } else {
4126 try {
4127 thread.scheduleExit();
4128 } catch (Exception e) {
4129 // Ignore exceptions.
4130 }
4131 }
4132 return false;
4133 }
4134
4135 // If this application record is still attached to a previous
4136 // process, clean it up now.
4137 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004138 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
4140
4141 // Tell the process all about itself.
4142
Joe Onorato8a9b2202010-02-26 18:56:32 -08004143 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 TAG, "Binding process pid " + pid + " to record " + app);
4145
4146 String processName = app.processName;
4147 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004148 AppDeathRecipient adr = new AppDeathRecipient(
4149 app, pid, thread);
4150 thread.asBinder().linkToDeath(adr, 0);
4151 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 } catch (RemoteException e) {
4153 app.resetPackageList();
4154 startProcessLocked(app, "link fail", processName);
4155 return false;
4156 }
4157
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004158 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159
4160 app.thread = thread;
4161 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004162 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4163 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 app.forcingToForeground = null;
4165 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004166 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 app.debugging = false;
4168
4169 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4170
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004171 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004172 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004174 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004175 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 }
4177
Joe Onorato8a9b2202010-02-26 18:56:32 -08004178 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 TAG, "New app record " + app
4180 + " thread=" + thread.asBinder() + " pid=" + pid);
4181 try {
4182 int testMode = IApplicationThread.DEBUG_OFF;
4183 if (mDebugApp != null && mDebugApp.equals(processName)) {
4184 testMode = mWaitForDebugger
4185 ? IApplicationThread.DEBUG_WAIT
4186 : IApplicationThread.DEBUG_ON;
4187 app.debugging = true;
4188 if (mDebugTransient) {
4189 mDebugApp = mOrigDebugApp;
4190 mWaitForDebugger = mOrigWaitForDebugger;
4191 }
4192 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004193 String profileFile = app.instrumentationProfileFile;
4194 ParcelFileDescriptor profileFd = null;
4195 boolean profileAutoStop = false;
4196 if (mProfileApp != null && mProfileApp.equals(processName)) {
4197 mProfileProc = app;
4198 profileFile = mProfileFile;
4199 profileFd = mProfileFd;
4200 profileAutoStop = mAutoStopProfiler;
4201 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004202 boolean enableOpenGlTrace = false;
4203 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4204 enableOpenGlTrace = true;
4205 mOpenGlTraceApp = null;
4206 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004207
Christopher Tate181fafa2009-05-14 11:12:14 -07004208 // If the app is being launched for restore or full backup, set it up specially
4209 boolean isRestrictedBackupMode = false;
4210 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4211 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004212 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004213 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4214 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004216 ensurePackageDexOpt(app.instrumentationInfo != null
4217 ? app.instrumentationInfo.packageName
4218 : app.info.packageName);
4219 if (app.instrumentationClass != null) {
4220 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004221 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004222 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004223 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004224 ApplicationInfo appInfo = app.instrumentationInfo != null
4225 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004226 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004227 if (profileFd != null) {
4228 profileFd = profileFd.dup();
4229 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004230 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004231 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08004232 app.instrumentationArguments, app.instrumentationWatcher,
4233 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
4234 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004235 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004236 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004237 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004238 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 } catch (Exception e) {
4240 // todo: Yikes! What should we do? For now we will try to
4241 // start another process, but that could easily get us in
4242 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004243 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244
4245 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004246 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 startProcessLocked(app, "bind fail", processName);
4248 return false;
4249 }
4250
4251 // Remove this record from the list of starting applications.
4252 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004253 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4254 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 mProcessesOnHold.remove(app);
4256
4257 boolean badApp = false;
4258 boolean didSomething = false;
4259
4260 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004261 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004262 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004263 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 && processName.equals(hr.processName)) {
4265 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004266 if (mHeadless) {
4267 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4268 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 didSomething = true;
4270 }
4271 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004272 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 + hr.intent.getComponent().flattenToShortString(), e);
4274 badApp = true;
4275 }
4276 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004277 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
4279 }
4280
4281 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004282 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004284 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 badApp = true;
4287 }
4288 }
4289
Christopher Tatef46723b2012-01-26 14:19:24 -08004290 // Check if a next-broadcast receiver is in this process...
4291 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004293 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004295 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 }
4298 }
4299
Christopher Tate181fafa2009-05-14 11:12:14 -07004300 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004301 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004302 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004303 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004304 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004305 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4306 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4307 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004308 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004309 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004310 e.printStackTrace();
4311 }
4312 }
4313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 if (badApp) {
4315 // todo: Also need to kill application to deal with all
4316 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004317 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 return false;
4319 }
4320
4321 if (!didSomething) {
4322 updateOomAdjLocked();
4323 }
4324
4325 return true;
4326 }
4327
4328 public final void attachApplication(IApplicationThread thread) {
4329 synchronized (this) {
4330 int callingPid = Binder.getCallingPid();
4331 final long origId = Binder.clearCallingIdentity();
4332 attachApplicationLocked(thread, callingPid);
4333 Binder.restoreCallingIdentity(origId);
4334 }
4335 }
4336
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004337 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004339 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4340 if (stopProfiling) {
4341 synchronized (this) {
4342 if (mProfileProc == r.app) {
4343 if (mProfileFd != null) {
4344 try {
4345 mProfileFd.close();
4346 } catch (IOException e) {
4347 }
4348 clearProfilerLocked();
4349 }
4350 }
4351 }
4352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 Binder.restoreCallingIdentity(origId);
4354 }
4355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004357 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004358 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004360
4361 synchronized (this) {
4362 updateEventDispatchingLocked();
4363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364 }
4365
Dianne Hackborn661cd522011-08-22 00:26:20 -07004366 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004367 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004368 mWindowManager.showBootMessage(msg, always);
4369 }
4370
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004371 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004372 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004373 final long token = Binder.clearCallingIdentity();
4374 try {
4375 synchronized (this) {
4376 if (mLockScreenShown) {
4377 mLockScreenShown = false;
4378 comeOutOfSleepIfNeededLocked();
4379 }
4380 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004381 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004382 } finally {
4383 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004384 }
4385 }
4386
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004387 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004388 IntentFilter pkgFilter = new IntentFilter();
4389 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4390 pkgFilter.addDataScheme("package");
4391 mContext.registerReceiver(new BroadcastReceiver() {
4392 @Override
4393 public void onReceive(Context context, Intent intent) {
4394 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4395 if (pkgs != null) {
4396 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004397 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004398 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4399 setResultCode(Activity.RESULT_OK);
4400 return;
4401 }
4402 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004403 }
4404 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004405 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004406 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004407
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004408 synchronized (this) {
4409 // Ensure that any processes we had put on hold are now started
4410 // up.
4411 final int NP = mProcessesOnHold.size();
4412 if (NP > 0) {
4413 ArrayList<ProcessRecord> procs =
4414 new ArrayList<ProcessRecord>(mProcessesOnHold);
4415 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004416 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4417 + procs.get(ip));
4418 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004419 }
4420 }
4421
4422 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004423 // Start looking for apps that are abusing wake locks.
4424 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004425 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004426 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004427 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004428 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004429 for (int i=0; i<mStartedUsers.size(); i++) {
4430 UserStartedState uss = mStartedUsers.valueAt(i);
4431 if (uss.mState == UserStartedState.STATE_BOOTING) {
4432 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004433 final int userId = mStartedUsers.keyAt(i);
4434 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4435 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4436 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004437 null, null, 0, null, null,
4438 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08004439 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID,
4440 userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004441 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004442 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004443 }
4444 }
4445 }
4446
4447 final void ensureBootCompleted() {
4448 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004449 boolean enableScreen;
4450 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004451 booting = mBooting;
4452 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004453 enableScreen = !mBooted;
4454 mBooted = true;
4455 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004456
4457 if (booting) {
4458 finishBooting();
4459 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004460
4461 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004462 enableScreenAfterBoot();
4463 }
4464 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004465
4466 public final void activityResumed(IBinder token) {
4467 final long origId = Binder.clearCallingIdentity();
4468 mMainStack.activityResumed(token);
4469 Binder.restoreCallingIdentity(origId);
4470 }
4471
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004472 public final void activityPaused(IBinder token) {
4473 final long origId = Binder.clearCallingIdentity();
4474 mMainStack.activityPaused(token, false);
4475 Binder.restoreCallingIdentity(origId);
4476 }
4477
4478 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4479 CharSequence description) {
4480 if (localLOGV) Slog.v(
4481 TAG, "Activity stopped: token=" + token);
4482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 // Refuse possible leaked file descriptors
4484 if (icicle != null && icicle.hasFileDescriptors()) {
4485 throw new IllegalArgumentException("File descriptors passed in Bundle");
4486 }
4487
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004488 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489
4490 final long origId = Binder.clearCallingIdentity();
4491
4492 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004493 r = mMainStack.isInStackLocked(token);
4494 if (r != null) {
4495 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 }
4497 }
4498
4499 if (r != null) {
4500 sendPendingThumbnail(r, null, null, null, false);
4501 }
4502
4503 trimApplications();
4504
4505 Binder.restoreCallingIdentity(origId);
4506 }
4507
4508 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004509 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004510 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 }
4512
4513 public String getCallingPackage(IBinder token) {
4514 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004515 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004516 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 }
4518 }
4519
4520 public ComponentName getCallingActivity(IBinder token) {
4521 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004522 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 return r != null ? r.intent.getComponent() : null;
4524 }
4525 }
4526
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004527 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004528 ActivityRecord r = mMainStack.isInStackLocked(token);
4529 if (r == null) {
4530 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004532 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
4534
4535 public ComponentName getActivityClassForToken(IBinder token) {
4536 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004537 ActivityRecord r = mMainStack.isInStackLocked(token);
4538 if (r == null) {
4539 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004541 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 }
4543 }
4544
4545 public String getPackageForToken(IBinder token) {
4546 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004547 ActivityRecord r = mMainStack.isInStackLocked(token);
4548 if (r == null) {
4549 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004551 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 }
4553 }
4554
4555 public IIntentSender getIntentSender(int type,
4556 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004557 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004558 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004559 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004561 if (intents != null) {
4562 if (intents.length < 1) {
4563 throw new IllegalArgumentException("Intents array length must be >= 1");
4564 }
4565 for (int i=0; i<intents.length; i++) {
4566 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004567 if (intent != null) {
4568 if (intent.hasFileDescriptors()) {
4569 throw new IllegalArgumentException("File descriptors passed in Intent");
4570 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004571 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004572 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4573 throw new IllegalArgumentException(
4574 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4575 }
4576 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004577 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004578 }
4579 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004580 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004581 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004582 }
4583 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004584 if (options != null) {
4585 if (options.hasFileDescriptors()) {
4586 throw new IllegalArgumentException("File descriptors passed in options");
4587 }
4588 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 synchronized(this) {
4591 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004592 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004593 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004594 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004595 "getIntentSender", null);
4596 if (origUserId == UserHandle.USER_CURRENT) {
4597 // We don't want to evaluate this until the pending intent is
4598 // actually executed. However, we do want to always do the
4599 // security checking for it above.
4600 userId = UserHandle.USER_CURRENT;
4601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004603 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004604 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004605 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4606 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 String msg = "Permission Denial: getIntentSender() from pid="
4608 + Binder.getCallingPid()
4609 + ", uid=" + Binder.getCallingUid()
4610 + ", (need uid=" + uid + ")"
4611 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004612 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 throw new SecurityException(msg);
4614 }
4615 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004616
4617 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004618 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 } catch (RemoteException e) {
4621 throw new SecurityException(e);
4622 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004623 }
4624 }
4625
Dianne Hackborn41203752012-08-31 14:05:51 -07004626 IIntentSender getIntentSenderLocked(int type, String packageName,
4627 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004628 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4629 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004630 if (DEBUG_MU)
4631 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004632 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004633 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004634 activity = mMainStack.isInStackLocked(token);
4635 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004636 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004638 if (activity.finishing) {
4639 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004641 }
4642
4643 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4644 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4645 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4646 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4647 |PendingIntent.FLAG_UPDATE_CURRENT);
4648
4649 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4650 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004651 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004652 WeakReference<PendingIntentRecord> ref;
4653 ref = mIntentSenderRecords.get(key);
4654 PendingIntentRecord rec = ref != null ? ref.get() : null;
4655 if (rec != null) {
4656 if (!cancelCurrent) {
4657 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004658 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004659 rec.key.requestIntent.replaceExtras(intents != null ?
4660 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004661 }
4662 if (intents != null) {
4663 intents[intents.length-1] = rec.key.requestIntent;
4664 rec.key.allIntents = intents;
4665 rec.key.allResolvedTypes = resolvedTypes;
4666 } else {
4667 rec.key.allIntents = null;
4668 rec.key.allResolvedTypes = null;
4669 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 return rec;
4672 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004673 rec.canceled = true;
4674 mIntentSenderRecords.remove(key);
4675 }
4676 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 return rec;
4678 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004679 rec = new PendingIntentRecord(this, key, callingUid);
4680 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004681 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004682 if (activity.pendingResults == null) {
4683 activity.pendingResults
4684 = new HashSet<WeakReference<PendingIntentRecord>>();
4685 }
4686 activity.pendingResults.add(rec.ref);
4687 }
4688 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 }
4690
4691 public void cancelIntentSender(IIntentSender sender) {
4692 if (!(sender instanceof PendingIntentRecord)) {
4693 return;
4694 }
4695 synchronized(this) {
4696 PendingIntentRecord rec = (PendingIntentRecord)sender;
4697 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004698 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004699 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4700 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 String msg = "Permission Denial: cancelIntentSender() from pid="
4702 + Binder.getCallingPid()
4703 + ", uid=" + Binder.getCallingUid()
4704 + " is not allowed to cancel packges "
4705 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004706 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004707 throw new SecurityException(msg);
4708 }
4709 } catch (RemoteException e) {
4710 throw new SecurityException(e);
4711 }
4712 cancelIntentSenderLocked(rec, true);
4713 }
4714 }
4715
4716 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4717 rec.canceled = true;
4718 mIntentSenderRecords.remove(rec.key);
4719 if (cleanActivity && rec.key.activity != null) {
4720 rec.key.activity.pendingResults.remove(rec.ref);
4721 }
4722 }
4723
4724 public String getPackageForIntentSender(IIntentSender pendingResult) {
4725 if (!(pendingResult instanceof PendingIntentRecord)) {
4726 return null;
4727 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004728 try {
4729 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4730 return res.key.packageName;
4731 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733 return null;
4734 }
4735
Christopher Tatec4a07d12012-04-06 14:19:13 -07004736 public int getUidForIntentSender(IIntentSender sender) {
4737 if (sender instanceof PendingIntentRecord) {
4738 try {
4739 PendingIntentRecord res = (PendingIntentRecord)sender;
4740 return res.uid;
4741 } catch (ClassCastException e) {
4742 }
4743 }
4744 return -1;
4745 }
4746
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004747 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4748 if (!(pendingResult instanceof PendingIntentRecord)) {
4749 return false;
4750 }
4751 try {
4752 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4753 if (res.key.allIntents == null) {
4754 return false;
4755 }
4756 for (int i=0; i<res.key.allIntents.length; i++) {
4757 Intent intent = res.key.allIntents[i];
4758 if (intent.getPackage() != null && intent.getComponent() != null) {
4759 return false;
4760 }
4761 }
4762 return true;
4763 } catch (ClassCastException e) {
4764 }
4765 return false;
4766 }
4767
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004768 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4769 if (!(pendingResult instanceof PendingIntentRecord)) {
4770 return false;
4771 }
4772 try {
4773 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4774 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4775 return true;
4776 }
4777 return false;
4778 } catch (ClassCastException e) {
4779 }
4780 return false;
4781 }
4782
Dianne Hackborn81038902012-11-26 17:04:09 -08004783 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4784 if (!(pendingResult instanceof PendingIntentRecord)) {
4785 return null;
4786 }
4787 try {
4788 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4789 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4790 } catch (ClassCastException e) {
4791 }
4792 return null;
4793 }
4794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 public void setProcessLimit(int max) {
4796 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4797 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004798 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004799 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004800 mProcessLimitOverride = max;
4801 }
4802 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803 }
4804
4805 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004806 synchronized (this) {
4807 return mProcessLimitOverride;
4808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004809 }
4810
4811 void foregroundTokenDied(ForegroundToken token) {
4812 synchronized (ActivityManagerService.this) {
4813 synchronized (mPidsSelfLocked) {
4814 ForegroundToken cur
4815 = mForegroundProcesses.get(token.pid);
4816 if (cur != token) {
4817 return;
4818 }
4819 mForegroundProcesses.remove(token.pid);
4820 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4821 if (pr == null) {
4822 return;
4823 }
4824 pr.forcingToForeground = null;
4825 pr.foregroundServices = false;
4826 }
4827 updateOomAdjLocked();
4828 }
4829 }
4830
4831 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4832 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4833 "setProcessForeground()");
4834 synchronized(this) {
4835 boolean changed = false;
4836
4837 synchronized (mPidsSelfLocked) {
4838 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004839 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004840 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 return;
4842 }
4843 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4844 if (oldToken != null) {
4845 oldToken.token.unlinkToDeath(oldToken, 0);
4846 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004847 if (pr != null) {
4848 pr.forcingToForeground = null;
4849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004850 changed = true;
4851 }
4852 if (isForeground && token != null) {
4853 ForegroundToken newToken = new ForegroundToken() {
4854 public void binderDied() {
4855 foregroundTokenDied(this);
4856 }
4857 };
4858 newToken.pid = pid;
4859 newToken.token = token;
4860 try {
4861 token.linkToDeath(newToken, 0);
4862 mForegroundProcesses.put(pid, newToken);
4863 pr.forcingToForeground = token;
4864 changed = true;
4865 } catch (RemoteException e) {
4866 // If the process died while doing this, we will later
4867 // do the cleanup with the process death link.
4868 }
4869 }
4870 }
4871
4872 if (changed) {
4873 updateOomAdjLocked();
4874 }
4875 }
4876 }
4877
4878 // =========================================================
4879 // PERMISSIONS
4880 // =========================================================
4881
4882 static class PermissionController extends IPermissionController.Stub {
4883 ActivityManagerService mActivityManagerService;
4884 PermissionController(ActivityManagerService activityManagerService) {
4885 mActivityManagerService = activityManagerService;
4886 }
4887
4888 public boolean checkPermission(String permission, int pid, int uid) {
4889 return mActivityManagerService.checkPermission(permission, pid,
4890 uid) == PackageManager.PERMISSION_GRANTED;
4891 }
4892 }
4893
4894 /**
4895 * This can be called with or without the global lock held.
4896 */
4897 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004898 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 // We might be performing an operation on behalf of an indirect binder
4900 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4901 // client identity accordingly before proceeding.
4902 Identity tlsIdentity = sCallerIdentity.get();
4903 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004904 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4906 uid = tlsIdentity.uid;
4907 pid = tlsIdentity.pid;
4908 }
4909
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004910 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 return PackageManager.PERMISSION_GRANTED;
4912 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004913
4914 return ActivityManager.checkComponentPermission(permission, uid,
4915 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 }
4917
4918 /**
4919 * As the only public entry point for permissions checking, this method
4920 * can enforce the semantic that requesting a check on a null global
4921 * permission is automatically denied. (Internally a null permission
4922 * string is used when calling {@link #checkComponentPermission} in cases
4923 * when only uid-based security is needed.)
4924 *
4925 * This can be called with or without the global lock held.
4926 */
4927 public int checkPermission(String permission, int pid, int uid) {
4928 if (permission == null) {
4929 return PackageManager.PERMISSION_DENIED;
4930 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004931 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 }
4933
4934 /**
4935 * Binder IPC calls go through the public entry point.
4936 * This can be called with or without the global lock held.
4937 */
4938 int checkCallingPermission(String permission) {
4939 return checkPermission(permission,
4940 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004941 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
4943
4944 /**
4945 * This can be called with or without the global lock held.
4946 */
4947 void enforceCallingPermission(String permission, String func) {
4948 if (checkCallingPermission(permission)
4949 == PackageManager.PERMISSION_GRANTED) {
4950 return;
4951 }
4952
4953 String msg = "Permission Denial: " + func + " from pid="
4954 + Binder.getCallingPid()
4955 + ", uid=" + Binder.getCallingUid()
4956 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004957 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004958 throw new SecurityException(msg);
4959 }
4960
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004961 /**
4962 * Determine if UID is holding permissions required to access {@link Uri} in
4963 * the given {@link ProviderInfo}. Final permission checking is always done
4964 * in {@link ContentProvider}.
4965 */
4966 private final boolean checkHoldingPermissionsLocked(
4967 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004968 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4969 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004970
4971 if (pi.applicationInfo.uid == uid) {
4972 return true;
4973 } else if (!pi.exported) {
4974 return false;
4975 }
4976
4977 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4978 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004980 // check if target holds top-level <provider> permissions
4981 if (!readMet && pi.readPermission != null
4982 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4983 readMet = true;
4984 }
4985 if (!writeMet && pi.writePermission != null
4986 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4987 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004988 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004989
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004990 // track if unprotected read/write is allowed; any denied
4991 // <path-permission> below removes this ability
4992 boolean allowDefaultRead = pi.readPermission == null;
4993 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004994
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004995 // check if target holds any <path-permission> that match uri
4996 final PathPermission[] pps = pi.pathPermissions;
4997 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004998 final String path = uri.getPath();
4999 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005000 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005001 i--;
5002 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005003 if (pp.match(path)) {
5004 if (!readMet) {
5005 final String pprperm = pp.getReadPermission();
5006 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5007 + pprperm + " for " + pp.getPath()
5008 + ": match=" + pp.match(path)
5009 + " check=" + pm.checkUidPermission(pprperm, uid));
5010 if (pprperm != null) {
5011 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5012 readMet = true;
5013 } else {
5014 allowDefaultRead = false;
5015 }
5016 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005017 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005018 if (!writeMet) {
5019 final String ppwperm = pp.getWritePermission();
5020 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5021 + ppwperm + " for " + pp.getPath()
5022 + ": match=" + pp.match(path)
5023 + " check=" + pm.checkUidPermission(ppwperm, uid));
5024 if (ppwperm != null) {
5025 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5026 writeMet = true;
5027 } else {
5028 allowDefaultWrite = false;
5029 }
5030 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005031 }
5032 }
5033 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005034 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005035
5036 // grant unprotected <provider> read/write, if not blocked by
5037 // <path-permission> above
5038 if (allowDefaultRead) readMet = true;
5039 if (allowDefaultWrite) writeMet = true;
5040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005041 } catch (RemoteException e) {
5042 return false;
5043 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005044
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005045 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 }
5047
5048 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5049 int modeFlags) {
5050 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005051 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005052 return true;
5053 }
5054 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5055 if (perms == null) return false;
5056 UriPermission perm = perms.get(uri);
5057 if (perm == null) return false;
5058 return (modeFlags&perm.modeFlags) == modeFlags;
5059 }
5060
5061 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005062 enforceNotIsolatedCaller("checkUriPermission");
5063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 // Another redirected-binder-call permissions check as in
5065 // {@link checkComponentPermission}.
5066 Identity tlsIdentity = sCallerIdentity.get();
5067 if (tlsIdentity != null) {
5068 uid = tlsIdentity.uid;
5069 pid = tlsIdentity.pid;
5070 }
5071
5072 // Our own process gets to do everything.
5073 if (pid == MY_PID) {
5074 return PackageManager.PERMISSION_GRANTED;
5075 }
5076 synchronized(this) {
5077 return checkUriPermissionLocked(uri, uid, modeFlags)
5078 ? PackageManager.PERMISSION_GRANTED
5079 : PackageManager.PERMISSION_DENIED;
5080 }
5081 }
5082
Dianne Hackborn39792d22010-08-19 18:01:52 -07005083 /**
5084 * Check if the targetPkg can be granted permission to access uri by
5085 * the callingUid using the given modeFlags. Throws a security exception
5086 * if callingUid is not allowed to do this. Returns the uid of the target
5087 * if the URI permission grant should be performed; returns -1 if it is not
5088 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005089 * If you already know the uid of the target, you can supply it in
5090 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005091 */
5092 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005093 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5095 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5096 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005097 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005098 }
5099
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005100 if (targetPkg != null) {
5101 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5102 "Checking grant " + targetPkg + " permission to " + uri);
5103 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005104
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005105 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106
5107 // If this is not a content: uri, we can't do anything with it.
5108 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005109 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005110 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005111 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 }
5113
5114 String name = uri.getAuthority();
5115 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005116 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005117 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 if (cpr != null) {
5119 pi = cpr.info;
5120 } else {
5121 try {
5122 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005123 PackageManager.GET_URI_PERMISSION_PATTERNS,
5124 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 } catch (RemoteException ex) {
5126 }
5127 }
5128 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005129 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005130 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 }
5132
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005133 int targetUid = lastTargetUid;
5134 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005135 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005136 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005137 if (targetUid < 0) {
5138 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5139 "Can't grant URI permission no uid for: " + targetPkg);
5140 return -1;
5141 }
5142 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005143 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 }
5146
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005147 if (targetUid >= 0) {
5148 // First... does the target actually need this permission?
5149 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5150 // No need to grant the target this permission.
5151 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5152 "Target " + targetPkg + " already has full permission to " + uri);
5153 return -1;
5154 }
5155 } else {
5156 // First... there is no target package, so can anyone access it?
5157 boolean allowed = pi.exported;
5158 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5159 if (pi.readPermission != null) {
5160 allowed = false;
5161 }
5162 }
5163 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5164 if (pi.writePermission != null) {
5165 allowed = false;
5166 }
5167 }
5168 if (allowed) {
5169 return -1;
5170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 }
5172
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005173 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005174 if (!pi.grantUriPermissions) {
5175 throw new SecurityException("Provider " + pi.packageName
5176 + "/" + pi.name
5177 + " does not allow granting of Uri permissions (uri "
5178 + uri + ")");
5179 }
5180 if (pi.uriPermissionPatterns != null) {
5181 final int N = pi.uriPermissionPatterns.length;
5182 boolean allowed = false;
5183 for (int i=0; i<N; i++) {
5184 if (pi.uriPermissionPatterns[i] != null
5185 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5186 allowed = true;
5187 break;
5188 }
5189 }
5190 if (!allowed) {
5191 throw new SecurityException("Provider " + pi.packageName
5192 + "/" + pi.name
5193 + " does not allow granting of permission to path of Uri "
5194 + uri);
5195 }
5196 }
5197
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005198 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005200 if (callingUid != Process.myUid()) {
5201 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5202 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5203 throw new SecurityException("Uid " + callingUid
5204 + " does not have permission to uri " + uri);
5205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 }
5207 }
5208
Dianne Hackborn39792d22010-08-19 18:01:52 -07005209 return targetUid;
5210 }
5211
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005212 public int checkGrantUriPermission(int callingUid, String targetPkg,
5213 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005214 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005215 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005216 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005217 }
5218 }
5219
Dianne Hackborn39792d22010-08-19 18:01:52 -07005220 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5221 Uri uri, int modeFlags, UriPermissionOwner owner) {
5222 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5223 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5224 if (modeFlags == 0) {
5225 return;
5226 }
5227
5228 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 // to the uri, and the target doesn't. Let's now give this to
5230 // the target.
5231
Joe Onorato8a9b2202010-02-26 18:56:32 -08005232 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005233 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005235 HashMap<Uri, UriPermission> targetUris
5236 = mGrantedUriPermissions.get(targetUid);
5237 if (targetUris == null) {
5238 targetUris = new HashMap<Uri, UriPermission>();
5239 mGrantedUriPermissions.put(targetUid, targetUris);
5240 }
5241
5242 UriPermission perm = targetUris.get(uri);
5243 if (perm == null) {
5244 perm = new UriPermission(targetUid, uri);
5245 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005249 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005251 } else {
5252 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5253 perm.readOwners.add(owner);
5254 owner.addReadPermission(perm);
5255 }
5256 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5257 perm.writeOwners.add(owner);
5258 owner.addWritePermission(perm);
5259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 }
5261 }
5262
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005263 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5264 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005265 if (targetPkg == null) {
5266 throw new NullPointerException("targetPkg");
5267 }
5268
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005269 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005270 if (targetUid < 0) {
5271 return;
5272 }
5273
5274 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5275 }
5276
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005277 static class NeededUriGrants extends ArrayList<Uri> {
5278 final String targetPkg;
5279 final int targetUid;
5280 final int flags;
5281
5282 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5283 targetPkg = _targetPkg;
5284 targetUid = _targetUid;
5285 flags = _flags;
5286 }
5287 }
5288
Dianne Hackborn39792d22010-08-19 18:01:52 -07005289 /**
5290 * Like checkGrantUriPermissionLocked, but takes an Intent.
5291 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005292 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5293 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005294 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005295 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5296 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005297 + " from " + intent + "; flags=0x"
5298 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5299
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005300 if (targetPkg == null) {
5301 throw new NullPointerException("targetPkg");
5302 }
5303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005305 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 }
5307 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005308 ClipData clip = intent.getClipData();
5309 if (data == null && clip == null) {
5310 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005311 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005312 if (data != null) {
5313 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5314 mode, needed != null ? needed.targetUid : -1);
5315 if (target > 0) {
5316 if (needed == null) {
5317 needed = new NeededUriGrants(targetPkg, target, mode);
5318 }
5319 needed.add(data);
5320 }
5321 }
5322 if (clip != null) {
5323 for (int i=0; i<clip.getItemCount(); i++) {
5324 Uri uri = clip.getItemAt(i).getUri();
5325 if (uri != null) {
5326 int target = -1;
5327 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5328 mode, needed != null ? needed.targetUid : -1);
5329 if (target > 0) {
5330 if (needed == null) {
5331 needed = new NeededUriGrants(targetPkg, target, mode);
5332 }
5333 needed.add(uri);
5334 }
5335 } else {
5336 Intent clipIntent = clip.getItemAt(i).getIntent();
5337 if (clipIntent != null) {
5338 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5339 callingUid, targetPkg, clipIntent, mode, needed);
5340 if (newNeeded != null) {
5341 needed = newNeeded;
5342 }
5343 }
5344 }
5345 }
5346 }
5347
5348 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005349 }
5350
5351 /**
5352 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5353 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005354 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5355 UriPermissionOwner owner) {
5356 if (needed != null) {
5357 for (int i=0; i<needed.size(); i++) {
5358 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5359 needed.get(i), needed.flags, owner);
5360 }
5361 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005362 }
5363
5364 void grantUriPermissionFromIntentLocked(int callingUid,
5365 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005366 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005367 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005368 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 return;
5370 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005371
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005372 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 }
5374
5375 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5376 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005377 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 synchronized(this) {
5379 final ProcessRecord r = getRecordForAppLocked(caller);
5380 if (r == null) {
5381 throw new SecurityException("Unable to find app for caller "
5382 + caller
5383 + " when granting permission to uri " + uri);
5384 }
5385 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005386 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005389 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 }
5391
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005392 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005393 null);
5394 }
5395 }
5396
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005397 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005398 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5399 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5400 HashMap<Uri, UriPermission> perms
5401 = mGrantedUriPermissions.get(perm.uid);
5402 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005403 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005404 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 perms.remove(perm.uri);
5406 if (perms.size() == 0) {
5407 mGrantedUriPermissions.remove(perm.uid);
5408 }
5409 }
5410 }
5411 }
5412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5414 int modeFlags) {
5415 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5416 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5417 if (modeFlags == 0) {
5418 return;
5419 }
5420
Joe Onorato8a9b2202010-02-26 18:56:32 -08005421 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005422 "Revoking all granted permissions to " + uri);
5423
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005424 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425
5426 final String authority = uri.getAuthority();
5427 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005428 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005429 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 if (cpr != null) {
5431 pi = cpr.info;
5432 } else {
5433 try {
5434 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005435 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 } catch (RemoteException ex) {
5437 }
5438 }
5439 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005440 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 return;
5442 }
5443
5444 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005445 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 // Right now, if you are not the original owner of the permission,
5447 // you are not allowed to revoke it.
5448 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5449 throw new SecurityException("Uid " + callingUid
5450 + " does not have permission to uri " + uri);
5451 //}
5452 }
5453
5454 // Go through all of the permissions and remove any that match.
5455 final List<String> SEGMENTS = uri.getPathSegments();
5456 if (SEGMENTS != null) {
5457 final int NS = SEGMENTS.size();
5458 int N = mGrantedUriPermissions.size();
5459 for (int i=0; i<N; i++) {
5460 HashMap<Uri, UriPermission> perms
5461 = mGrantedUriPermissions.valueAt(i);
5462 Iterator<UriPermission> it = perms.values().iterator();
5463 toploop:
5464 while (it.hasNext()) {
5465 UriPermission perm = it.next();
5466 Uri targetUri = perm.uri;
5467 if (!authority.equals(targetUri.getAuthority())) {
5468 continue;
5469 }
5470 List<String> targetSegments = targetUri.getPathSegments();
5471 if (targetSegments == null) {
5472 continue;
5473 }
5474 if (targetSegments.size() < NS) {
5475 continue;
5476 }
5477 for (int j=0; j<NS; j++) {
5478 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5479 continue toploop;
5480 }
5481 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005482 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005483 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 perm.clearModes(modeFlags);
5485 if (perm.modeFlags == 0) {
5486 it.remove();
5487 }
5488 }
5489 if (perms.size() == 0) {
5490 mGrantedUriPermissions.remove(
5491 mGrantedUriPermissions.keyAt(i));
5492 N--;
5493 i--;
5494 }
5495 }
5496 }
5497 }
5498
5499 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5500 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005501 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 synchronized(this) {
5503 final ProcessRecord r = getRecordForAppLocked(caller);
5504 if (r == null) {
5505 throw new SecurityException("Unable to find app for caller "
5506 + caller
5507 + " when revoking permission to uri " + uri);
5508 }
5509 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005510 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005511 return;
5512 }
5513
5514 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5515 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5516 if (modeFlags == 0) {
5517 return;
5518 }
5519
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005520 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521
5522 final String authority = uri.getAuthority();
5523 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005524 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 if (cpr != null) {
5526 pi = cpr.info;
5527 } else {
5528 try {
5529 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005530 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 } catch (RemoteException ex) {
5532 }
5533 }
5534 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005535 Slog.w(TAG, "No content provider found for permission revoke: "
5536 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 return;
5538 }
5539
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005540 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 }
5542 }
5543
Dianne Hackborn7e269642010-08-25 19:50:20 -07005544 @Override
5545 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005546 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005547 synchronized(this) {
5548 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5549 return owner.getExternalTokenLocked();
5550 }
5551 }
5552
5553 @Override
5554 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5555 Uri uri, int modeFlags) {
5556 synchronized(this) {
5557 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5558 if (owner == null) {
5559 throw new IllegalArgumentException("Unknown owner: " + token);
5560 }
5561 if (fromUid != Binder.getCallingUid()) {
5562 if (Binder.getCallingUid() != Process.myUid()) {
5563 // Only system code can grant URI permissions on behalf
5564 // of other users.
5565 throw new SecurityException("nice try");
5566 }
5567 }
5568 if (targetPkg == null) {
5569 throw new IllegalArgumentException("null target");
5570 }
5571 if (uri == null) {
5572 throw new IllegalArgumentException("null uri");
5573 }
5574
5575 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5576 }
5577 }
5578
5579 @Override
5580 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5581 synchronized(this) {
5582 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5583 if (owner == null) {
5584 throw new IllegalArgumentException("Unknown owner: " + token);
5585 }
5586
5587 if (uri == null) {
5588 owner.removeUriPermissionsLocked(mode);
5589 } else {
5590 owner.removeUriPermissionLocked(uri, mode);
5591 }
5592 }
5593 }
5594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5596 synchronized (this) {
5597 ProcessRecord app =
5598 who != null ? getRecordForAppLocked(who) : null;
5599 if (app == null) return;
5600
5601 Message msg = Message.obtain();
5602 msg.what = WAIT_FOR_DEBUGGER_MSG;
5603 msg.obj = app;
5604 msg.arg1 = waiting ? 1 : 0;
5605 mHandler.sendMessage(msg);
5606 }
5607 }
5608
5609 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005610 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5611 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005613 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005614 outInfo.threshold = homeAppMem;
5615 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5616 outInfo.hiddenAppThreshold = hiddenAppMem;
5617 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005618 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005619 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5620 ProcessList.VISIBLE_APP_ADJ);
5621 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5622 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 }
5624
5625 // =========================================================
5626 // TASK MANAGEMENT
5627 // =========================================================
5628
Craig Mautnercae015f2013-02-08 14:31:27 -08005629 @Override
5630 public List<RunningTaskInfo> getTasks(int maxNum, int flags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 IThumbnailReceiver receiver) {
Craig Mautnercae015f2013-02-08 14:31:27 -08005632 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633
Craig Mautnercae015f2013-02-08 14:31:27 -08005634 PendingThumbnailsRecord pending = new PendingThumbnailsRecord(receiver);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005635 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636
5637 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005638 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5640 + ", receiver=" + receiver);
5641
5642 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5643 != PackageManager.PERMISSION_GRANTED) {
5644 if (receiver != null) {
5645 // If the caller wants to wait for pending thumbnails,
5646 // it ain't gonna get them.
5647 try {
5648 receiver.finished();
5649 } catch (RemoteException ex) {
5650 }
5651 }
5652 String msg = "Permission Denial: getTasks() from pid="
5653 + Binder.getCallingPid()
5654 + ", uid=" + Binder.getCallingUid()
5655 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005656 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 throw new SecurityException(msg);
5658 }
5659
Craig Mautnercae015f2013-02-08 14:31:27 -08005660 topRecord = mMainStack.getTasksLocked(maxNum, receiver, pending, list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661
Craig Mautnercae015f2013-02-08 14:31:27 -08005662 if (!pending.pendingRecords.isEmpty()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 mPendingThumbnails.add(pending);
5664 }
5665 }
5666
Joe Onorato8a9b2202010-02-26 18:56:32 -08005667 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668
Craig Mautnercae015f2013-02-08 14:31:27 -08005669 if (topRecord != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005670 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 try {
Craig Mautnercae015f2013-02-08 14:31:27 -08005672 IApplicationThread topThumbnail = topRecord.app.thread;
Dianne Hackbornbe707852011-11-11 14:32:10 -08005673 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005675 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005676 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 }
5678 }
5679
5680 if (pending == null && receiver != null) {
5681 // In this case all thumbnails were available and the client
5682 // is being asked to be told when the remaining ones come in...
5683 // which is unusually, since the top-most currently running
5684 // activity should never have a canned thumbnail! Oh well.
5685 try {
5686 receiver.finished();
5687 } catch (RemoteException ex) {
5688 }
5689 }
5690
5691 return list;
5692 }
5693
5694 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005695 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005696 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5697 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 synchronized (this) {
5700 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5701 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005702 final boolean detailed = checkCallingPermission(
5703 android.Manifest.permission.GET_DETAILED_TASKS)
5704 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005706 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 final int N = mRecentTasks.size();
5709 ArrayList<ActivityManager.RecentTaskInfo> res
5710 = new ArrayList<ActivityManager.RecentTaskInfo>(
5711 maxNum < N ? maxNum : N);
5712 for (int i=0; i<N && maxNum > 0; i++) {
5713 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005714 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005715 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005716 // Return the entry if desired by the caller. We always return
5717 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005718 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005719 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5720 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005721
Dianne Hackborn905577f2011-09-07 18:31:28 -07005722 if (i == 0
5723 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 || (tr.intent == null)
5725 || ((tr.intent.getFlags()
5726 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5727 ActivityManager.RecentTaskInfo rti
5728 = new ActivityManager.RecentTaskInfo();
5729 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005730 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 rti.baseIntent = new Intent(
5732 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005733 if (!detailed) {
5734 rti.baseIntent.replaceExtras((Bundle)null);
5735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005737 rti.description = tr.lastDescription;
5738
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005739 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5740 // Check whether this activity is currently available.
5741 try {
5742 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005743 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005744 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005745 continue;
5746 }
5747 } else if (rti.baseIntent != null) {
5748 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005749 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005750 continue;
5751 }
5752 }
5753 } catch (RemoteException e) {
5754 // Will never happen.
5755 }
5756 }
5757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 res.add(rti);
5759 maxNum--;
5760 }
5761 }
5762 return res;
5763 }
5764 }
5765
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005766 private TaskRecord taskForIdLocked(int id) {
5767 final int N = mRecentTasks.size();
5768 for (int i=0; i<N; i++) {
5769 TaskRecord tr = mRecentTasks.get(i);
5770 if (tr.taskId == id) {
5771 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005772 }
5773 }
5774 return null;
5775 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005776
5777 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5778 synchronized (this) {
5779 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5780 "getTaskThumbnails()");
5781 TaskRecord tr = taskForIdLocked(id);
5782 if (tr != null) {
5783 return mMainStack.getTaskThumbnailsLocked(tr);
5784 }
5785 }
5786 return null;
5787 }
5788
Dianne Hackborn15491c62012-09-19 10:59:14 -07005789 public Bitmap getTaskTopThumbnail(int id) {
5790 synchronized (this) {
5791 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5792 "getTaskTopThumbnail()");
5793 TaskRecord tr = taskForIdLocked(id);
5794 if (tr != null) {
5795 return mMainStack.getTaskTopThumbnailLocked(tr);
5796 }
5797 }
5798 return null;
5799 }
5800
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005801 public boolean removeSubTask(int taskId, int subTaskIndex) {
5802 synchronized (this) {
5803 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5804 "removeSubTask()");
5805 long ident = Binder.clearCallingIdentity();
5806 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005807 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5808 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005809 } finally {
5810 Binder.restoreCallingIdentity(ident);
5811 }
5812 }
5813 }
5814
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005815 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5816 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005817 Intent baseIntent = new Intent(
5818 tr.intent != null ? tr.intent : tr.affinityIntent);
5819 ComponentName component = baseIntent.getComponent();
5820 if (component == null) {
5821 Slog.w(TAG, "Now component for base intent of task: " + tr);
5822 return;
5823 }
5824
5825 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005826 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005827
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005828 if (killProcesses) {
5829 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005830 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005831 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005832 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5833 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5834 for (int i=0; i<uids.size(); i++) {
5835 ProcessRecord proc = uids.valueAt(i);
5836 if (proc.userId != tr.userId) {
5837 continue;
5838 }
5839 if (!proc.pkgList.contains(pkg)) {
5840 continue;
5841 }
5842 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005843 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005844 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005845
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005846 // Kill the running processes.
5847 for (int i=0; i<procs.size(); i++) {
5848 ProcessRecord pr = procs.get(i);
5849 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5850 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005851 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005852 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005853 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005854 Process.killProcessQuiet(pr.pid);
5855 } else {
5856 pr.waitingToKill = "remove task";
5857 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858 }
5859 }
5860 }
5861
5862 public boolean removeTask(int taskId, int flags) {
5863 synchronized (this) {
5864 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5865 "removeTask()");
5866 long ident = Binder.clearCallingIdentity();
5867 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005868 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5869 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 if (r != null) {
5871 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005872 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005873 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005874 } else {
5875 TaskRecord tr = null;
5876 int i=0;
5877 while (i < mRecentTasks.size()) {
5878 TaskRecord t = mRecentTasks.get(i);
5879 if (t.taskId == taskId) {
5880 tr = t;
5881 break;
5882 }
5883 i++;
5884 }
5885 if (tr != null) {
5886 if (tr.numActivities <= 0) {
5887 // Caller is just removing a recent task that is
5888 // not actively running. That is easy!
5889 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005890 cleanUpRemovedTaskLocked(tr, flags);
5891 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005892 } else {
5893 Slog.w(TAG, "removeTask: task " + taskId
5894 + " does not have activities to remove, "
5895 + " but numActivities=" + tr.numActivities
5896 + ": " + tr);
5897 }
5898 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005899 }
5900 } finally {
5901 Binder.restoreCallingIdentity(ident);
5902 }
5903 }
5904 return false;
5905 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005908 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005910 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005911 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5912 "moveTaskToFront()");
5913
5914 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005915 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5916 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005917 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005918 return;
5919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 final long origId = Binder.clearCallingIdentity();
5921 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005922 TaskRecord tr = taskForIdLocked(task);
5923 if (tr != null) {
5924 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5925 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005927 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5928 // Caller wants the home activity moved with it. To accomplish this,
5929 // we'll just move the home task to the top first.
5930 mMainStack.moveHomeToFrontLocked();
5931 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005932 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005933 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005935 if (mMainStack.findTaskToMoveToFrontLocked(task, flags, options)) {
5936 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 }
5938 } finally {
5939 Binder.restoreCallingIdentity(origId);
5940 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005941 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
5943 }
5944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 public void moveTaskToBack(int task) {
5946 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5947 "moveTaskToBack()");
5948
5949 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005950 if (mMainStack.mResumedActivity != null
5951 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005952 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5953 Binder.getCallingUid(), "Task to back")) {
5954 return;
5955 }
5956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005958 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 Binder.restoreCallingIdentity(origId);
5960 }
5961 }
5962
5963 /**
5964 * Moves an activity, and all of the other activities within the same task, to the bottom
5965 * of the history stack. The activity's order within the task is unchanged.
5966 *
5967 * @param token A reference to the activity we wish to move
5968 * @param nonRoot If false then this only works if the activity is the root
5969 * of a task; if true it will work for any activity in a task.
5970 * @return Returns true if the move completed, false if not.
5971 */
5972 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005973 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 synchronized(this) {
5975 final long origId = Binder.clearCallingIdentity();
Craig Mautnercae015f2013-02-08 14:31:27 -08005976 int taskId = mMainStack.getTaskForActivityLocked(token, !nonRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005977 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005978 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 }
5980 Binder.restoreCallingIdentity(origId);
5981 }
5982 return false;
5983 }
5984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 public void moveTaskBackwards(int task) {
5986 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5987 "moveTaskBackwards()");
5988
5989 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005990 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5991 Binder.getCallingUid(), "Task backwards")) {
5992 return;
5993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 final long origId = Binder.clearCallingIdentity();
5995 moveTaskBackwardsLocked(task);
5996 Binder.restoreCallingIdentity(origId);
5997 }
5998 }
5999
6000 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006001 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 }
6003
6004 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6005 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08006006 return mMainStack.getTaskForActivityLocked(token, onlyRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 }
6008 }
6009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 // =========================================================
6011 // THUMBNAILS
6012 // =========================================================
6013
6014 public void reportThumbnail(IBinder token,
6015 Bitmap thumbnail, CharSequence description) {
6016 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6017 final long origId = Binder.clearCallingIdentity();
6018 sendPendingThumbnail(null, token, thumbnail, description, true);
6019 Binder.restoreCallingIdentity(origId);
6020 }
6021
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006022 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 Bitmap thumbnail, CharSequence description, boolean always) {
6024 TaskRecord task = null;
6025 ArrayList receivers = null;
6026
6027 //System.out.println("Send pending thumbnail: " + r);
6028
6029 synchronized(this) {
6030 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006031 r = mMainStack.isInStackLocked(token);
6032 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 return;
6034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006036 if (thumbnail == null && r.thumbHolder != null) {
6037 thumbnail = r.thumbHolder.lastThumbnail;
6038 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
6040 if (thumbnail == null && !always) {
6041 // If there is no thumbnail, and this entry is not actually
6042 // going away, then abort for now and pick up the next
6043 // thumbnail we get.
6044 return;
6045 }
6046 task = r.task;
6047
6048 int N = mPendingThumbnails.size();
6049 int i=0;
6050 while (i<N) {
6051 PendingThumbnailsRecord pr =
6052 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6053 //System.out.println("Looking in " + pr.pendingRecords);
6054 if (pr.pendingRecords.remove(r)) {
6055 if (receivers == null) {
6056 receivers = new ArrayList();
6057 }
6058 receivers.add(pr);
6059 if (pr.pendingRecords.size() == 0) {
6060 pr.finished = true;
6061 mPendingThumbnails.remove(i);
6062 N--;
6063 continue;
6064 }
6065 }
6066 i++;
6067 }
6068 }
6069
6070 if (receivers != null) {
6071 final int N = receivers.size();
6072 for (int i=0; i<N; i++) {
6073 try {
6074 PendingThumbnailsRecord pr =
6075 (PendingThumbnailsRecord)receivers.get(i);
6076 pr.receiver.newThumbnail(
6077 task != null ? task.taskId : -1, thumbnail, description);
6078 if (pr.finished) {
6079 pr.receiver.finished();
6080 }
6081 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006082 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 }
6084 }
6085 }
6086 }
6087
6088 // =========================================================
6089 // CONTENT PROVIDERS
6090 // =========================================================
6091
Jeff Brown10e89712011-07-08 18:52:57 -07006092 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6093 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006095 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006096 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006097 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 } catch (RemoteException ex) {
6099 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006100 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006101 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6102 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006104 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 for (int i=0; i<N; i++) {
6106 ProviderInfo cpi =
6107 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006108 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6109 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006110 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006111 // This is a singleton provider, but a user besides the
6112 // default user is asking to initialize a process it runs
6113 // in... well, no, it doesn't actually run in this process,
6114 // it runs in the process of the default user. Get rid of it.
6115 providers.remove(i);
6116 N--;
6117 continue;
6118 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006119
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006120 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006121 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006123 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006124 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006126 if (DEBUG_MU)
6127 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 app.pubProviders.put(cpi.name, cpr);
6129 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006130 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132 }
6133 return providers;
6134 }
6135
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006136 /**
6137 * Check if {@link ProcessRecord} has a possible chance at accessing the
6138 * given {@link ProviderInfo}. Final permission checking is always done
6139 * in {@link ContentProvider}.
6140 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006142 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006144 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006146 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006147 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 return null;
6149 }
6150 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006151 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 == PackageManager.PERMISSION_GRANTED) {
6153 return null;
6154 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006155
6156 PathPermission[] pps = cpi.pathPermissions;
6157 if (pps != null) {
6158 int i = pps.length;
6159 while (i > 0) {
6160 i--;
6161 PathPermission pp = pps[i];
6162 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006163 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006164 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006165 return null;
6166 }
6167 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006168 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006169 == PackageManager.PERMISSION_GRANTED) {
6170 return null;
6171 }
6172 }
6173 }
6174
Dianne Hackbornb424b632010-08-18 15:59:05 -07006175 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6176 if (perms != null) {
6177 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6178 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6179 return null;
6180 }
6181 }
6182 }
6183
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006184 String msg;
6185 if (!cpi.exported) {
6186 msg = "Permission Denial: opening provider " + cpi.name
6187 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6188 + ", uid=" + callingUid + ") that is not exported from uid "
6189 + cpi.applicationInfo.uid;
6190 } else {
6191 msg = "Permission Denial: opening provider " + cpi.name
6192 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6193 + ", uid=" + callingUid + ") requires "
6194 + cpi.readPermission + " or " + cpi.writePermission;
6195 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006196 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 return msg;
6198 }
6199
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006200 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6201 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006202 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006203 for (int i=0; i<r.conProviders.size(); i++) {
6204 ContentProviderConnection conn = r.conProviders.get(i);
6205 if (conn.provider == cpr) {
6206 if (DEBUG_PROVIDER) Slog.v(TAG,
6207 "Adding provider requested by "
6208 + r.processName + " from process "
6209 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6210 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6211 if (stable) {
6212 conn.stableCount++;
6213 conn.numStableIncs++;
6214 } else {
6215 conn.unstableCount++;
6216 conn.numUnstableIncs++;
6217 }
6218 return conn;
6219 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006220 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006221 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6222 if (stable) {
6223 conn.stableCount = 1;
6224 conn.numStableIncs = 1;
6225 } else {
6226 conn.unstableCount = 1;
6227 conn.numUnstableIncs = 1;
6228 }
6229 cpr.connections.add(conn);
6230 r.conProviders.add(conn);
6231 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006232 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006233 cpr.addExternalProcessHandleLocked(externalProcessToken);
6234 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006235 }
6236
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006237 boolean decProviderCountLocked(ContentProviderConnection conn,
6238 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6239 if (conn != null) {
6240 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006241 if (DEBUG_PROVIDER) Slog.v(TAG,
6242 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006243 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006244 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006245 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6246 if (stable) {
6247 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006248 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006249 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006250 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006251 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6252 cpr.connections.remove(conn);
6253 conn.client.conProviders.remove(conn);
6254 return true;
6255 }
6256 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006257 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006258 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006259 return false;
6260 }
6261
Amith Yamasani742a6712011-05-04 14:49:28 -07006262 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006263 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006265 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 ProviderInfo cpi = null;
6267
6268 synchronized(this) {
6269 ProcessRecord r = null;
6270 if (caller != null) {
6271 r = getRecordForAppLocked(caller);
6272 if (r == null) {
6273 throw new SecurityException(
6274 "Unable to find app for caller " + caller
6275 + " (pid=" + Binder.getCallingPid()
6276 + ") when getting content provider " + name);
6277 }
6278 }
6279
6280 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006281 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006282 boolean providerRunning = cpr != null;
6283 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006285 String msg;
6286 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6287 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
6290 if (r != null && cpr.canRunHere(r)) {
6291 // This provider has been published or is in the process
6292 // of being published... but it is also allowed to run
6293 // in the caller's process, so don't make a connection
6294 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006295 ContentProviderHolder holder = cpr.newHolder(null);
6296 // don't give caller the provider object, it needs
6297 // to make its own.
6298 holder.provider = null;
6299 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 }
6301
6302 final long origId = Binder.clearCallingIdentity();
6303
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006304 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006306 conn = incProviderCountLocked(r, cpr, token, stable);
6307 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006308 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006309 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006310 // make sure to count it as being accessed and thus
6311 // back up on the LRU list. This is good because
6312 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006313 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006314 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006315 }
6316
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006317 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006318 if (false) {
6319 if (cpr.name.flattenToShortString().equals(
6320 "com.android.providers.calendar/.CalendarProvider2")) {
6321 Slog.v(TAG, "****************** KILLING "
6322 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006323 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006324 }
6325 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006326 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006327 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6328 // NOTE: there is still a race here where a signal could be
6329 // pending on the process even though we managed to update its
6330 // adj level. Not sure what to do about this, but at least
6331 // the race is now smaller.
6332 if (!success) {
6333 // Uh oh... it looks like the provider's process
6334 // has been killed on us. We need to wait for a new
6335 // process to be started, and make sure its death
6336 // doesn't kill our process.
6337 Slog.i(TAG,
6338 "Existing provider " + cpr.name.flattenToShortString()
6339 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006340 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006341 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006342 if (!lastRef) {
6343 // This wasn't the last ref our process had on
6344 // the provider... we have now been killed, bail.
6345 return null;
6346 }
6347 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006348 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 }
6351
6352 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006355 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006356 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006358 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006359 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006360 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 } catch (RemoteException ex) {
6362 }
6363 if (cpi == null) {
6364 return null;
6365 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006366 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6367 cpi.name, cpi.flags);
6368 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006369 userId = 0;
6370 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006371 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006372
Dianne Hackbornb424b632010-08-18 15:59:05 -07006373 String msg;
6374 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6375 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 }
6377
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006378 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006379 && !cpi.processName.equals("system")) {
6380 // If this content provider does not run in the system
6381 // process, and the system is not yet ready to run other
6382 // processes, then fail fast instead of hanging.
6383 throw new IllegalArgumentException(
6384 "Attempt to launch content provider before system ready");
6385 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006386
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006387 // Make sure that the user who owns this provider is started. If not,
6388 // we don't want to allow it to run.
6389 if (mStartedUsers.get(userId) == null) {
6390 Slog.w(TAG, "Unable to launch app "
6391 + cpi.applicationInfo.packageName + "/"
6392 + cpi.applicationInfo.uid + " for provider "
6393 + name + ": user " + userId + " is stopped");
6394 return null;
6395 }
6396
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006397 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006398 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 final boolean firstClass = cpr == null;
6400 if (firstClass) {
6401 try {
6402 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006403 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 getApplicationInfo(
6405 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006406 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006408 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 + cpi.name);
6410 return null;
6411 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006412 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006413 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 } catch (RemoteException ex) {
6415 // pm is in same process, this will never happen.
6416 }
6417 }
6418
6419 if (r != null && cpr.canRunHere(r)) {
6420 // If this is a multiprocess provider, then just return its
6421 // info and allow the caller to instantiate it. Only do
6422 // this if the provider is the same user as the caller's
6423 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 }
6426
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006427 if (DEBUG_PROVIDER) {
6428 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006429 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006430 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432
6433 // This is single process, and our app is now connecting to it.
6434 // See if we are already in the process of launching this
6435 // provider.
6436 final int N = mLaunchingProviders.size();
6437 int i;
6438 for (i=0; i<N; i++) {
6439 if (mLaunchingProviders.get(i) == cpr) {
6440 break;
6441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 }
6443
6444 // If the provider is not already being launched, then get it
6445 // started.
6446 if (i >= N) {
6447 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006448
6449 try {
6450 // Content provider is now in use, its package can't be stopped.
6451 try {
6452 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006453 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006454 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006455 } catch (IllegalArgumentException e) {
6456 Slog.w(TAG, "Failed trying to unstop package "
6457 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006458 }
6459
6460 ProcessRecord proc = startProcessLocked(cpi.processName,
6461 cpr.appInfo, false, 0, "content provider",
6462 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006463 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006464 if (proc == null) {
6465 Slog.w(TAG, "Unable to launch app "
6466 + cpi.applicationInfo.packageName + "/"
6467 + cpi.applicationInfo.uid + " for provider "
6468 + name + ": process is bad");
6469 return null;
6470 }
6471 cpr.launchingApp = proc;
6472 mLaunchingProviders.add(cpr);
6473 } finally {
6474 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 }
6477
6478 // Make sure the provider is published (the same provider class
6479 // may be published under multiple names).
6480 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006481 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006483
Amith Yamasani742a6712011-05-04 14:49:28 -07006484 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006485 conn = incProviderCountLocked(r, cpr, token, stable);
6486 if (conn != null) {
6487 conn.waiting = true;
6488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
6490 }
6491
6492 // Wait for the provider to be published...
6493 synchronized (cpr) {
6494 while (cpr.provider == null) {
6495 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006496 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 + cpi.applicationInfo.packageName + "/"
6498 + cpi.applicationInfo.uid + " for provider "
6499 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006500 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006501 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 cpi.applicationInfo.packageName,
6503 cpi.applicationInfo.uid, name);
6504 return null;
6505 }
6506 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006507 if (DEBUG_MU) {
6508 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6509 + cpr.launchingApp);
6510 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006511 if (conn != null) {
6512 conn.waiting = true;
6513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 cpr.wait();
6515 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006516 } finally {
6517 if (conn != null) {
6518 conn.waiting = false;
6519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 }
6521 }
6522 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006523 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525
6526 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006527 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006528 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 if (caller == null) {
6530 String msg = "null IApplicationThread when getting content provider "
6531 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006532 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 throw new SecurityException(msg);
6534 }
6535
Dianne Hackborn139748f2012-09-24 11:36:57 -07006536 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006537 false, true, "getContentProvider", null);
6538 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
Jeff Sharkey6d515712012-09-20 16:06:08 -07006541 public ContentProviderHolder getContentProviderExternal(
6542 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006543 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6544 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006545 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006546 false, true, "getContentProvider", null);
6547 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006548 }
6549
Dianne Hackborn41203752012-08-31 14:05:51 -07006550 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6551 IBinder token, int userId) {
6552 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 }
6554
6555 /**
6556 * Drop a content provider from a ProcessRecord's bookkeeping
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006558 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006559 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006561 ContentProviderConnection conn;
6562 try {
6563 conn = (ContentProviderConnection)connection;
6564 } catch (ClassCastException e) {
6565 String msg ="removeContentProvider: " + connection
6566 + " not a ContentProviderConnection";
6567 Slog.w(TAG, msg);
6568 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006570 if (conn == null) {
6571 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006573 if (decProviderCountLocked(conn, null, null, stable)) {
6574 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 }
6577 }
6578
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006579 public void removeContentProviderExternal(String name, IBinder token) {
6580 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6581 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006582 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006583 }
6584
Dianne Hackborn41203752012-08-31 14:05:51 -07006585 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006587 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 if(cpr == null) {
6589 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006590 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 return;
6592 }
6593
6594 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006595 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006596 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006597 if (localCpr.hasExternalProcessHandles()) {
6598 if (localCpr.removeExternalProcessHandleLocked(token)) {
6599 updateOomAdjLocked();
6600 } else {
6601 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6602 + " with no external reference for token: "
6603 + token + ".");
6604 }
6605 } else {
6606 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6607 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006609 }
6610 }
6611
6612 public final void publishContentProviders(IApplicationThread caller,
6613 List<ContentProviderHolder> providers) {
6614 if (providers == null) {
6615 return;
6616 }
6617
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006618 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006619 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006621 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006622 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 if (r == null) {
6624 throw new SecurityException(
6625 "Unable to find app for caller " + caller
6626 + " (pid=" + Binder.getCallingPid()
6627 + ") when publishing content providers");
6628 }
6629
6630 final long origId = Binder.clearCallingIdentity();
6631
6632 final int N = providers.size();
6633 for (int i=0; i<N; i++) {
6634 ContentProviderHolder src = providers.get(i);
6635 if (src == null || src.info == null || src.provider == null) {
6636 continue;
6637 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006638 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006639 if (DEBUG_MU)
6640 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006642 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006643 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 String names[] = dst.info.authority.split(";");
6645 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006646 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 }
6648
6649 int NL = mLaunchingProviders.size();
6650 int j;
6651 for (j=0; j<NL; j++) {
6652 if (mLaunchingProviders.get(j) == dst) {
6653 mLaunchingProviders.remove(j);
6654 j--;
6655 NL--;
6656 }
6657 }
6658 synchronized (dst) {
6659 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006660 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 dst.notifyAll();
6662 }
6663 updateOomAdjLocked(r);
6664 }
6665 }
6666
6667 Binder.restoreCallingIdentity(origId);
6668 }
6669 }
6670
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006671 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6672 ContentProviderConnection conn;
6673 try {
6674 conn = (ContentProviderConnection)connection;
6675 } catch (ClassCastException e) {
6676 String msg ="refContentProvider: " + connection
6677 + " not a ContentProviderConnection";
6678 Slog.w(TAG, msg);
6679 throw new IllegalArgumentException(msg);
6680 }
6681 if (conn == null) {
6682 throw new NullPointerException("connection is null");
6683 }
6684
6685 synchronized (this) {
6686 if (stable > 0) {
6687 conn.numStableIncs += stable;
6688 }
6689 stable = conn.stableCount + stable;
6690 if (stable < 0) {
6691 throw new IllegalStateException("stableCount < 0: " + stable);
6692 }
6693
6694 if (unstable > 0) {
6695 conn.numUnstableIncs += unstable;
6696 }
6697 unstable = conn.unstableCount + unstable;
6698 if (unstable < 0) {
6699 throw new IllegalStateException("unstableCount < 0: " + unstable);
6700 }
6701
6702 if ((stable+unstable) <= 0) {
6703 throw new IllegalStateException("ref counts can't go to zero here: stable="
6704 + stable + " unstable=" + unstable);
6705 }
6706 conn.stableCount = stable;
6707 conn.unstableCount = unstable;
6708 return !conn.dead;
6709 }
6710 }
6711
6712 public void unstableProviderDied(IBinder connection) {
6713 ContentProviderConnection conn;
6714 try {
6715 conn = (ContentProviderConnection)connection;
6716 } catch (ClassCastException e) {
6717 String msg ="refContentProvider: " + connection
6718 + " not a ContentProviderConnection";
6719 Slog.w(TAG, msg);
6720 throw new IllegalArgumentException(msg);
6721 }
6722 if (conn == null) {
6723 throw new NullPointerException("connection is null");
6724 }
6725
6726 // Safely retrieve the content provider associated with the connection.
6727 IContentProvider provider;
6728 synchronized (this) {
6729 provider = conn.provider.provider;
6730 }
6731
6732 if (provider == null) {
6733 // Um, yeah, we're way ahead of you.
6734 return;
6735 }
6736
6737 // Make sure the caller is being honest with us.
6738 if (provider.asBinder().pingBinder()) {
6739 // Er, no, still looks good to us.
6740 synchronized (this) {
6741 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6742 + " says " + conn + " died, but we don't agree");
6743 return;
6744 }
6745 }
6746
6747 // Well look at that! It's dead!
6748 synchronized (this) {
6749 if (conn.provider.provider != provider) {
6750 // But something changed... good enough.
6751 return;
6752 }
6753
6754 ProcessRecord proc = conn.provider.proc;
6755 if (proc == null || proc.thread == null) {
6756 // Seems like the process is already cleaned up.
6757 return;
6758 }
6759
6760 // As far as we're concerned, this is just like receiving a
6761 // death notification... just a bit prematurely.
6762 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6763 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006764 final long ident = Binder.clearCallingIdentity();
6765 try {
6766 appDiedLocked(proc, proc.pid, proc.thread);
6767 } finally {
6768 Binder.restoreCallingIdentity(ident);
6769 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006770 }
6771 }
6772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006774 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006775 synchronized (mSelf) {
6776 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6777 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006778 if (providers != null) {
6779 for (int i=providers.size()-1; i>=0; i--) {
6780 ProviderInfo pi = (ProviderInfo)providers.get(i);
6781 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6782 Slog.w(TAG, "Not installing system proc provider " + pi.name
6783 + ": not system .apk");
6784 providers.remove(i);
6785 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006786 }
6787 }
6788 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006789 if (providers != null) {
6790 mSystemThread.installSystemProviders(providers);
6791 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006792
6793 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006794
6795 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
6797
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006798 /**
6799 * Allows app to retrieve the MIME type of a URI without having permission
6800 * to access its content provider.
6801 *
6802 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6803 *
6804 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6805 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6806 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006807 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006808 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006809 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006810 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006811 final String name = uri.getAuthority();
6812 final long ident = Binder.clearCallingIdentity();
6813 ContentProviderHolder holder = null;
6814
6815 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006816 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006817 if (holder != null) {
6818 return holder.provider.getType(uri);
6819 }
6820 } catch (RemoteException e) {
6821 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6822 return null;
6823 } finally {
6824 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006825 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006826 }
6827 Binder.restoreCallingIdentity(ident);
6828 }
6829
6830 return null;
6831 }
6832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 // =========================================================
6834 // GLOBAL MANAGEMENT
6835 // =========================================================
6836
6837 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006838 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 String proc = customProcess != null ? customProcess : info.processName;
6840 BatteryStatsImpl.Uid.Proc ps = null;
6841 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006842 int uid = info.uid;
6843 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006844 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006845 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6846 uid = 0;
6847 while (true) {
6848 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6849 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6850 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6851 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006852 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006853 mNextIsolatedProcessUid++;
6854 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6855 // No process for this uid, use it.
6856 break;
6857 }
6858 stepsLeft--;
6859 if (stepsLeft <= 0) {
6860 return null;
6861 }
6862 }
6863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 synchronized (stats) {
6865 ps = stats.getProcessStatsLocked(info.uid, proc);
6866 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006867 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 }
6869
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006870 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6871 ProcessRecord app;
6872 if (!isolated) {
6873 app = getProcessRecordLocked(info.processName, info.uid);
6874 } else {
6875 app = null;
6876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006877
6878 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006879 app = newProcessRecordLocked(null, info, null, isolated);
6880 mProcessNames.put(info.processName, app.uid, app);
6881 if (isolated) {
6882 mIsolatedProcesses.put(app.uid, app);
6883 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006884 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 }
6886
Dianne Hackborne7f97212011-02-24 14:40:20 -08006887 // This package really, really can not be stopped.
6888 try {
6889 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006890 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006891 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006892 } catch (IllegalArgumentException e) {
6893 Slog.w(TAG, "Failed trying to unstop package "
6894 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006895 }
6896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6898 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6899 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006900 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 }
6902 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6903 mPersistentStartingProcesses.add(app);
6904 startProcessLocked(app, "added application", app.processName);
6905 }
6906
6907 return app;
6908 }
6909
6910 public void unhandledBack() {
6911 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6912 "unhandledBack()");
6913
6914 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08006915 final long origId = Binder.clearCallingIdentity();
6916 try {
6917 mMainStack.unhandledBackLocked();
6918 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 Binder.restoreCallingIdentity(origId);
6920 }
6921 }
6922 }
6923
6924 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006925 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006926 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006928 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 ParcelFileDescriptor pfd = null;
6930 if (cph != null) {
6931 // We record the binder invoker's uid in thread-local storage before
6932 // going to the content provider to open the file. Later, in the code
6933 // that handles all permissions checks, we look for this uid and use
6934 // that rather than the Activity Manager's own uid. The effect is that
6935 // we do the check against the caller's permissions even though it looks
6936 // to the content provider like the Activity Manager itself is making
6937 // the request.
6938 sCallerIdentity.set(new Identity(
6939 Binder.getCallingPid(), Binder.getCallingUid()));
6940 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08006941 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 } catch (FileNotFoundException e) {
6943 // do nothing; pfd will be returned null
6944 } finally {
6945 // Ensure that whatever happens, we clean up the identity state
6946 sCallerIdentity.remove();
6947 }
6948
6949 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07006950 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006952 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006953 }
6954 return pfd;
6955 }
6956
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006957 // Actually is sleeping or shutting down or whatever else in the future
6958 // is an inactive state.
6959 public boolean isSleeping() {
6960 return mSleeping || mShuttingDown;
6961 }
6962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006964 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6965 != PackageManager.PERMISSION_GRANTED) {
6966 throw new SecurityException("Requires permission "
6967 + android.Manifest.permission.DEVICE_POWER);
6968 }
6969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006971 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006972 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006974 if (!mSleeping) {
6975 mSleeping = true;
6976 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006977
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006978 // Initialize the wake times of all processes.
6979 checkExcessivePowerUsageLocked(false);
6980 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6981 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6982 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 }
6985 }
6986
Dianne Hackborn55280a92009-05-07 15:53:46 -07006987 public boolean shutdown(int timeout) {
6988 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6989 != PackageManager.PERMISSION_GRANTED) {
6990 throw new SecurityException("Requires permission "
6991 + android.Manifest.permission.SHUTDOWN);
6992 }
6993
6994 boolean timedout = false;
6995
6996 synchronized(this) {
6997 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006998 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006999
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007000 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007001 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007002 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007003 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007004 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007005 long delay = endTime - System.currentTimeMillis();
7006 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007007 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007008 timedout = true;
7009 break;
7010 }
7011 try {
7012 this.wait();
7013 } catch (InterruptedException e) {
7014 }
7015 }
7016 }
7017 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007018
7019 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007020 mUsageStatsService.shutdown();
7021 mBatteryStatsService.shutdown();
7022
7023 return timedout;
7024 }
7025
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007026 public final void activitySlept(IBinder token) {
7027 if (localLOGV) Slog.v(
7028 TAG, "Activity slept: token=" + token);
7029
7030 ActivityRecord r = null;
7031
7032 final long origId = Binder.clearCallingIdentity();
7033
7034 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007035 r = mMainStack.isInStackLocked(token);
7036 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007037 mMainStack.activitySleptLocked(r);
7038 }
7039 }
7040
7041 Binder.restoreCallingIdentity(origId);
7042 }
7043
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007044 private void comeOutOfSleepIfNeededLocked() {
7045 if (!mWentToSleep && !mLockScreenShown) {
7046 if (mSleeping) {
7047 mSleeping = false;
7048 mMainStack.awakeFromSleepingLocked();
7049 mMainStack.resumeTopActivityLocked(null);
7050 }
7051 }
7052 }
7053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007055 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7056 != PackageManager.PERMISSION_GRANTED) {
7057 throw new SecurityException("Requires permission "
7058 + android.Manifest.permission.DEVICE_POWER);
7059 }
7060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007062 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007063 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007064 comeOutOfSleepIfNeededLocked();
7065 }
7066 }
7067
Jeff Brownc042ee22012-05-08 13:03:42 -07007068 private void updateEventDispatchingLocked() {
7069 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7070 }
7071
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007072 public void setLockScreenShown(boolean shown) {
7073 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7074 != PackageManager.PERMISSION_GRANTED) {
7075 throw new SecurityException("Requires permission "
7076 + android.Manifest.permission.DEVICE_POWER);
7077 }
7078
7079 synchronized(this) {
7080 mLockScreenShown = shown;
7081 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007082 }
7083 }
7084
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007085 public void stopAppSwitches() {
7086 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7087 != PackageManager.PERMISSION_GRANTED) {
7088 throw new SecurityException("Requires permission "
7089 + android.Manifest.permission.STOP_APP_SWITCHES);
7090 }
7091
7092 synchronized(this) {
7093 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7094 + APP_SWITCH_DELAY_TIME;
7095 mDidAppSwitch = false;
7096 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7097 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7098 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7099 }
7100 }
7101
7102 public void resumeAppSwitches() {
7103 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7104 != PackageManager.PERMISSION_GRANTED) {
7105 throw new SecurityException("Requires permission "
7106 + android.Manifest.permission.STOP_APP_SWITCHES);
7107 }
7108
7109 synchronized(this) {
7110 // Note that we don't execute any pending app switches... we will
7111 // let those wait until either the timeout, or the next start
7112 // activity request.
7113 mAppSwitchesAllowedTime = 0;
7114 }
7115 }
7116
7117 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7118 String name) {
7119 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7120 return true;
7121 }
7122
7123 final int perm = checkComponentPermission(
7124 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007125 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007126 if (perm == PackageManager.PERMISSION_GRANTED) {
7127 return true;
7128 }
7129
Joe Onorato8a9b2202010-02-26 18:56:32 -08007130 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007131 return false;
7132 }
7133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 public void setDebugApp(String packageName, boolean waitForDebugger,
7135 boolean persistent) {
7136 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7137 "setDebugApp()");
7138
7139 // Note that this is not really thread safe if there are multiple
7140 // callers into it at the same time, but that's not a situation we
7141 // care about.
7142 if (persistent) {
7143 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007144 Settings.Global.putString(
7145 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007146 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007147 Settings.Global.putInt(
7148 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 waitForDebugger ? 1 : 0);
7150 }
7151
7152 synchronized (this) {
7153 if (!persistent) {
7154 mOrigDebugApp = mDebugApp;
7155 mOrigWaitForDebugger = mWaitForDebugger;
7156 }
7157 mDebugApp = packageName;
7158 mWaitForDebugger = waitForDebugger;
7159 mDebugTransient = !persistent;
7160 if (packageName != null) {
7161 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007162 forceStopPackageLocked(packageName, -1, false, false, true, true,
7163 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 Binder.restoreCallingIdentity(origId);
7165 }
7166 }
7167 }
7168
Siva Velusamy92a8b222012-03-09 16:24:04 -08007169 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7170 synchronized (this) {
7171 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7172 if (!isDebuggable) {
7173 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7174 throw new SecurityException("Process not debuggable: " + app.packageName);
7175 }
7176 }
7177
7178 mOpenGlTraceApp = processName;
7179 }
7180 }
7181
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007182 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7183 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7184 synchronized (this) {
7185 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7186 if (!isDebuggable) {
7187 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7188 throw new SecurityException("Process not debuggable: " + app.packageName);
7189 }
7190 }
7191 mProfileApp = processName;
7192 mProfileFile = profileFile;
7193 if (mProfileFd != null) {
7194 try {
7195 mProfileFd.close();
7196 } catch (IOException e) {
7197 }
7198 mProfileFd = null;
7199 }
7200 mProfileFd = profileFd;
7201 mProfileType = 0;
7202 mAutoStopProfiler = autoStopProfiler;
7203 }
7204 }
7205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007206 public void setAlwaysFinish(boolean enabled) {
7207 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7208 "setAlwaysFinish()");
7209
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007210 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007212 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213
7214 synchronized (this) {
7215 mAlwaysFinishActivities = enabled;
7216 }
7217 }
7218
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007219 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007221 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007222 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007223 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 }
7225 }
7226
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007227 public boolean isUserAMonkey() {
7228 // For now the fact that there is a controller implies
7229 // we have a monkey.
7230 synchronized (this) {
7231 return mController != null;
7232 }
7233 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007234
7235 public void requestBugReport() {
Jeff Sharkeyb9323192013-02-05 13:32:18 -08007236 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007237 SystemProperties.set("ctl.start", "bugreport");
7238 }
7239
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007240 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7241 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7242 != PackageManager.PERMISSION_GRANTED) {
7243 throw new SecurityException("Requires permission "
7244 + android.Manifest.permission.FILTER_EVENTS);
7245 }
7246
7247 ProcessRecord proc;
7248
7249 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7250 synchronized (this) {
7251 synchronized (mPidsSelfLocked) {
7252 proc = mPidsSelfLocked.get(pid);
7253 }
7254 if (proc != null) {
7255 if (proc.debugging) {
7256 return -1;
7257 }
7258
7259 if (mDidDexOpt) {
7260 // Give more time since we were dexopting.
7261 mDidDexOpt = false;
7262 return -1;
7263 }
7264
7265 if (proc.instrumentationClass != null) {
7266 Bundle info = new Bundle();
7267 info.putString("shortMsg", "keyDispatchingTimedOut");
7268 info.putString("longMsg", "Timed out while dispatching key event");
7269 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7270 proc = null;
7271 }
7272 }
7273 }
7274
7275 if (proc != null) {
7276 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7277 if (proc.instrumentationClass != null || proc.usingWrapper) {
7278 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7279 }
7280 }
7281
7282 return KEY_DISPATCHING_TIMEOUT;
7283 }
7284
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007285 public Bundle getTopActivityExtras(int requestType) {
7286 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7287 "getTopActivityExtras()");
7288 PendingActivityExtras pae;
7289 Bundle extras = new Bundle();
7290 synchronized (this) {
7291 ActivityRecord activity = mMainStack.mResumedActivity;
7292 if (activity == null) {
7293 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7294 return null;
7295 }
7296 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7297 if (activity.app == null || activity.app.thread == null) {
7298 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7299 return extras;
7300 }
7301 if (activity.app.pid == Binder.getCallingPid()) {
7302 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7303 return extras;
7304 }
7305 pae = new PendingActivityExtras(activity);
7306 try {
7307 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7308 mPendingActivityExtras.add(pae);
7309 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7310 } catch (RemoteException e) {
7311 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7312 return extras;
7313 }
7314 }
7315 synchronized (pae) {
7316 while (!pae.haveResult) {
7317 try {
7318 pae.wait();
7319 } catch (InterruptedException e) {
7320 }
7321 }
7322 if (pae.result != null) {
7323 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7324 }
7325 }
7326 synchronized (this) {
7327 mPendingActivityExtras.remove(pae);
7328 mHandler.removeCallbacks(pae);
7329 }
7330 return extras;
7331 }
7332
7333 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7334 PendingActivityExtras pae = (PendingActivityExtras)token;
7335 synchronized (pae) {
7336 pae.result = extras;
7337 pae.haveResult = true;
7338 pae.notifyAll();
7339 }
7340 }
7341
Jeff Sharkeya4620792011-05-20 15:29:23 -07007342 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007343 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7344 "registerProcessObserver()");
7345 synchronized (this) {
7346 mProcessObservers.register(observer);
7347 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007348 }
7349
7350 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007351 synchronized (this) {
7352 mProcessObservers.unregister(observer);
7353 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007354 }
7355
Daniel Sandler69a48172010-06-23 16:29:36 -04007356 public void setImmersive(IBinder token, boolean immersive) {
7357 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007358 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007359 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007360 throw new IllegalArgumentException();
7361 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007362 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007363
7364 // update associated state if we're frontmost
7365 if (r == mFocusedActivity) {
7366 if (DEBUG_IMMERSIVE) {
7367 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7368 }
7369 applyUpdateLockStateLocked(r);
7370 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007371 }
7372 }
7373
7374 public boolean isImmersive(IBinder token) {
7375 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007376 ActivityRecord r = mMainStack.isInStackLocked(token);
7377 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007378 throw new IllegalArgumentException();
7379 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007380 return r.immersive;
7381 }
7382 }
7383
7384 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007385 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007386 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007387 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007388 return (r != null) ? r.immersive : false;
7389 }
7390 }
7391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 public final void enterSafeMode() {
7393 synchronized(this) {
7394 // It only makes sense to do this before the system is ready
7395 // and started launching other packages.
7396 if (!mSystemReady) {
7397 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007398 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007399 } catch (RemoteException e) {
7400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007401 }
7402 }
7403 }
7404
Jeff Brownb09abc12011-01-13 21:08:27 -08007405 public final void showSafeModeOverlay() {
7406 View v = LayoutInflater.from(mContext).inflate(
7407 com.android.internal.R.layout.safe_mode, null);
7408 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7409 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7410 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7411 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007412 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007413 lp.format = v.getBackground().getOpacity();
7414 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7415 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007416 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007417 ((WindowManager)mContext.getSystemService(
7418 Context.WINDOW_SERVICE)).addView(v, lp);
7419 }
7420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 public void noteWakeupAlarm(IIntentSender sender) {
7422 if (!(sender instanceof PendingIntentRecord)) {
7423 return;
7424 }
7425 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7426 synchronized (stats) {
7427 if (mBatteryStatsService.isOnBattery()) {
7428 mBatteryStatsService.enforceCallingPermission();
7429 PendingIntentRecord rec = (PendingIntentRecord)sender;
7430 int MY_UID = Binder.getCallingUid();
7431 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7432 BatteryStatsImpl.Uid.Pkg pkg =
7433 stats.getPackageStatsLocked(uid, rec.key.packageName);
7434 pkg.incWakeupsLocked();
7435 }
7436 }
7437 }
7438
Dianne Hackborn64825172011-03-02 21:32:58 -08007439 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007441 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007442 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007443 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 // XXX Note: don't acquire main activity lock here, because the window
7445 // manager calls in with its locks held.
7446
7447 boolean killed = false;
7448 synchronized (mPidsSelfLocked) {
7449 int[] types = new int[pids.length];
7450 int worstType = 0;
7451 for (int i=0; i<pids.length; i++) {
7452 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7453 if (proc != null) {
7454 int type = proc.setAdj;
7455 types[i] = type;
7456 if (type > worstType) {
7457 worstType = type;
7458 }
7459 }
7460 }
7461
Dianne Hackborn64825172011-03-02 21:32:58 -08007462 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007463 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007464 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7465 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007466 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007468
7469 // If this is not a secure call, don't let it kill processes that
7470 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007471 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7472 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007473 }
7474
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007475 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 for (int i=0; i<pids.length; i++) {
7477 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7478 if (proc == null) {
7479 continue;
7480 }
7481 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007482 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007483 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007484 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007485 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007487 proc.killedBackground = true;
7488 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 }
7490 }
7491 }
7492 return killed;
7493 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007494
7495 @Override
7496 public boolean killProcessesBelowForeground(String reason) {
7497 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7498 throw new SecurityException("killProcessesBelowForeground() only available to system");
7499 }
7500
7501 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7502 }
7503
7504 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7505 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7506 throw new SecurityException("killProcessesBelowAdj() only available to system");
7507 }
7508
7509 boolean killed = false;
7510 synchronized (mPidsSelfLocked) {
7511 final int size = mPidsSelfLocked.size();
7512 for (int i = 0; i < size; i++) {
7513 final int pid = mPidsSelfLocked.keyAt(i);
7514 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7515 if (proc == null) continue;
7516
7517 final int adj = proc.setAdj;
7518 if (adj > belowAdj && !proc.killedBackground) {
7519 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007520 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7521 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007522 killed = true;
7523 proc.killedBackground = true;
7524 Process.killProcessQuiet(pid);
7525 }
7526 }
7527 }
7528 return killed;
7529 }
7530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007531 public final void startRunning(String pkg, String cls, String action,
7532 String data) {
7533 synchronized(this) {
7534 if (mStartRunning) {
7535 return;
7536 }
7537 mStartRunning = true;
7538 mTopComponent = pkg != null && cls != null
7539 ? new ComponentName(pkg, cls) : null;
7540 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7541 mTopData = data;
7542 if (!mSystemReady) {
7543 return;
7544 }
7545 }
7546
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007547 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007548 }
7549
7550 private void retrieveSettings() {
7551 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007552 String debugApp = Settings.Global.getString(
7553 resolver, Settings.Global.DEBUG_APP);
7554 boolean waitForDebugger = Settings.Global.getInt(
7555 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7556 boolean alwaysFinishActivities = Settings.Global.getInt(
7557 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558
7559 Configuration configuration = new Configuration();
7560 Settings.System.getConfiguration(resolver, configuration);
7561
7562 synchronized (this) {
7563 mDebugApp = mOrigDebugApp = debugApp;
7564 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7565 mAlwaysFinishActivities = alwaysFinishActivities;
7566 // This happens before any activities are started, so we can
7567 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007568 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007569 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007570 }
7571 }
7572
7573 public boolean testIsSystemReady() {
7574 // no need to synchronize(this) just to read & return the value
7575 return mSystemReady;
7576 }
7577
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007578 private static File getCalledPreBootReceiversFile() {
7579 File dataDir = Environment.getDataDirectory();
7580 File systemDir = new File(dataDir, "system");
7581 File fname = new File(systemDir, "called_pre_boots.dat");
7582 return fname;
7583 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007584
7585 static final int LAST_DONE_VERSION = 10000;
7586
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007587 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7588 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7589 File file = getCalledPreBootReceiversFile();
7590 FileInputStream fis = null;
7591 try {
7592 fis = new FileInputStream(file);
7593 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007594 int fvers = dis.readInt();
7595 if (fvers == LAST_DONE_VERSION) {
7596 String vers = dis.readUTF();
7597 String codename = dis.readUTF();
7598 String build = dis.readUTF();
7599 if (android.os.Build.VERSION.RELEASE.equals(vers)
7600 && android.os.Build.VERSION.CODENAME.equals(codename)
7601 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7602 int num = dis.readInt();
7603 while (num > 0) {
7604 num--;
7605 String pkg = dis.readUTF();
7606 String cls = dis.readUTF();
7607 lastDoneReceivers.add(new ComponentName(pkg, cls));
7608 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007609 }
7610 }
7611 } catch (FileNotFoundException e) {
7612 } catch (IOException e) {
7613 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7614 } finally {
7615 if (fis != null) {
7616 try {
7617 fis.close();
7618 } catch (IOException e) {
7619 }
7620 }
7621 }
7622 return lastDoneReceivers;
7623 }
7624
7625 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7626 File file = getCalledPreBootReceiversFile();
7627 FileOutputStream fos = null;
7628 DataOutputStream dos = null;
7629 try {
7630 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7631 fos = new FileOutputStream(file);
7632 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007633 dos.writeInt(LAST_DONE_VERSION);
7634 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007635 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007636 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007637 dos.writeInt(list.size());
7638 for (int i=0; i<list.size(); i++) {
7639 dos.writeUTF(list.get(i).getPackageName());
7640 dos.writeUTF(list.get(i).getClassName());
7641 }
7642 } catch (IOException e) {
7643 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7644 file.delete();
7645 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007646 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007647 if (dos != null) {
7648 try {
7649 dos.close();
7650 } catch (IOException e) {
7651 // TODO Auto-generated catch block
7652 e.printStackTrace();
7653 }
7654 }
7655 }
7656 }
7657
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007658 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 synchronized(this) {
7660 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007661 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 return;
7663 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007664
7665 // Check to see if there are any update receivers to run.
7666 if (!mDidUpdate) {
7667 if (mWaitingUpdate) {
7668 return;
7669 }
7670 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7671 List<ResolveInfo> ris = null;
7672 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007673 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007674 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007675 } catch (RemoteException e) {
7676 }
7677 if (ris != null) {
7678 for (int i=ris.size()-1; i>=0; i--) {
7679 if ((ris.get(i).activityInfo.applicationInfo.flags
7680 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7681 ris.remove(i);
7682 }
7683 }
7684 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007685
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007686 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007687
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007688 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007689 for (int i=0; i<ris.size(); i++) {
7690 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007691 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7692 if (lastDoneReceivers.contains(comp)) {
7693 ris.remove(i);
7694 i--;
7695 }
7696 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007697
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007698 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007699 for (int i=0; i<ris.size(); i++) {
7700 ActivityInfo ai = ris.get(i).activityInfo;
7701 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7702 doneReceivers.add(comp);
7703 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007704 for (int j=0; j<users.length; j++) {
7705 IIntentReceiver finisher = null;
7706 if (i == ris.size()-1 && j == users.length-1) {
7707 finisher = new IIntentReceiver.Stub() {
7708 public void performReceive(Intent intent, int resultCode,
7709 String data, Bundle extras, boolean ordered,
7710 boolean sticky, int sendingUser) {
7711 // The raw IIntentReceiver interface is called
7712 // with the AM lock held, so redispatch to
7713 // execute our code without the lock.
7714 mHandler.post(new Runnable() {
7715 public void run() {
7716 synchronized (ActivityManagerService.this) {
7717 mDidUpdate = true;
7718 }
7719 writeLastDonePreBootReceivers(doneReceivers);
7720 showBootMessage(mContext.getText(
7721 R.string.android_upgrading_complete),
7722 false);
7723 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007724 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007725 });
7726 }
7727 };
7728 }
7729 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7730 + " for user " + users[j]);
7731 broadcastIntentLocked(null, null, intent, null, finisher,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007732 0, null, null, null, AppOpsManager.OP_NONE,
7733 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007734 users[j]);
7735 if (finisher != null) {
7736 mWaitingUpdate = true;
7737 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007738 }
7739 }
7740 }
7741 if (mWaitingUpdate) {
7742 return;
7743 }
7744 mDidUpdate = true;
7745 }
7746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 mSystemReady = true;
7748 if (!mStartRunning) {
7749 return;
7750 }
7751 }
7752
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007753 ArrayList<ProcessRecord> procsToKill = null;
7754 synchronized(mPidsSelfLocked) {
7755 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7756 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7757 if (!isAllowedWhileBooting(proc.info)){
7758 if (procsToKill == null) {
7759 procsToKill = new ArrayList<ProcessRecord>();
7760 }
7761 procsToKill.add(proc);
7762 }
7763 }
7764 }
7765
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007766 synchronized(this) {
7767 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007768 for (int i=procsToKill.size()-1; i>=0; i--) {
7769 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007770 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007771 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007772 }
7773 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007774
7775 // Now that we have cleaned up any update processes, we
7776 // are ready to start launching real processes and know that
7777 // we won't trample on them any more.
7778 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007779 }
7780
Joe Onorato8a9b2202010-02-26 18:56:32 -08007781 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007782 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 SystemClock.uptimeMillis());
7784
7785 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007786 // Make sure we have no pre-ready processes sitting around.
7787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7789 ResolveInfo ri = mContext.getPackageManager()
7790 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007791 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 CharSequence errorMsg = null;
7793 if (ri != null) {
7794 ActivityInfo ai = ri.activityInfo;
7795 ApplicationInfo app = ai.applicationInfo;
7796 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7797 mTopAction = Intent.ACTION_FACTORY_TEST;
7798 mTopData = null;
7799 mTopComponent = new ComponentName(app.packageName,
7800 ai.name);
7801 } else {
7802 errorMsg = mContext.getResources().getText(
7803 com.android.internal.R.string.factorytest_not_system);
7804 }
7805 } else {
7806 errorMsg = mContext.getResources().getText(
7807 com.android.internal.R.string.factorytest_no_action);
7808 }
7809 if (errorMsg != null) {
7810 mTopAction = null;
7811 mTopData = null;
7812 mTopComponent = null;
7813 Message msg = Message.obtain();
7814 msg.what = SHOW_FACTORY_ERROR_MSG;
7815 msg.getData().putCharSequence("msg", errorMsg);
7816 mHandler.sendMessage(msg);
7817 }
7818 }
7819 }
7820
7821 retrieveSettings();
7822
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007823 if (goingCallback != null) goingCallback.run();
7824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 synchronized (this) {
7826 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7827 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007828 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007829 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 if (apps != null) {
7831 int N = apps.size();
7832 int i;
7833 for (i=0; i<N; i++) {
7834 ApplicationInfo info
7835 = (ApplicationInfo)apps.get(i);
7836 if (info != null &&
7837 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007838 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 }
7840 }
7841 }
7842 } catch (RemoteException ex) {
7843 // pm is in same process, this will never happen.
7844 }
7845 }
7846
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007847 // Start up initial activity.
7848 mBooting = true;
7849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007851 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 Message msg = Message.obtain();
7853 msg.what = SHOW_UID_ERROR_MSG;
7854 mHandler.sendMessage(msg);
7855 }
7856 } catch (RemoteException e) {
7857 }
7858
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007859 long ident = Binder.clearCallingIdentity();
7860 try {
7861 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007862 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7863 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007864 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7865 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007866 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007867 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007868 intent = new Intent(Intent.ACTION_USER_STARTING);
7869 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7870 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7871 broadcastIntentLocked(null, null, intent,
7872 null, new IIntentReceiver.Stub() {
7873 @Override
7874 public void performReceive(Intent intent, int resultCode, String data,
7875 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7876 throws RemoteException {
7877 }
7878 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007879 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007880 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007881 } finally {
7882 Binder.restoreCallingIdentity(ident);
7883 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007884 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007885 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 }
7887 }
7888
Dan Egnorb7f03672009-12-09 16:22:32 -08007889 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007890 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007892 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007893 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 startAppProblemLocked(app);
7895 app.stopFreezingAllLocked();
7896 return handleAppCrashLocked(app);
7897 }
7898
Dan Egnorb7f03672009-12-09 16:22:32 -08007899 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007900 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007902 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007903 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7904 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 startAppProblemLocked(app);
7906 app.stopFreezingAllLocked();
7907 }
7908
7909 /**
7910 * Generate a process error record, suitable for attachment to a ProcessRecord.
7911 *
7912 * @param app The ProcessRecord in which the error occurred.
7913 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7914 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007915 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 * @param shortMsg Short message describing the crash.
7917 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007918 * @param stackTrace Full crash stack trace, may be null.
7919 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 * @return Returns a fully-formed AppErrorStateInfo record.
7921 */
7922 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007923 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 report.condition = condition;
7927 report.processName = app.processName;
7928 report.pid = app.pid;
7929 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007930 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 report.shortMsg = shortMsg;
7932 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007933 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934
7935 return report;
7936 }
7937
Dan Egnor42471dd2010-01-07 17:25:22 -08007938 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 synchronized (this) {
7940 app.crashing = false;
7941 app.crashingReport = null;
7942 app.notResponding = false;
7943 app.notRespondingReport = null;
7944 if (app.anrDialog == fromDialog) {
7945 app.anrDialog = null;
7946 }
7947 if (app.waitDialog == fromDialog) {
7948 app.waitDialog = null;
7949 }
7950 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007951 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007952 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007953 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07007954 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007955 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 }
7958 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007959
Dan Egnorb7f03672009-12-09 16:22:32 -08007960 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007961 if (mHeadless) {
7962 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7963 return false;
7964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007965 long now = SystemClock.uptimeMillis();
7966
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007967 Long crashTime;
7968 if (!app.isolated) {
7969 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7970 } else {
7971 crashTime = null;
7972 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007973 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007975 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007977 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007978 app.userId, app.info.processName, app.uid);
Craig Mautnercae015f2013-02-08 14:31:27 -08007979 mMainStack.handleAppCrashLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 if (!app.persistent) {
7981 // We don't want to start this process again until the user
7982 // explicitly does so... but for persistent process, we really
7983 // need to keep it running. If a persistent process is actually
7984 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007985 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007987 if (!app.isolated) {
7988 // XXX We don't have a way to mark isolated processes
7989 // as bad, since they don't have a peristent identity.
7990 mBadProcesses.put(app.info.processName, app.uid, now);
7991 mProcessCrashTimes.remove(app.info.processName, app.uid);
7992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007995 // Don't let services in this process be restarted and potentially
7996 // annoy the user repeatedly. Unless it is persistent, since those
7997 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007998 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007999 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 return false;
8001 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008002 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008003 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008004 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008005 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008006 // If the top running activity is from this crashing
8007 // process, then terminate it to avoid getting in a loop.
8008 Slog.w(TAG, " Force finishing activity "
8009 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008010 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008011 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008012 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008013 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008014 // stopped, to avoid a situation where one will get
8015 // re-start our crashing activity once it gets resumed again.
8016 index--;
8017 if (index >= 0) {
Craig Mautnercae015f2013-02-08 14:31:27 -08008018 r = mMainStack.getActivityAtIndex(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008019 if (r.state == ActivityState.RESUMED
8020 || r.state == ActivityState.PAUSING
8021 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008022 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008023 Slog.w(TAG, " Force finishing activity "
8024 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008025 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008026 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008027 }
8028 }
8029 }
8030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 }
8032
8033 // Bump up the crash count of any services currently running in the proc.
8034 if (app.services.size() != 0) {
8035 // Any services running in the application need to be placed
8036 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008037 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008039 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 sr.crashCount++;
8041 }
8042 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008043
8044 // If the crashing process is what we consider to be the "home process" and it has been
8045 // replaced by a third-party app, clear the package preferred activities from packages
8046 // with a home activity running in the process to prevent a repeatedly crashing app
8047 // from blocking the user to manually clear the list.
8048 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8049 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8050 Iterator it = mHomeProcess.activities.iterator();
8051 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008052 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008053 if (r.isHomeActivity) {
8054 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8055 try {
8056 ActivityThread.getPackageManager()
8057 .clearPackagePreferredActivities(r.packageName);
8058 } catch (RemoteException c) {
8059 // pm is in same process, this will never happen.
8060 }
8061 }
8062 }
8063 }
8064
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008065 if (!app.isolated) {
8066 // XXX Can't keep track of crash times for isolated processes,
8067 // because they don't have a perisistent identity.
8068 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8069 }
8070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008071 return true;
8072 }
8073
8074 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008075 if (app.userId == mCurrentUserId) {
8076 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8077 mContext, app.info.packageName, app.info.flags);
8078 } else {
8079 // If this app is not running under the current user, then we
8080 // can't give it a report button because that would require
8081 // launching the report UI under a different user.
8082 app.errorReportReceiver = null;
8083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 skipCurrentReceiverLocked(app);
8085 }
8086
8087 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008088 for (BroadcastQueue queue : mBroadcastQueues) {
8089 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 }
8091 }
8092
Dan Egnor60d87622009-12-16 16:32:58 -08008093 /**
8094 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8095 * The application process will exit immediately after this call returns.
8096 * @param app object of the crashing app, null for the system server
8097 * @param crashInfo describing the exception
8098 */
8099 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008100 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008101 final String processName = app == null ? "system_server"
8102 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008103
8104 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008105 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008106 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008107 crashInfo.exceptionClassName,
8108 crashInfo.exceptionMessage,
8109 crashInfo.throwFileName,
8110 crashInfo.throwLineNumber);
8111
Jeff Sharkeya353d262011-10-28 11:12:06 -07008112 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008113
8114 crashApplication(r, crashInfo);
8115 }
8116
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008117 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008118 IBinder app,
8119 int violationMask,
8120 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008121 ProcessRecord r = findAppProcess(app, "StrictMode");
8122 if (r == null) {
8123 return;
8124 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008125
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008126 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008127 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008128 boolean logIt = true;
8129 synchronized (mAlreadyLoggedViolatedStacks) {
8130 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8131 logIt = false;
8132 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008133 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008134 // the relative pain numbers, without logging all
8135 // the stack traces repeatedly. We'd want to do
8136 // likewise in the client code, which also does
8137 // dup suppression, before the Binder call.
8138 } else {
8139 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8140 mAlreadyLoggedViolatedStacks.clear();
8141 }
8142 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8143 }
8144 }
8145 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008146 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008147 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008148 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008149
8150 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8151 AppErrorResult result = new AppErrorResult();
8152 synchronized (this) {
8153 final long origId = Binder.clearCallingIdentity();
8154
8155 Message msg = Message.obtain();
8156 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8157 HashMap<String, Object> data = new HashMap<String, Object>();
8158 data.put("result", result);
8159 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008160 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008161 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008162 msg.obj = data;
8163 mHandler.sendMessage(msg);
8164
8165 Binder.restoreCallingIdentity(origId);
8166 }
8167 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008168 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008169 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008170 }
8171
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008172 // Depending on the policy in effect, there could be a bunch of
8173 // these in quick succession so we try to batch these together to
8174 // minimize disk writes, number of dropbox entries, and maximize
8175 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008176 private void logStrictModeViolationToDropBox(
8177 ProcessRecord process,
8178 StrictMode.ViolationInfo info) {
8179 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008180 return;
8181 }
8182 final boolean isSystemApp = process == null ||
8183 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8184 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008185 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008186 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8187 final DropBoxManager dbox = (DropBoxManager)
8188 mContext.getSystemService(Context.DROPBOX_SERVICE);
8189
8190 // Exit early if the dropbox isn't configured to accept this report type.
8191 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8192
8193 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008194 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008195 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8196 synchronized (sb) {
8197 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008198 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008199 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8200 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008201 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8202 if (info.violationNumThisLoop != 0) {
8203 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8204 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008205 if (info.numAnimationsRunning != 0) {
8206 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8207 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008208 if (info.broadcastIntentAction != null) {
8209 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8210 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008211 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008212 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008213 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008214 if (info.numInstances != -1) {
8215 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8216 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008217 if (info.tags != null) {
8218 for (String tag : info.tags) {
8219 sb.append("Span-Tag: ").append(tag).append("\n");
8220 }
8221 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008222 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008223 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8224 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008225 }
8226 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008227
8228 // Only buffer up to ~64k. Various logging bits truncate
8229 // things at 128k.
8230 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008231 }
8232
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008233 // Flush immediately if the buffer's grown too large, or this
8234 // is a non-system app. Non-system apps are isolated with a
8235 // different tag & policy and not batched.
8236 //
8237 // Batching is useful during internal testing with
8238 // StrictMode settings turned up high. Without batching,
8239 // thousands of separate files could be created on boot.
8240 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008241 new Thread("Error dump: " + dropboxTag) {
8242 @Override
8243 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008244 String report;
8245 synchronized (sb) {
8246 report = sb.toString();
8247 sb.delete(0, sb.length());
8248 sb.trimToSize();
8249 }
8250 if (report.length() != 0) {
8251 dbox.addText(dropboxTag, report);
8252 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008253 }
8254 }.start();
8255 return;
8256 }
8257
8258 // System app batching:
8259 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008260 // An existing dropbox-writing thread is outstanding, so
8261 // we don't need to start it up. The existing thread will
8262 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008263 return;
8264 }
8265
8266 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8267 // (After this point, we shouldn't access AMS internal data structures.)
8268 new Thread("Error dump: " + dropboxTag) {
8269 @Override
8270 public void run() {
8271 // 5 second sleep to let stacks arrive and be batched together
8272 try {
8273 Thread.sleep(5000); // 5 seconds
8274 } catch (InterruptedException e) {}
8275
8276 String errorReport;
8277 synchronized (mStrictModeBuffer) {
8278 errorReport = mStrictModeBuffer.toString();
8279 if (errorReport.length() == 0) {
8280 return;
8281 }
8282 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8283 mStrictModeBuffer.trimToSize();
8284 }
8285 dbox.addText(dropboxTag, errorReport);
8286 }
8287 }.start();
8288 }
8289
Dan Egnor60d87622009-12-16 16:32:58 -08008290 /**
8291 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8292 * @param app object of the crashing app, null for the system server
8293 * @param tag reported by the caller
8294 * @param crashInfo describing the context of the error
8295 * @return true if the process should exit immediately (WTF is fatal)
8296 */
8297 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008298 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008299 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008300 final String processName = app == null ? "system_server"
8301 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008302
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008303 EventLog.writeEvent(EventLogTags.AM_WTF,
8304 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008305 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008306 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008307 tag, crashInfo.exceptionMessage);
8308
Jeff Sharkeya353d262011-10-28 11:12:06 -07008309 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008310
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008311 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008312 Settings.Global.getInt(mContext.getContentResolver(),
8313 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008314 crashApplication(r, crashInfo);
8315 return true;
8316 } else {
8317 return false;
8318 }
8319 }
8320
8321 /**
8322 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8323 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8324 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008325 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008326 if (app == null) {
8327 return null;
8328 }
8329
8330 synchronized (this) {
8331 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8332 final int NA = apps.size();
8333 for (int ia=0; ia<NA; ia++) {
8334 ProcessRecord p = apps.valueAt(ia);
8335 if (p.thread != null && p.thread.asBinder() == app) {
8336 return p;
8337 }
8338 }
8339 }
8340
Dianne Hackborncb44d962011-03-10 17:02:27 -08008341 Slog.w(TAG, "Can't find mystery application for " + reason
8342 + " from pid=" + Binder.getCallingPid()
8343 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008344 return null;
8345 }
8346 }
8347
8348 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008349 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8350 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008351 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008352 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8353 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008354 // Watchdog thread ends up invoking this function (with
8355 // a null ProcessRecord) to add the stack file to dropbox.
8356 // Do not acquire a lock on this (am) in such cases, as it
8357 // could cause a potential deadlock, if and when watchdog
8358 // is invoked due to unavailability of lock on am and it
8359 // would prevent watchdog from killing system_server.
8360 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008361 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008362 return;
8363 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008364 // Note: ProcessRecord 'process' is guarded by the service
8365 // instance. (notably process.pkgList, which could otherwise change
8366 // concurrently during execution of this method)
8367 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008368 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008369 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008370 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008371 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8372 for (String pkg : process.pkgList) {
8373 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008374 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008375 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008376 if (pi != null) {
8377 sb.append(" v").append(pi.versionCode);
8378 if (pi.versionName != null) {
8379 sb.append(" (").append(pi.versionName).append(")");
8380 }
8381 }
8382 } catch (RemoteException e) {
8383 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008384 }
Dan Egnora455d192010-03-12 08:52:28 -08008385 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008386 }
Dan Egnora455d192010-03-12 08:52:28 -08008387 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008388 }
8389
8390 private static String processClass(ProcessRecord process) {
8391 if (process == null || process.pid == MY_PID) {
8392 return "system_server";
8393 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8394 return "system_app";
8395 } else {
8396 return "data_app";
8397 }
8398 }
8399
8400 /**
8401 * Write a description of an error (crash, WTF, ANR) to the drop box.
8402 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8403 * @param process which caused the error, null means the system server
8404 * @param activity which triggered the error, null if unknown
8405 * @param parent activity related to the error, null if unknown
8406 * @param subject line related to the error, null if absent
8407 * @param report in long form describing the error, null if absent
8408 * @param logFile to include in the report, null if none
8409 * @param crashInfo giving an application stack trace, null if absent
8410 */
8411 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008412 ProcessRecord process, String processName, ActivityRecord activity,
8413 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008414 final String report, final File logFile,
8415 final ApplicationErrorReport.CrashInfo crashInfo) {
8416 // NOTE -- this must never acquire the ActivityManagerService lock,
8417 // otherwise the watchdog may be prevented from resetting the system.
8418
8419 final String dropboxTag = processClass(process) + "_" + eventType;
8420 final DropBoxManager dbox = (DropBoxManager)
8421 mContext.getSystemService(Context.DROPBOX_SERVICE);
8422
8423 // Exit early if the dropbox isn't configured to accept this report type.
8424 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8425
8426 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008427 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008428 if (activity != null) {
8429 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8430 }
8431 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8432 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8433 }
8434 if (parent != null && parent != activity) {
8435 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8436 }
8437 if (subject != null) {
8438 sb.append("Subject: ").append(subject).append("\n");
8439 }
8440 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008441 if (Debug.isDebuggerConnected()) {
8442 sb.append("Debugger: Connected\n");
8443 }
Dan Egnora455d192010-03-12 08:52:28 -08008444 sb.append("\n");
8445
8446 // Do the rest in a worker thread to avoid blocking the caller on I/O
8447 // (After this point, we shouldn't access AMS internal data structures.)
8448 Thread worker = new Thread("Error dump: " + dropboxTag) {
8449 @Override
8450 public void run() {
8451 if (report != null) {
8452 sb.append(report);
8453 }
8454 if (logFile != null) {
8455 try {
8456 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8457 } catch (IOException e) {
8458 Slog.e(TAG, "Error reading " + logFile, e);
8459 }
8460 }
8461 if (crashInfo != null && crashInfo.stackTrace != null) {
8462 sb.append(crashInfo.stackTrace);
8463 }
8464
Jeff Sharkey625239a2012-09-26 22:03:49 -07008465 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8466 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008467 if (lines > 0) {
8468 sb.append("\n");
8469
8470 // Merge several logcat streams, and take the last N lines
8471 InputStreamReader input = null;
8472 try {
8473 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8474 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8475 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8476
8477 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8478 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8479 input = new InputStreamReader(logcat.getInputStream());
8480
8481 int num;
8482 char[] buf = new char[8192];
8483 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8484 } catch (IOException e) {
8485 Slog.e(TAG, "Error running logcat", e);
8486 } finally {
8487 if (input != null) try { input.close(); } catch (IOException e) {}
8488 }
8489 }
8490
8491 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008492 }
Dan Egnora455d192010-03-12 08:52:28 -08008493 };
8494
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008495 if (process == null) {
8496 // If process is null, we are being called from some internal code
8497 // and may be about to die -- run this synchronously.
8498 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008499 } else {
8500 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008501 }
8502 }
8503
8504 /**
8505 * Bring up the "unexpected error" dialog box for a crashing app.
8506 * Deal with edge cases (intercepts from instrumented applications,
8507 * ActivityController, error intent receivers, that sort of thing).
8508 * @param r the application crashing
8509 * @param crashInfo describing the failure
8510 */
8511 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008512 long timeMillis = System.currentTimeMillis();
8513 String shortMsg = crashInfo.exceptionClassName;
8514 String longMsg = crashInfo.exceptionMessage;
8515 String stackTrace = crashInfo.stackTrace;
8516 if (shortMsg != null && longMsg != null) {
8517 longMsg = shortMsg + ": " + longMsg;
8518 } else if (shortMsg != null) {
8519 longMsg = shortMsg;
8520 }
8521
Dan Egnor60d87622009-12-16 16:32:58 -08008522 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008524 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 try {
8526 String name = r != null ? r.processName : null;
8527 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008528 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008529 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008530 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 + " at watcher's request");
8532 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008533 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 }
8535 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008536 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 }
8538 }
8539
8540 final long origId = Binder.clearCallingIdentity();
8541
8542 // If this process is running instrumentation, finish it.
8543 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008544 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008546 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8547 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 Bundle info = new Bundle();
8549 info.putString("shortMsg", shortMsg);
8550 info.putString("longMsg", longMsg);
8551 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8552 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008553 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 }
8555
Dan Egnor60d87622009-12-16 16:32:58 -08008556 // If we can't identify the process or it's already exceeded its crash quota,
8557 // quit right away without showing a crash dialog.
8558 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008560 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 }
8562
8563 Message msg = Message.obtain();
8564 msg.what = SHOW_ERROR_MSG;
8565 HashMap data = new HashMap();
8566 data.put("result", result);
8567 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 msg.obj = data;
8569 mHandler.sendMessage(msg);
8570
8571 Binder.restoreCallingIdentity(origId);
8572 }
8573
8574 int res = result.get();
8575
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008576 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008578 if (r != null && !r.isolated) {
8579 // XXX Can't keep track of crash time for isolated processes,
8580 // since they don't have a persistent identity.
8581 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 SystemClock.uptimeMillis());
8583 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008584 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008585 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008586 }
8587 }
8588
8589 if (appErrorIntent != null) {
8590 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008591 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008592 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008593 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008597
8598 Intent createAppErrorIntentLocked(ProcessRecord r,
8599 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8600 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008601 if (report == null) {
8602 return null;
8603 }
8604 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8605 result.setComponent(r.errorReportReceiver);
8606 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8607 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8608 return result;
8609 }
8610
Dan Egnorb7f03672009-12-09 16:22:32 -08008611 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8612 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008613 if (r.errorReportReceiver == null) {
8614 return null;
8615 }
8616
8617 if (!r.crashing && !r.notResponding) {
8618 return null;
8619 }
8620
Dan Egnorb7f03672009-12-09 16:22:32 -08008621 ApplicationErrorReport report = new ApplicationErrorReport();
8622 report.packageName = r.info.packageName;
8623 report.installerPackageName = r.errorReportReceiver.getPackageName();
8624 report.processName = r.processName;
8625 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008626 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008627
Dan Egnorb7f03672009-12-09 16:22:32 -08008628 if (r.crashing) {
8629 report.type = ApplicationErrorReport.TYPE_CRASH;
8630 report.crashInfo = crashInfo;
8631 } else if (r.notResponding) {
8632 report.type = ApplicationErrorReport.TYPE_ANR;
8633 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008634
Dan Egnorb7f03672009-12-09 16:22:32 -08008635 report.anrInfo.activity = r.notRespondingReport.tag;
8636 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8637 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008638 }
8639
Dan Egnorb7f03672009-12-09 16:22:32 -08008640 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008641 }
8642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008644 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 // assume our apps are happy - lazy create the list
8646 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8647
Dianne Hackborn0c380492012-08-20 17:23:30 -07008648 final boolean allUsers = ActivityManager.checkUidPermission(
8649 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8650 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8651 int userId = UserHandle.getUserId(Binder.getCallingUid());
8652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 synchronized (this) {
8654
8655 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008656 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8657 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008658 if (!allUsers && app.userId != userId) {
8659 continue;
8660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8662 // This one's in trouble, so we'll generate a report for it
8663 // crashes are higher priority (in case there's a crash *and* an anr)
8664 ActivityManager.ProcessErrorStateInfo report = null;
8665 if (app.crashing) {
8666 report = app.crashingReport;
8667 } else if (app.notResponding) {
8668 report = app.notRespondingReport;
8669 }
8670
8671 if (report != null) {
8672 if (errList == null) {
8673 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8674 }
8675 errList.add(report);
8676 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008677 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 " crashing = " + app.crashing +
8679 " notResponding = " + app.notResponding);
8680 }
8681 }
8682 }
8683 }
8684
8685 return errList;
8686 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008687
8688 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008689 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008690 if (currApp != null) {
8691 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8692 }
8693 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008694 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8695 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008696 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8697 if (currApp != null) {
8698 currApp.lru = 0;
8699 }
8700 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008701 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008702 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8703 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8704 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8705 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8706 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8707 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8708 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8709 } else {
8710 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8711 }
8712 }
8713
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008714 private void fillInProcMemInfo(ProcessRecord app,
8715 ActivityManager.RunningAppProcessInfo outInfo) {
8716 outInfo.pid = app.pid;
8717 outInfo.uid = app.info.uid;
8718 if (mHeavyWeightProcess == app) {
8719 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8720 }
8721 if (app.persistent) {
8722 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8723 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008724 if (app.hasActivities) {
8725 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8726 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008727 outInfo.lastTrimLevel = app.trimMemoryLevel;
8728 int adj = app.curAdj;
8729 outInfo.importance = oomAdjToImportance(adj, outInfo);
8730 outInfo.importanceReasonCode = app.adjTypeCode;
8731 }
8732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008734 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 // Lazy instantiation of list
8736 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008737 final boolean allUsers = ActivityManager.checkUidPermission(
8738 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8739 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8740 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 synchronized (this) {
8742 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008743 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8744 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008745 if (!allUsers && app.userId != userId) {
8746 continue;
8747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8749 // Generate process state info for running application
8750 ActivityManager.RunningAppProcessInfo currApp =
8751 new ActivityManager.RunningAppProcessInfo(app.processName,
8752 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008753 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008754 if (app.adjSource instanceof ProcessRecord) {
8755 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008756 currApp.importanceReasonImportance = oomAdjToImportance(
8757 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008758 } else if (app.adjSource instanceof ActivityRecord) {
8759 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008760 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8761 }
8762 if (app.adjTarget instanceof ComponentName) {
8763 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8764 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008765 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 // + " lru=" + currApp.lru);
8767 if (runList == null) {
8768 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8769 }
8770 runList.add(currApp);
8771 }
8772 }
8773 }
8774 return runList;
8775 }
8776
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008777 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008778 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008779 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8780 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8781 if (runningApps != null && runningApps.size() > 0) {
8782 Set<String> extList = new HashSet<String>();
8783 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8784 if (app.pkgList != null) {
8785 for (String pkg : app.pkgList) {
8786 extList.add(pkg);
8787 }
8788 }
8789 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008790 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008791 for (String pkg : extList) {
8792 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008793 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008794 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8795 retList.add(info);
8796 }
8797 } catch (RemoteException e) {
8798 }
8799 }
8800 }
8801 return retList;
8802 }
8803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008805 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8806 enforceNotIsolatedCaller("getMyMemoryState");
8807 synchronized (this) {
8808 ProcessRecord proc;
8809 synchronized (mPidsSelfLocked) {
8810 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8811 }
8812 fillInProcMemInfo(proc, outInfo);
8813 }
8814 }
8815
8816 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 if (checkCallingPermission(android.Manifest.permission.DUMP)
8819 != PackageManager.PERMISSION_GRANTED) {
8820 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8821 + Binder.getCallingPid()
8822 + ", uid=" + Binder.getCallingUid()
8823 + " without permission "
8824 + android.Manifest.permission.DUMP);
8825 return;
8826 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008827
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008829 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008830 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831
8832 int opti = 0;
8833 while (opti < args.length) {
8834 String opt = args[opti];
8835 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8836 break;
8837 }
8838 opti++;
8839 if ("-a".equals(opt)) {
8840 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008841 } else if ("-c".equals(opt)) {
8842 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008843 } else if ("-h".equals(opt)) {
8844 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008845 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008846 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008847 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008848 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008849 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8850 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008851 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008852 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008853 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008854 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008855 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008857 pw.println(" all: dump all activities");
8858 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008859 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008860 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8861 pw.println(" a partial substring in a component name, a");
8862 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008863 pw.println(" -a: include all available server state.");
8864 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 } else {
8867 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008869 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008870
8871 long origId = Binder.clearCallingIdentity();
8872 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008873 // Is the caller requesting to dump a particular piece of data?
8874 if (opti < args.length) {
8875 String cmd = args[opti];
8876 opti++;
8877 if ("activities".equals(cmd) || "a".equals(cmd)) {
8878 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008879 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008882 String[] newArgs;
8883 String name;
8884 if (opti >= args.length) {
8885 name = null;
8886 newArgs = EMPTY_STRING_ARRAY;
8887 } else {
8888 name = args[opti];
8889 opti++;
8890 newArgs = new String[args.length - opti];
8891 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8892 args.length - opti);
8893 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008894 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008895 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008896 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008898 String[] newArgs;
8899 String name;
8900 if (opti >= args.length) {
8901 name = null;
8902 newArgs = EMPTY_STRING_ARRAY;
8903 } else {
8904 name = args[opti];
8905 opti++;
8906 newArgs = new String[args.length - opti];
8907 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8908 args.length - opti);
8909 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008911 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008913 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008914 String[] newArgs;
8915 String name;
8916 if (opti >= args.length) {
8917 name = null;
8918 newArgs = EMPTY_STRING_ARRAY;
8919 } else {
8920 name = args[opti];
8921 opti++;
8922 newArgs = new String[args.length - opti];
8923 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8924 args.length - opti);
8925 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008926 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008927 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008929 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8930 synchronized (this) {
8931 dumpOomLocked(fd, pw, args, opti, true);
8932 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008933 } else if ("provider".equals(cmd)) {
8934 String[] newArgs;
8935 String name;
8936 if (opti >= args.length) {
8937 name = null;
8938 newArgs = EMPTY_STRING_ARRAY;
8939 } else {
8940 name = args[opti];
8941 opti++;
8942 newArgs = new String[args.length - opti];
8943 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8944 }
8945 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8946 pw.println("No providers match: " + name);
8947 pw.println("Use -h for help.");
8948 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008949 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8950 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008951 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008952 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008953 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008954 String[] newArgs;
8955 String name;
8956 if (opti >= args.length) {
8957 name = null;
8958 newArgs = EMPTY_STRING_ARRAY;
8959 } else {
8960 name = args[opti];
8961 opti++;
8962 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008963 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8964 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008965 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008966 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008967 pw.println("No services match: " + name);
8968 pw.println("Use -h for help.");
8969 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008970 } else if ("package".equals(cmd)) {
8971 String[] newArgs;
8972 if (opti >= args.length) {
8973 pw.println("package: no package name specified");
8974 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 } else {
8976 dumpPackage = args[opti];
8977 opti++;
8978 newArgs = new String[args.length - opti];
8979 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8980 args.length - opti);
8981 args = newArgs;
8982 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008983 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8986 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008987 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008988 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008989 } else {
8990 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008991 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8992 pw.println("Bad activity command, or no activities match: " + cmd);
8993 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008994 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008995 }
8996 if (!more) {
8997 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008998 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009000 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009001
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 // No piece of data specified, dump everything.
9003 synchronized (this) {
9004 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009005 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 if (needSep) {
9007 pw.println(" ");
9008 }
9009 if (dumpAll) {
9010 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009012 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 if (needSep) {
9014 pw.println(" ");
9015 }
9016 if (dumpAll) {
9017 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 if (needSep) {
9021 pw.println(" ");
9022 }
9023 if (dumpAll) {
9024 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009026 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027 if (needSep) {
9028 pw.println(" ");
9029 }
9030 if (dumpAll) {
9031 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009033 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009034 if (needSep) {
9035 pw.println(" ");
9036 }
9037 if (dumpAll) {
9038 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009040 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009041 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009042 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009044
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009046 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9048 pw.println(" Main stack:");
Craig Mautnercae015f2013-02-08 14:31:27 -08009049 mMainStack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009050 pw.println(" ");
9051 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009052 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9053 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009054 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009058 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009060 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009064 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009066 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9067 pw.println(" ");
9068 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009069 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009071 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009072 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 pw.println(" ");
9074 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009075 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009076 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009080 if (mMainStack.mPausingActivity != null) {
9081 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009082 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009083 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009085 if (dumpAll) {
9086 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9087 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009088 pw.println(" mDismissKeyguardOnNextActivity: "
9089 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009092 if (mRecentTasks.size() > 0) {
9093 pw.println();
9094 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009095
9096 final int N = mRecentTasks.size();
9097 for (int i=0; i<N; i++) {
9098 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 if (dumpPackage != null) {
9100 if (tr.realActivity == null ||
9101 !dumpPackage.equals(tr.realActivity)) {
9102 continue;
9103 }
9104 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009105 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9106 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009107 if (dumpAll) {
9108 mRecentTasks.get(i).dump(pw, " ");
9109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009110 }
9111 }
9112
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 if (dumpAll) {
9114 pw.println(" ");
9115 pw.println(" mCurTask: " + mCurTask);
9116 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009117
9118 return true;
9119 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009120
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009122 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009123 boolean needSep = false;
9124 int numPers = 0;
9125
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009126 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9127
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009128 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9130 final int NA = procs.size();
9131 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009132 ProcessRecord r = procs.valueAt(ia);
9133 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9134 continue;
9135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 if (!needSep) {
9137 pw.println(" All known processes:");
9138 needSep = true;
9139 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009140 pw.print(r.persistent ? " *PERS*" : " *APP*");
9141 pw.print(" UID "); pw.print(procs.keyAt(ia));
9142 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 r.dump(pw, " ");
9144 if (r.persistent) {
9145 numPers++;
9146 }
9147 }
9148 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009149 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009150
9151 if (mIsolatedProcesses.size() > 0) {
9152 if (needSep) pw.println(" ");
9153 needSep = true;
9154 pw.println(" Isolated process list (sorted by uid):");
9155 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9156 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9157 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9158 continue;
9159 }
9160 pw.println(String.format("%sIsolated #%2d: %s",
9161 " ", i, r.toString()));
9162 }
9163 }
9164
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009165 if (mLruProcesses.size() > 0) {
9166 if (needSep) pw.println(" ");
9167 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009168 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009169 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009170 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 needSep = true;
9172 }
9173
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009174 if (dumpAll) {
9175 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 boolean printed = false;
9177 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9178 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9179 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9180 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009182 if (!printed) {
9183 if (needSep) pw.println(" ");
9184 needSep = true;
9185 pw.println(" PID mappings:");
9186 printed = true;
9187 }
9188 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9189 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 }
9191 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009192 }
9193
9194 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009195 synchronized (mPidsSelfLocked) {
9196 boolean printed = false;
9197 for (int i=0; i<mForegroundProcesses.size(); i++) {
9198 ProcessRecord r = mPidsSelfLocked.get(
9199 mForegroundProcesses.valueAt(i).pid);
9200 if (dumpPackage != null && (r == null
9201 || !dumpPackage.equals(r.info.packageName))) {
9202 continue;
9203 }
9204 if (!printed) {
9205 if (needSep) pw.println(" ");
9206 needSep = true;
9207 pw.println(" Foreground Processes:");
9208 printed = true;
9209 }
9210 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9211 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214 }
9215
9216 if (mPersistentStartingProcesses.size() > 0) {
9217 if (needSep) pw.println(" ");
9218 needSep = true;
9219 pw.println(" Persisent processes that are starting:");
9220 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009221 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 if (mRemovedProcesses.size() > 0) {
9225 if (needSep) pw.println(" ");
9226 needSep = true;
9227 pw.println(" Processes that are being removed:");
9228 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009229 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 }
9231
9232 if (mProcessesOnHold.size() > 0) {
9233 if (needSep) pw.println(" ");
9234 needSep = true;
9235 pw.println(" Processes that are on old until the system is ready:");
9236 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009239
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009240 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241
9242 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009243 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009244 long now = SystemClock.uptimeMillis();
9245 for (Map.Entry<String, SparseArray<Long>> procs
9246 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009247 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 SparseArray<Long> uids = procs.getValue();
9249 final int N = uids.size();
9250 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009251 int puid = uids.keyAt(i);
9252 ProcessRecord r = mProcessNames.get(pname, puid);
9253 if (dumpPackage != null && (r == null
9254 || !dumpPackage.equals(r.info.packageName))) {
9255 continue;
9256 }
9257 if (!printed) {
9258 if (needSep) pw.println(" ");
9259 needSep = true;
9260 pw.println(" Time since processes crashed:");
9261 printed = true;
9262 }
9263 pw.print(" Process "); pw.print(pname);
9264 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009266 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9267 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009268 }
9269 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009274 for (Map.Entry<String, SparseArray<Long>> procs
9275 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009276 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 SparseArray<Long> uids = procs.getValue();
9278 final int N = uids.size();
9279 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009280 int puid = uids.keyAt(i);
9281 ProcessRecord r = mProcessNames.get(pname, puid);
9282 if (dumpPackage != null && (r == null
9283 || !dumpPackage.equals(r.info.packageName))) {
9284 continue;
9285 }
9286 if (!printed) {
9287 if (needSep) pw.println(" ");
9288 needSep = true;
9289 pw.println(" Bad processes:");
9290 }
9291 pw.print(" Bad process "); pw.print(pname);
9292 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009293 pw.print(": crashed at time ");
9294 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 }
9296 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009298
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009299 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009300 pw.println(" mStartedUsers:");
9301 for (int i=0; i<mStartedUsers.size(); i++) {
9302 UserStartedState uss = mStartedUsers.valueAt(i);
9303 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009304 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009305 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009306 pw.print(" mStartedUserArray: [");
9307 for (int i=0; i<mStartedUserArray.length; i++) {
9308 if (i > 0) pw.print(", ");
9309 pw.print(mStartedUserArray[i]);
9310 }
9311 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009312 pw.print(" mUserLru: [");
9313 for (int i=0; i<mUserLru.size(); i++) {
9314 if (i > 0) pw.print(", ");
9315 pw.print(mUserLru.get(i));
9316 }
9317 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009318 if (dumpAll) {
9319 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9320 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009322 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009323 if (dumpAll) {
9324 StringBuilder sb = new StringBuilder(128);
9325 sb.append(" mPreviousProcessVisibleTime: ");
9326 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9327 pw.println(sb);
9328 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009329 if (mHeavyWeightProcess != null) {
9330 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9331 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009333 if (dumpAll) {
9334 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009335 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009336 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009337 for (Map.Entry<String, Integer> entry
9338 : mCompatModePackages.getPackages().entrySet()) {
9339 String pkg = entry.getKey();
9340 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009341 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9342 continue;
9343 }
9344 if (!printed) {
9345 pw.println(" mScreenCompatPackages:");
9346 printed = true;
9347 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009348 pw.print(" "); pw.print(pkg); pw.print(": ");
9349 pw.print(mode); pw.println();
9350 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009351 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009352 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009353 if (mSleeping || mWentToSleep || mLockScreenShown) {
9354 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9355 + " mLockScreenShown " + mLockScreenShown);
9356 }
9357 if (mShuttingDown) {
9358 pw.println(" mShuttingDown=" + mShuttingDown);
9359 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009360 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9361 || mOrigWaitForDebugger) {
9362 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9363 + " mDebugTransient=" + mDebugTransient
9364 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9365 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009366 if (mOpenGlTraceApp != null) {
9367 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9368 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009369 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9370 || mProfileFd != null) {
9371 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9372 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9373 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9374 + mAutoStopProfiler);
9375 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 if (mAlwaysFinishActivities || mController != null) {
9377 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9378 + " mController=" + mController);
9379 }
9380 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009383 + " mProcessesReady=" + mProcessesReady
9384 + " mSystemReady=" + mSystemReady);
9385 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009386 + " mBooted=" + mBooted
9387 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009388 pw.print(" mLastPowerCheckRealtime=");
9389 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9390 pw.println("");
9391 pw.print(" mLastPowerCheckUptime=");
9392 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9393 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009394 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9395 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009396 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009397 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9398 + " mNumHiddenProcs=" + mNumHiddenProcs
9399 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009400 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402
9403 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 }
9405
Dianne Hackborn287952c2010-09-22 22:34:31 -07009406 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009407 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009408 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009410 long now = SystemClock.uptimeMillis();
9411 for (int i=0; i<mProcessesToGc.size(); i++) {
9412 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009413 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9414 continue;
9415 }
9416 if (!printed) {
9417 if (needSep) pw.println(" ");
9418 needSep = true;
9419 pw.println(" Processes that are waiting to GC:");
9420 printed = true;
9421 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009422 pw.print(" Process "); pw.println(proc);
9423 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9424 pw.print(", last gced=");
9425 pw.print(now-proc.lastRequestedGc);
9426 pw.print(" ms ago, last lowMem=");
9427 pw.print(now-proc.lastLowMemory);
9428 pw.println(" ms ago");
9429
9430 }
9431 }
9432 return needSep;
9433 }
9434
9435 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9436 int opti, boolean dumpAll) {
9437 boolean needSep = false;
9438
9439 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009440 if (needSep) pw.println(" ");
9441 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009442 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009443 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009444 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009445 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9446 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9447 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9448 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9449 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009450 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009451 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009452 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009453 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009454 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009455 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009456
9457 if (needSep) pw.println(" ");
9458 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009459 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009460 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009462 needSep = true;
9463 }
9464
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009465 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009468 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009469 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009470 if (mHeavyWeightProcess != null) {
9471 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9472 }
9473
9474 return true;
9475 }
9476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009477 /**
9478 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009479 * - no provider specified: dump all the providers
9480 * - a flattened component name that matched an existing provider was specified as the
9481 * first arg: dump that one provider
9482 * - the first arg isn't the flattened component name of an existing provider:
9483 * dump all providers whose component contains the first arg as a substring
9484 */
9485 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9486 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009487 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009488 }
9489
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009490 static class ItemMatcher {
9491 ArrayList<ComponentName> components;
9492 ArrayList<String> strings;
9493 ArrayList<Integer> objects;
9494 boolean all;
9495
9496 ItemMatcher() {
9497 all = true;
9498 }
9499
9500 void build(String name) {
9501 ComponentName componentName = ComponentName.unflattenFromString(name);
9502 if (componentName != null) {
9503 if (components == null) {
9504 components = new ArrayList<ComponentName>();
9505 }
9506 components.add(componentName);
9507 all = false;
9508 } else {
9509 int objectId = 0;
9510 // Not a '/' separated full component name; maybe an object ID?
9511 try {
9512 objectId = Integer.parseInt(name, 16);
9513 if (objects == null) {
9514 objects = new ArrayList<Integer>();
9515 }
9516 objects.add(objectId);
9517 all = false;
9518 } catch (RuntimeException e) {
9519 // Not an integer; just do string match.
9520 if (strings == null) {
9521 strings = new ArrayList<String>();
9522 }
9523 strings.add(name);
9524 all = false;
9525 }
9526 }
9527 }
9528
9529 int build(String[] args, int opti) {
9530 for (; opti<args.length; opti++) {
9531 String name = args[opti];
9532 if ("--".equals(name)) {
9533 return opti+1;
9534 }
9535 build(name);
9536 }
9537 return opti;
9538 }
9539
9540 boolean match(Object object, ComponentName comp) {
9541 if (all) {
9542 return true;
9543 }
9544 if (components != null) {
9545 for (int i=0; i<components.size(); i++) {
9546 if (components.get(i).equals(comp)) {
9547 return true;
9548 }
9549 }
9550 }
9551 if (objects != null) {
9552 for (int i=0; i<objects.size(); i++) {
9553 if (System.identityHashCode(object) == objects.get(i)) {
9554 return true;
9555 }
9556 }
9557 }
9558 if (strings != null) {
9559 String flat = comp.flattenToString();
9560 for (int i=0; i<strings.size(); i++) {
9561 if (flat.contains(strings.get(i))) {
9562 return true;
9563 }
9564 }
9565 }
9566 return false;
9567 }
9568 }
9569
Dianne Hackborn625ac272010-09-17 18:29:22 -07009570 /**
9571 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009572 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009573 * - the cmd arg isn't the flattened component name of an existing activity:
9574 * dump all activity whose component contains the cmd as a substring
9575 * - A hex number of the ActivityRecord object instance.
9576 */
9577 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9578 int opti, boolean dumpAll) {
Craig Mautnercae015f2013-02-08 14:31:27 -08009579 ArrayList<ActivityRecord> activities;
9580
9581 synchronized (this) {
9582 activities = mMainStack.getDumpActivitiesLocked(name);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009583 }
9584
9585 if (activities.size() <= 0) {
9586 return false;
9587 }
9588
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009589 String[] newArgs = new String[args.length - opti];
9590 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9591
Dianne Hackborn30d71892010-12-11 10:37:55 -08009592 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009593 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009594 for (int i=activities.size()-1; i>=0; i--) {
9595 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009596 if (needSep) {
9597 pw.println();
9598 }
9599 needSep = true;
9600 synchronized (this) {
9601 if (lastTask != r.task) {
9602 lastTask = r.task;
9603 pw.print("TASK "); pw.print(lastTask.affinity);
9604 pw.print(" id="); pw.println(lastTask.taskId);
9605 if (dumpAll) {
9606 lastTask.dump(pw, " ");
9607 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009608 }
9609 }
9610 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009611 }
9612 return true;
9613 }
9614
9615 /**
9616 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9617 * there is a thread associated with the activity.
9618 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009619 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009620 final ActivityRecord r, String[] args, boolean dumpAll) {
9621 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009622 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9624 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9625 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009626 if (r.app != null) pw.println(r.app.pid);
9627 else pw.println("(not running)");
9628 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009629 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009630 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009631 }
9632 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009633 // flush anything that is already in the PrintWriter since the thread is going
9634 // to write to the file descriptor directly
9635 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009636 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009637 TransferPipe tp = new TransferPipe();
9638 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009639 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9640 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 tp.go(fd);
9642 } finally {
9643 tp.kill();
9644 }
9645 } catch (IOException e) {
9646 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009647 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009649 }
9650 }
9651 }
9652
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009653 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009655 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009656 boolean onlyHistory = false;
9657
9658 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009659 if (opti < args.length && "-s".equals(args[opti])) {
9660 dumpAll = false;
9661 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009662 onlyHistory = true;
9663 dumpPackage = null;
9664 }
9665
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009667 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 Iterator it = mRegisteredReceivers.values().iterator();
9671 while (it.hasNext()) {
9672 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009673 if (dumpPackage != null && (r.app == null ||
9674 !dumpPackage.equals(r.app.info.packageName))) {
9675 continue;
9676 }
9677 if (!printed) {
9678 pw.println(" Registered Receivers:");
9679 needSep = true;
9680 printed = true;
9681 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009682 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683 r.dump(pw, " ");
9684 }
9685 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686
9687 if (mReceiverResolver.dump(pw, needSep ?
9688 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9689 " ", dumpPackage, false)) {
9690 needSep = true;
9691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009692 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009693
9694 for (BroadcastQueue q : mBroadcastQueues) {
9695 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009698 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009699
Dianne Hackborn786b4402012-08-27 15:14:02 -07009700 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009701 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9702 if (needSep) {
9703 pw.println();
9704 }
9705 needSep = true;
9706 pw.print(" Sticky broadcasts for user ");
9707 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9708 StringBuilder sb = new StringBuilder(128);
9709 for (Map.Entry<String, ArrayList<Intent>> ent
9710 : mStickyBroadcasts.valueAt(user).entrySet()) {
9711 pw.print(" * Sticky action "); pw.print(ent.getKey());
9712 if (dumpAll) {
9713 pw.println(":");
9714 ArrayList<Intent> intents = ent.getValue();
9715 final int N = intents.size();
9716 for (int i=0; i<N; i++) {
9717 sb.setLength(0);
9718 sb.append(" Intent: ");
9719 intents.get(i).toShortString(sb, false, true, false, false);
9720 pw.println(sb.toString());
9721 Bundle bundle = intents.get(i).getExtras();
9722 if (bundle != null) {
9723 pw.print(" ");
9724 pw.println(bundle.toString());
9725 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009727 } else {
9728 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 }
9730 }
9731 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009732 }
9733
Dianne Hackborn786b4402012-08-27 15:14:02 -07009734 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009735 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009736 for (BroadcastQueue queue : mBroadcastQueues) {
9737 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9738 + queue.mBroadcastsScheduled);
9739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009740 pw.println(" mHandler:");
9741 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009742 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009744
9745 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 }
9747
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009749 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009750 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009751
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009752 ItemMatcher matcher = new ItemMatcher();
9753 matcher.build(args, opti);
9754
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009755 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009756
9757 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009758
9759 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009760 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009761 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009762 ContentProviderRecord r = mLaunchingProviders.get(i);
9763 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9764 continue;
9765 }
9766 if (!printed) {
9767 if (needSep) pw.println(" ");
9768 needSep = true;
9769 pw.println(" Launching content providers:");
9770 printed = true;
9771 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009772 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009773 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009775 }
9776
9777 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009778 if (needSep) pw.println();
9779 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009780 pw.println("Granted Uri Permissions:");
9781 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9782 int uid = mGrantedUriPermissions.keyAt(i);
9783 HashMap<Uri, UriPermission> perms
9784 = mGrantedUriPermissions.valueAt(i);
9785 pw.print(" * UID "); pw.print(uid);
9786 pw.println(" holds:");
9787 for (UriPermission perm : perms.values()) {
9788 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009789 if (dumpAll) {
9790 perm.dump(pw, " ");
9791 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009792 }
9793 }
9794 needSep = true;
9795 }
9796
9797 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009798 }
9799
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009800 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009801 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009802 boolean needSep = false;
9803
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009804 if (mIntentSenderRecords.size() > 0) {
9805 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 Iterator<WeakReference<PendingIntentRecord>> it
9807 = mIntentSenderRecords.values().iterator();
9808 while (it.hasNext()) {
9809 WeakReference<PendingIntentRecord> ref = it.next();
9810 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009811 if (dumpPackage != null && (rec == null
9812 || !dumpPackage.equals(rec.key.packageName))) {
9813 continue;
9814 }
9815 if (!printed) {
9816 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9817 printed = true;
9818 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009819 needSep = true;
9820 if (rec != null) {
9821 pw.print(" * "); pw.println(rec);
9822 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009824 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009825 } else {
9826 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009827 }
9828 }
9829 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009830
9831 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 }
9833
Craig Mautnercae015f2013-02-08 14:31:27 -08009834 static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009835 String prefix, String label, boolean complete, boolean brief, boolean client,
9836 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 boolean needNL = false;
9839 final String innerPrefix = prefix + " ";
9840 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009841 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009842 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009843 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9844 continue;
9845 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009846 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 if (needNL) {
9848 pw.println(" ");
9849 needNL = false;
9850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009851 if (lastTask != r.task) {
9852 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009853 pw.print(prefix);
9854 pw.print(full ? "* " : " ");
9855 pw.println(lastTask);
9856 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009857 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 } else if (complete) {
9859 // Complete + brief == give a summary. Isn't that obvious?!?
9860 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009861 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009862 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009865 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009866 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9867 pw.print(" #"); pw.print(i); pw.print(": ");
9868 pw.println(r);
9869 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009870 r.dump(pw, innerPrefix);
9871 } else if (complete) {
9872 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009873 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009874 if (r.app != null) {
9875 pw.print(innerPrefix); pw.println(r.app);
9876 }
9877 }
9878 if (client && r.app != null && r.app.thread != null) {
9879 // flush anything that is already in the PrintWriter since the thread is going
9880 // to write to the file descriptor directly
9881 pw.flush();
9882 try {
9883 TransferPipe tp = new TransferPipe();
9884 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009885 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9886 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 // Short timeout, since blocking here can
9888 // deadlock with the application.
9889 tp.go(fd, 2000);
9890 } finally {
9891 tp.kill();
9892 }
9893 } catch (IOException e) {
9894 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9895 } catch (RemoteException e) {
9896 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9897 }
9898 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009900 }
9901 }
9902
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009903 private static String buildOomTag(String prefix, String space, int val, int base) {
9904 if (val == base) {
9905 if (space == null) return prefix;
9906 return prefix + " ";
9907 }
9908 return prefix + "+" + Integer.toString(val-base);
9909 }
9910
9911 private static final int dumpProcessList(PrintWriter pw,
9912 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009913 String prefix, String normalLabel, String persistentLabel,
9914 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009916 final int N = list.size()-1;
9917 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009918 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009919 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9920 continue;
9921 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009922 pw.println(String.format("%s%s #%2d: %s",
9923 prefix, (r.persistent ? persistentLabel : normalLabel),
9924 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925 if (r.persistent) {
9926 numPers++;
9927 }
9928 }
9929 return numPers;
9930 }
9931
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009933 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009934 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009935 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009936
Dianne Hackborn905577f2011-09-07 18:31:28 -07009937 ArrayList<Pair<ProcessRecord, Integer>> list
9938 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9939 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009940 ProcessRecord r = origList.get(i);
9941 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9942 continue;
9943 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009944 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9945 }
9946
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009947 if (list.size() <= 0) {
9948 return false;
9949 }
9950
Dianne Hackborn905577f2011-09-07 18:31:28 -07009951 Comparator<Pair<ProcessRecord, Integer>> comparator
9952 = new Comparator<Pair<ProcessRecord, Integer>>() {
9953 @Override
9954 public int compare(Pair<ProcessRecord, Integer> object1,
9955 Pair<ProcessRecord, Integer> object2) {
9956 if (object1.first.setAdj != object2.first.setAdj) {
9957 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9958 }
9959 if (object1.second.intValue() != object2.second.intValue()) {
9960 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9961 }
9962 return 0;
9963 }
9964 };
9965
9966 Collections.sort(list, comparator);
9967
Dianne Hackborn287952c2010-09-22 22:34:31 -07009968 final long curRealtime = SystemClock.elapsedRealtime();
9969 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9970 final long curUptime = SystemClock.uptimeMillis();
9971 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9972
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009973 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009974 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009975 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009976 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009977 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009978 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9979 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009980 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9981 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009982 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9983 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009984 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9985 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009986 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009987 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009988 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9989 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9990 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9991 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9992 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9993 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9994 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9995 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009996 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9997 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009998 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9999 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010000 } else {
10001 oomAdj = Integer.toString(r.setAdj);
10002 }
10003 String schedGroup;
10004 switch (r.setSchedGroup) {
10005 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10006 schedGroup = "B";
10007 break;
10008 case Process.THREAD_GROUP_DEFAULT:
10009 schedGroup = "F";
10010 break;
10011 default:
10012 schedGroup = Integer.toString(r.setSchedGroup);
10013 break;
10014 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010015 String foreground;
10016 if (r.foregroundActivities) {
10017 foreground = "A";
10018 } else if (r.foregroundServices) {
10019 foreground = "S";
10020 } else {
10021 foreground = " ";
10022 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010023 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010024 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010025 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10026 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010027 if (r.adjSource != null || r.adjTarget != null) {
10028 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010029 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010030 if (r.adjTarget instanceof ComponentName) {
10031 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10032 } else if (r.adjTarget != null) {
10033 pw.print(r.adjTarget.toString());
10034 } else {
10035 pw.print("{null}");
10036 }
10037 pw.print("<=");
10038 if (r.adjSource instanceof ProcessRecord) {
10039 pw.print("Proc{");
10040 pw.print(((ProcessRecord)r.adjSource).toShortString());
10041 pw.println("}");
10042 } else if (r.adjSource != null) {
10043 pw.println(r.adjSource.toString());
10044 } else {
10045 pw.println("{null}");
10046 }
10047 }
10048 if (inclDetails) {
10049 pw.print(prefix);
10050 pw.print(" ");
10051 pw.print("oom: max="); pw.print(r.maxAdj);
10052 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010053 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010054 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010055 pw.print(" curRaw="); pw.print(r.curRawAdj);
10056 pw.print(" setRaw="); pw.print(r.setRawAdj);
10057 pw.print(" cur="); pw.print(r.curAdj);
10058 pw.print(" set="); pw.println(r.setAdj);
10059 pw.print(prefix);
10060 pw.print(" ");
10061 pw.print("keeping="); pw.print(r.keeping);
10062 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010063 pw.print(" empty="); pw.print(r.empty);
10064 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010065
10066 if (!r.keeping) {
10067 if (r.lastWakeTime != 0) {
10068 long wtime;
10069 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10070 synchronized (stats) {
10071 wtime = stats.getProcessWakeTime(r.info.uid,
10072 r.pid, curRealtime);
10073 }
10074 long timeUsed = wtime - r.lastWakeTime;
10075 pw.print(prefix);
10076 pw.print(" ");
10077 pw.print("keep awake over ");
10078 TimeUtils.formatDuration(realtimeSince, pw);
10079 pw.print(" used ");
10080 TimeUtils.formatDuration(timeUsed, pw);
10081 pw.print(" (");
10082 pw.print((timeUsed*100)/realtimeSince);
10083 pw.println("%)");
10084 }
10085 if (r.lastCpuTime != 0) {
10086 long timeUsed = r.curCpuTime - r.lastCpuTime;
10087 pw.print(prefix);
10088 pw.print(" ");
10089 pw.print("run cpu over ");
10090 TimeUtils.formatDuration(uptimeSince, pw);
10091 pw.print(" used ");
10092 TimeUtils.formatDuration(timeUsed, pw);
10093 pw.print(" (");
10094 pw.print((timeUsed*100)/uptimeSince);
10095 pw.println("%)");
10096 }
10097 }
10098 }
10099 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010100 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010101 }
10102
Dianne Hackbornb437e092011-08-05 17:50:29 -070010103 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010104 ArrayList<ProcessRecord> procs;
10105 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010106 if (args != null && args.length > start
10107 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010108 procs = new ArrayList<ProcessRecord>();
10109 int pid = -1;
10110 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010111 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010112 } catch (NumberFormatException e) {
10113
10114 }
10115 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10116 ProcessRecord proc = mLruProcesses.get(i);
10117 if (proc.pid == pid) {
10118 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010120 procs.add(proc);
10121 }
10122 }
10123 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010124 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010125 return null;
10126 }
10127 } else {
10128 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10129 }
10130 }
10131 return procs;
10132 }
10133
10134 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10135 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010137 if (procs == null) {
10138 return;
10139 }
10140
10141 long uptime = SystemClock.uptimeMillis();
10142 long realtime = SystemClock.elapsedRealtime();
10143 pw.println("Applications Graphics Acceleration Info:");
10144 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10145
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010146 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10147 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010148 if (r.thread != null) {
10149 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10150 pw.flush();
10151 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010152 TransferPipe tp = new TransferPipe();
10153 try {
10154 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10155 tp.go(fd);
10156 } finally {
10157 tp.kill();
10158 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010159 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010160 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010161 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010162 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010164 pw.flush();
10165 }
10166 }
10167 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010168 }
10169
Jeff Brown6754ba22011-12-14 20:20:01 -080010170 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10171 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10172 if (procs == null) {
10173 return;
10174 }
10175
10176 pw.println("Applications Database Info:");
10177
10178 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10179 ProcessRecord r = procs.get(i);
10180 if (r.thread != null) {
10181 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10182 pw.flush();
10183 try {
10184 TransferPipe tp = new TransferPipe();
10185 try {
10186 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10187 tp.go(fd);
10188 } finally {
10189 tp.kill();
10190 }
10191 } catch (IOException e) {
10192 pw.println("Failure while dumping the app: " + r);
10193 pw.flush();
10194 } catch (RemoteException e) {
10195 pw.println("Got a RemoteException while dumping the app " + r);
10196 pw.flush();
10197 }
10198 }
10199 }
10200 }
10201
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010202 final static class MemItem {
10203 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010204 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010207 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010208
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010209 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010211 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010212 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010213 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010214 }
10215 }
10216
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 boolean sort) {
10219 if (sort) {
10220 Collections.sort(items, new Comparator<MemItem>() {
10221 @Override
10222 public int compare(MemItem lhs, MemItem rhs) {
10223 if (lhs.pss < rhs.pss) {
10224 return 1;
10225 } else if (lhs.pss > rhs.pss) {
10226 return -1;
10227 }
10228 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010229 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010230 });
10231 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232
10233 for (int i=0; i<items.size(); i++) {
10234 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010235 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010236 if (mi.subitems != null) {
10237 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10238 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239 }
10240 }
10241
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010242 // These are in KB.
10243 static final long[] DUMP_MEM_BUCKETS = new long[] {
10244 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10245 120*1024, 160*1024, 200*1024,
10246 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10247 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10248 };
10249
Dianne Hackborn672342c2011-11-29 11:29:02 -080010250 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10251 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010252 int start = label.lastIndexOf('.');
10253 if (start >= 0) start++;
10254 else start = 0;
10255 int end = label.length();
10256 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10257 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10258 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10259 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010260 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010261 out.append(label, start, end);
10262 return;
10263 }
10264 }
10265 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010266 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010267 out.append(label, start, end);
10268 }
10269
10270 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10271 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10272 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10273 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10274 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10275 };
10276 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10277 "System", "Persistent", "Foreground",
10278 "Visible", "Perceptible", "Heavy Weight",
10279 "Backup", "A Services", "Home", "Previous",
10280 "B Services", "Background"
10281 };
10282
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010283 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010284 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010285 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010286 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010287 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010288
10289 int opti = 0;
10290 while (opti < args.length) {
10291 String opt = args[opti];
10292 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10293 break;
10294 }
10295 opti++;
10296 if ("-a".equals(opt)) {
10297 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010298 } else if ("--oom".equals(opt)) {
10299 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010300 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010301 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010302 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010303 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010304 pw.println("If [process] is specified it can be the name or ");
10305 pw.println("pid of a specific process to dump.");
10306 return;
10307 } else {
10308 pw.println("Unknown argument: " + opt + "; use -h for help");
10309 }
10310 }
10311
10312 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010313 if (procs == null) {
10314 return;
10315 }
10316
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010317 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 long uptime = SystemClock.uptimeMillis();
10319 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320
10321 if (procs.size() == 1 || isCheckinRequest) {
10322 dumpAll = true;
10323 }
10324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010325 if (isCheckinRequest) {
10326 // short checkin version
10327 pw.println(uptime + "," + realtime);
10328 pw.flush();
10329 } else {
10330 pw.println("Applications Memory Usage (kB):");
10331 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10332 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010333
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 String[] innerArgs = new String[args.length-opti];
10335 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10336
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010337 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10338 long nativePss=0, dalvikPss=0, otherPss=0;
10339 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10340
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010341 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10342 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10343 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010344
10345 long totalPss = 0;
10346
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010347 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10348 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010351 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10352 pw.flush();
10353 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010354 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010355 if (dumpAll) {
10356 try {
10357 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10358 } catch (RemoteException e) {
10359 if (!isCheckinRequest) {
10360 pw.println("Got RemoteException!");
10361 pw.flush();
10362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010364 } else {
10365 mi = new Debug.MemoryInfo();
10366 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010367 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010368
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010369 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010370 long myTotalPss = mi.getTotalPss();
10371 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010372 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010373 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010374 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010375
10376 nativePss += mi.nativePss;
10377 dalvikPss += mi.dalvikPss;
10378 otherPss += mi.otherPss;
10379 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10380 long mem = mi.getOtherPss(j);
10381 miscPss[j] += mem;
10382 otherPss -= mem;
10383 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010384
10385 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010386 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10387 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010388 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010389 if (oomProcs[oomIndex] == null) {
10390 oomProcs[oomIndex] = new ArrayList<MemItem>();
10391 }
10392 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010393 break;
10394 }
10395 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 }
10398 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010399
10400 if (!isCheckinRequest && procs.size() > 1) {
10401 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10402
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010403 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10404 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10405 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010406 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010407 String label = Debug.MemoryInfo.getOtherLabel(j);
10408 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010409 }
10410
Dianne Hackbornb437e092011-08-05 17:50:29 -070010411 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10412 for (int j=0; j<oomPss.length; j++) {
10413 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010414 String label = DUMP_MEM_OOM_LABEL[j];
10415 MemItem item = new MemItem(label, label, oomPss[j],
10416 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010417 item.subitems = oomProcs[j];
10418 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010419 }
10420 }
10421
Dianne Hackborn672342c2011-11-29 11:29:02 -080010422 if (outTag != null || outStack != null) {
10423 if (outTag != null) {
10424 appendMemBucket(outTag, totalPss, "total", false);
10425 }
10426 if (outStack != null) {
10427 appendMemBucket(outStack, totalPss, "total", true);
10428 }
10429 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010430 for (int i=0; i<oomMems.size(); i++) {
10431 MemItem miCat = oomMems.get(i);
10432 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10433 continue;
10434 }
10435 if (miCat.id < ProcessList.SERVICE_ADJ
10436 || miCat.id == ProcessList.HOME_APP_ADJ
10437 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010438 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10439 outTag.append(" / ");
10440 }
10441 if (outStack != null) {
10442 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10443 if (firstLine) {
10444 outStack.append(":");
10445 firstLine = false;
10446 }
10447 outStack.append("\n\t at ");
10448 } else {
10449 outStack.append("$");
10450 }
10451 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010452 for (int j=0; j<miCat.subitems.size(); j++) {
10453 MemItem mi = miCat.subitems.get(j);
10454 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010455 if (outTag != null) {
10456 outTag.append(" ");
10457 }
10458 if (outStack != null) {
10459 outStack.append("$");
10460 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010461 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010462 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10463 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10464 }
10465 if (outStack != null) {
10466 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10467 }
10468 }
10469 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10470 outStack.append("(");
10471 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10472 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10473 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10474 outStack.append(":");
10475 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10476 }
10477 }
10478 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010479 }
10480 }
10481 }
10482 }
10483
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010484 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010485 pw.println();
10486 pw.println("Total PSS by process:");
10487 dumpMemItems(pw, " ", procMems, true);
10488 pw.println();
10489 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010490 pw.println("Total PSS by OOM adjustment:");
10491 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010492 if (!oomOnly) {
10493 PrintWriter out = categoryPw != null ? categoryPw : pw;
10494 out.println();
10495 out.println("Total PSS by category:");
10496 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010497 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010498 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010499 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010500 final int[] SINGLE_LONG_FORMAT = new int[] {
10501 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10502 };
10503 long[] longOut = new long[1];
10504 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10505 SINGLE_LONG_FORMAT, null, longOut, null);
10506 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10507 longOut[0] = 0;
10508 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10509 SINGLE_LONG_FORMAT, null, longOut, null);
10510 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10511 longOut[0] = 0;
10512 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10513 SINGLE_LONG_FORMAT, null, longOut, null);
10514 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10515 longOut[0] = 0;
10516 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10517 SINGLE_LONG_FORMAT, null, longOut, null);
10518 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10519 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10520 pw.print(shared); pw.println(" kB");
10521 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10522 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010524 }
10525
10526 /**
10527 * Searches array of arguments for the specified string
10528 * @param args array of argument strings
10529 * @param value value to search for
10530 * @return true if the value is contained in the array
10531 */
10532 private static boolean scanArgs(String[] args, String value) {
10533 if (args != null) {
10534 for (String arg : args) {
10535 if (value.equals(arg)) {
10536 return true;
10537 }
10538 }
10539 }
10540 return false;
10541 }
10542
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010543 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10544 ContentProviderRecord cpr, boolean always) {
10545 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10546
10547 if (!inLaunching || always) {
10548 synchronized (cpr) {
10549 cpr.launchingApp = null;
10550 cpr.notifyAll();
10551 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010552 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010553 String names[] = cpr.info.authority.split(";");
10554 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010555 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010556 }
10557 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010558
10559 for (int i=0; i<cpr.connections.size(); i++) {
10560 ContentProviderConnection conn = cpr.connections.get(i);
10561 if (conn.waiting) {
10562 // If this connection is waiting for the provider, then we don't
10563 // need to mess with its process unless we are always removing
10564 // or for some reason the provider is not currently launching.
10565 if (inLaunching && !always) {
10566 continue;
10567 }
10568 }
10569 ProcessRecord capp = conn.client;
10570 conn.dead = true;
10571 if (conn.stableCount > 0) {
10572 if (!capp.persistent && capp.thread != null
10573 && capp.pid != 0
10574 && capp.pid != MY_PID) {
10575 Slog.i(TAG, "Kill " + capp.processName
10576 + " (pid " + capp.pid + "): provider " + cpr.info.name
10577 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010578 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010579 capp.processName, capp.setAdj, "dying provider "
10580 + cpr.name.toShortString());
10581 Process.killProcessQuiet(capp.pid);
10582 }
10583 } else if (capp.thread != null && conn.provider.provider != null) {
10584 try {
10585 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10586 } catch (RemoteException e) {
10587 }
10588 // In the protocol here, we don't expect the client to correctly
10589 // clean up this connection, we'll just remove it.
10590 cpr.connections.remove(i);
10591 conn.client.conProviders.remove(conn);
10592 }
10593 }
10594
10595 if (inLaunching && always) {
10596 mLaunchingProviders.remove(cpr);
10597 }
10598 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 }
10600
10601 /**
10602 * Main code for cleaning up a process when it has gone away. This is
10603 * called both as a result of the process dying, or directly when stopping
10604 * a process when running in single process mode.
10605 */
10606 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010607 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010609 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010610 }
10611
Dianne Hackborn36124872009-10-08 16:22:03 -070010612 mProcessesToGc.remove(app);
10613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 // Dismiss any open dialogs.
10615 if (app.crashDialog != null) {
10616 app.crashDialog.dismiss();
10617 app.crashDialog = null;
10618 }
10619 if (app.anrDialog != null) {
10620 app.anrDialog.dismiss();
10621 app.anrDialog = null;
10622 }
10623 if (app.waitDialog != null) {
10624 app.waitDialog.dismiss();
10625 app.waitDialog = null;
10626 }
10627
10628 app.crashing = false;
10629 app.notResponding = false;
10630
10631 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010632 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 app.thread = null;
10634 app.forcingToForeground = null;
10635 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010636 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010637 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010638 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010640 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641
10642 boolean restart = false;
10643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010644 // Remove published content providers.
10645 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010646 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010647 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010648 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010649
10650 final boolean always = app.bad || !allowRestart;
10651 if (removeDyingProviderLocked(app, cpr, always) || always) {
10652 // We left the provider in the launching list, need to
10653 // restart it.
10654 restart = true;
10655 }
10656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010658 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010659 }
10660 app.pubProviders.clear();
10661 }
10662
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010663 // Take care of any launching providers waiting for this process.
10664 if (checkAppInLaunchingProvidersLocked(app, false)) {
10665 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 // Unregister from connected content providers.
10669 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010670 for (int i=0; i<app.conProviders.size(); i++) {
10671 ContentProviderConnection conn = app.conProviders.get(i);
10672 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 }
10674 app.conProviders.clear();
10675 }
10676
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010677 // At this point there may be remaining entries in mLaunchingProviders
10678 // where we were the only one waiting, so they are no longer of use.
10679 // Look for these and clean up if found.
10680 // XXX Commented out for now. Trying to figure out a way to reproduce
10681 // the actual situation to identify what is actually going on.
10682 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010683 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010684 ContentProviderRecord cpr = (ContentProviderRecord)
10685 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010686 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010687 synchronized (cpr) {
10688 cpr.launchingApp = null;
10689 cpr.notifyAll();
10690 }
10691 }
10692 }
10693 }
10694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695 skipCurrentReceiverLocked(app);
10696
10697 // Unregister any receivers.
10698 if (app.receivers.size() > 0) {
10699 Iterator<ReceiverList> it = app.receivers.iterator();
10700 while (it.hasNext()) {
10701 removeReceiverLocked(it.next());
10702 }
10703 app.receivers.clear();
10704 }
10705
Christopher Tate181fafa2009-05-14 11:12:14 -070010706 // If the app is undergoing backup, tell the backup manager about it
10707 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010708 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10709 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010710 try {
10711 IBackupManager bm = IBackupManager.Stub.asInterface(
10712 ServiceManager.getService(Context.BACKUP_SERVICE));
10713 bm.agentDisconnected(app.info.packageName);
10714 } catch (RemoteException e) {
10715 // can't happen; backup manager is local
10716 }
10717 }
10718
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010719 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10720 ProcessChangeItem item = mPendingProcessChanges.get(i);
10721 if (item.pid == app.pid) {
10722 mPendingProcessChanges.remove(i);
10723 mAvailProcessChanges.add(item);
10724 }
10725 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010726 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010728 // If the caller is restarting this app, then leave it in its
10729 // current lists and let the caller take care of it.
10730 if (restarting) {
10731 return;
10732 }
10733
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010734 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010735 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010737 mProcessNames.remove(app.processName, app.uid);
10738 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010739 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010740 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10741 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010742 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010744 } else if (!app.removed) {
10745 // This app is persistent, so we need to keep its record around.
10746 // If it is not already on the pending app list, add it there
10747 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10749 mPersistentStartingProcesses.add(app);
10750 restart = true;
10751 }
10752 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010753 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010754 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 mProcessesOnHold.remove(app);
10756
The Android Open Source Project4df24232009-03-05 14:34:35 -080010757 if (app == mHomeProcess) {
10758 mHomeProcess = null;
10759 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010760 if (app == mPreviousProcess) {
10761 mPreviousProcess = null;
10762 }
10763
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010764 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 // We have components that still need to be running in the
10766 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010767 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 startProcessLocked(app, "restart", app.processName);
10769 } else if (app.pid > 0 && app.pid != MY_PID) {
10770 // Goodbye!
10771 synchronized (mPidsSelfLocked) {
10772 mPidsSelfLocked.remove(app.pid);
10773 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10774 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010775 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 }
10777 }
10778
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010779 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10780 // Look through the content providers we are waiting to have launched,
10781 // and if any run in this process then either schedule a restart of
10782 // the process or kill the client waiting for it if this process has
10783 // gone bad.
10784 int NL = mLaunchingProviders.size();
10785 boolean restart = false;
10786 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010787 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010788 if (cpr.launchingApp == app) {
10789 if (!alwaysBad && !app.bad) {
10790 restart = true;
10791 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010792 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010793 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010794 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010795 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010796 }
10797 }
10798 }
10799 return restart;
10800 }
10801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 // =========================================================
10803 // SERVICES
10804 // =========================================================
10805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10807 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010808 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010810 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 }
10812 }
10813
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010814 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010815 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010816 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010817 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010818 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010819 }
10820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010822 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010823 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 // Refuse possible leaked file descriptors
10825 if (service != null && service.hasFileDescriptors() == true) {
10826 throw new IllegalArgumentException("File descriptors passed in Intent");
10827 }
10828
Amith Yamasani742a6712011-05-04 14:49:28 -070010829 if (DEBUG_SERVICE)
10830 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 synchronized(this) {
10832 final int callingPid = Binder.getCallingPid();
10833 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010834 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010836 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010837 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 Binder.restoreCallingIdentity(origId);
10839 return res;
10840 }
10841 }
10842
10843 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010844 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010846 if (DEBUG_SERVICE)
10847 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010849 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010850 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 Binder.restoreCallingIdentity(origId);
10852 return res;
10853 }
10854 }
10855
10856 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010857 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010858 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 // Refuse possible leaked file descriptors
10860 if (service != null && service.hasFileDescriptors() == true) {
10861 throw new IllegalArgumentException("File descriptors passed in Intent");
10862 }
10863
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010864 checkValidCaller(Binder.getCallingUid(), userId);
10865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010867 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 }
10870
10871 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010872 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 // Refuse possible leaked file descriptors
10874 if (service != null && service.hasFileDescriptors() == true) {
10875 throw new IllegalArgumentException("File descriptors passed in Intent");
10876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010877 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010878 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 }
10881
10882 public boolean stopServiceToken(ComponentName className, IBinder token,
10883 int startId) {
10884 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010885 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
10888
10889 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010890 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010892 mServices.setServiceForegroundLocked(className, token, id, notification,
10893 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 }
10895 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010896
Dianne Hackborn41203752012-08-31 14:05:51 -070010897 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10898 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010899 final int callingUserId = UserHandle.getUserId(callingUid);
10900 if (callingUserId != userId) {
10901 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10902 if ((requireFull || checkComponentPermission(
10903 android.Manifest.permission.INTERACT_ACROSS_USERS,
10904 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10905 && checkComponentPermission(
10906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10907 callingPid, callingUid, -1, true)
10908 != PackageManager.PERMISSION_GRANTED) {
10909 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10910 // In this case, they would like to just execute as their
10911 // owner user instead of failing.
10912 userId = callingUserId;
10913 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010914 StringBuilder builder = new StringBuilder(128);
10915 builder.append("Permission Denial: ");
10916 builder.append(name);
10917 if (callerPackage != null) {
10918 builder.append(" from ");
10919 builder.append(callerPackage);
10920 }
10921 builder.append(" asks to run as user ");
10922 builder.append(userId);
10923 builder.append(" but is calling from user ");
10924 builder.append(UserHandle.getUserId(callingUid));
10925 builder.append("; this requires ");
10926 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10927 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010928 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010929 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10930 }
10931 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010932 Slog.w(TAG, msg);
10933 throw new SecurityException(msg);
10934 }
10935 }
10936 }
10937 if (userId == UserHandle.USER_CURRENT
10938 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010939 // Note that we may be accessing this outside of a lock...
10940 // shouldn't be a big deal, if this is being called outside
10941 // of a locked context there is intrinsically a race with
10942 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010943 userId = mCurrentUserId;
10944 }
10945 if (!allowAll && userId < 0) {
10946 throw new IllegalArgumentException(
10947 "Call does not support special user #" + userId);
10948 }
10949 }
10950 return userId;
10951 }
10952
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010953 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10954 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010955 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010956 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010957 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10958 if (ActivityManager.checkUidPermission(
10959 android.Manifest.permission.INTERACT_ACROSS_USERS,
10960 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10961 ComponentName comp = new ComponentName(aInfo.packageName, className);
10962 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10963 + " requests FLAG_SINGLE_USER, but app does not hold "
10964 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10965 Slog.w(TAG, msg);
10966 throw new SecurityException(msg);
10967 }
10968 result = true;
10969 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010970 } else if (componentProcessName == aInfo.packageName) {
10971 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10972 } else if ("system".equals(componentProcessName)) {
10973 result = true;
10974 }
10975 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010976 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10977 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010978 }
10979 return result;
10980 }
10981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 public int bindService(IApplicationThread caller, IBinder token,
10983 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010984 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010985 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 // Refuse possible leaked file descriptors
10987 if (service != null && service.hasFileDescriptors() == true) {
10988 throw new IllegalArgumentException("File descriptors passed in Intent");
10989 }
10990
10991 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010992 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10993 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994 }
10995 }
10996
10997 public boolean unbindService(IServiceConnection connection) {
10998 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010999 return mServices.unbindServiceLocked(connection);
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 void publishService(IBinder token, Intent intent, IBinder service) {
11004 // Refuse possible leaked file descriptors
11005 if (intent != null && intent.hasFileDescriptors() == true) {
11006 throw new IllegalArgumentException("File descriptors passed in Intent");
11007 }
11008
11009 synchronized(this) {
11010 if (!(token instanceof ServiceRecord)) {
11011 throw new IllegalArgumentException("Invalid service token");
11012 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011013 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 }
11015 }
11016
11017 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11018 // Refuse possible leaked file descriptors
11019 if (intent != null && intent.hasFileDescriptors() == true) {
11020 throw new IllegalArgumentException("File descriptors passed in Intent");
11021 }
11022
11023 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011024 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 }
11027
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011028 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 synchronized(this) {
11030 if (!(token instanceof ServiceRecord)) {
11031 throw new IllegalArgumentException("Invalid service token");
11032 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011033 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 }
11036
11037 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011038 // BACKUP AND RESTORE
11039 // =========================================================
11040
11041 // Cause the target app to be launched if necessary and its backup agent
11042 // instantiated. The backup agent will invoke backupAgentCreated() on the
11043 // activity manager to announce its creation.
11044 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011045 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11046 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011047
11048 synchronized(this) {
11049 // !!! TODO: currently no check here that we're already bound
11050 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11051 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11052 synchronized (stats) {
11053 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11054 }
11055
Dianne Hackborne7f97212011-02-24 14:40:20 -080011056 // Backup agent is now in use, its package can't be stopped.
11057 try {
11058 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011059 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011060 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011061 } catch (IllegalArgumentException e) {
11062 Slog.w(TAG, "Failed trying to unstop package "
11063 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011064 }
11065
Christopher Tate181fafa2009-05-14 11:12:14 -070011066 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011067 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11068 ? new ComponentName(app.packageName, app.backupAgentName)
11069 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011070 // startProcessLocked() returns existing proc's record if it's already running
11071 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011072 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011073 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011074 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011075 return false;
11076 }
11077
11078 r.app = proc;
11079 mBackupTarget = r;
11080 mBackupAppName = app.packageName;
11081
Christopher Tate6fa95972009-06-05 18:43:55 -070011082 // Try not to kill the process during backup
11083 updateOomAdjLocked(proc);
11084
Christopher Tate181fafa2009-05-14 11:12:14 -070011085 // If the process is already attached, schedule the creation of the backup agent now.
11086 // If it is not yet live, this will be done when it attaches to the framework.
11087 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011088 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011089 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011090 proc.thread.scheduleCreateBackupAgent(app,
11091 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011093 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011094 }
11095 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011096 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011097 }
11098 // Invariants: at this point, the target app process exists and the application
11099 // is either already running or in the process of coming up. mBackupTarget and
11100 // mBackupAppName describe the app, so that when it binds back to the AM we
11101 // know that it's scheduled for a backup-agent operation.
11102 }
11103
11104 return true;
11105 }
11106
Christopher Tate346acb12012-10-15 19:20:25 -070011107 @Override
11108 public void clearPendingBackup() {
11109 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11110 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11111
11112 synchronized (this) {
11113 mBackupTarget = null;
11114 mBackupAppName = null;
11115 }
11116 }
11117
Christopher Tate181fafa2009-05-14 11:12:14 -070011118 // A backup agent has just come up
11119 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011121 + " = " + agent);
11122
11123 synchronized(this) {
11124 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011125 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011126 return;
11127 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011128 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011129
Dianne Hackborn06740692010-09-22 22:46:21 -070011130 long oldIdent = Binder.clearCallingIdentity();
11131 try {
11132 IBackupManager bm = IBackupManager.Stub.asInterface(
11133 ServiceManager.getService(Context.BACKUP_SERVICE));
11134 bm.agentConnected(agentPackageName, agent);
11135 } catch (RemoteException e) {
11136 // can't happen; the backup manager service is local
11137 } catch (Exception e) {
11138 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11139 e.printStackTrace();
11140 } finally {
11141 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011142 }
11143 }
11144
11145 // done with this agent
11146 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011147 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011148 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011150 return;
11151 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011152
11153 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011154 try {
11155 if (mBackupAppName == null) {
11156 Slog.w(TAG, "Unbinding backup agent with no active backup");
11157 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011158 }
Christopher Tate346acb12012-10-15 19:20:25 -070011159
11160 if (!mBackupAppName.equals(appInfo.packageName)) {
11161 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11162 return;
11163 }
11164
11165 // Not backing this app up any more; reset its OOM adjustment
11166 final ProcessRecord proc = mBackupTarget.app;
11167 updateOomAdjLocked(proc);
11168
11169 // If the app crashed during backup, 'thread' will be null here
11170 if (proc.thread != null) {
11171 try {
11172 proc.thread.scheduleDestroyBackupAgent(appInfo,
11173 compatibilityInfoForPackageLocked(appInfo));
11174 } catch (Exception e) {
11175 Slog.e(TAG, "Exception when unbinding backup agent:");
11176 e.printStackTrace();
11177 }
11178 }
11179 } finally {
11180 mBackupTarget = null;
11181 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011182 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011183 }
11184 }
11185 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 // BROADCASTS
11187 // =========================================================
11188
Josh Bartel7f208742010-02-25 11:01:44 -060011189 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011190 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011192 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11193 if (stickies == null) {
11194 return cur;
11195 }
11196 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 if (list == null) {
11198 return cur;
11199 }
11200 int N = list.size();
11201 for (int i=0; i<N; i++) {
11202 Intent intent = list.get(i);
11203 if (filter.match(resolver, intent, true, TAG) >= 0) {
11204 if (cur == null) {
11205 cur = new ArrayList<Intent>();
11206 }
11207 cur.add(intent);
11208 }
11209 }
11210 return cur;
11211 }
11212
Christopher Tatef46723b2012-01-26 14:19:24 -080011213 boolean isPendingBroadcastProcessLocked(int pid) {
11214 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11215 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217
Christopher Tatef46723b2012-01-26 14:19:24 -080011218 void skipPendingBroadcastLocked(int pid) {
11219 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11220 for (BroadcastQueue queue : mBroadcastQueues) {
11221 queue.skipPendingBroadcastLocked(pid);
11222 }
11223 }
11224
11225 // The app just attached; send any pending broadcasts that it should receive
11226 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11227 boolean didSomething = false;
11228 for (BroadcastQueue queue : mBroadcastQueues) {
11229 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011231 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 }
11233
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011234 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011235 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011236 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011237 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011238 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 synchronized(this) {
11240 ProcessRecord callerApp = null;
11241 if (caller != null) {
11242 callerApp = getRecordForAppLocked(caller);
11243 if (callerApp == null) {
11244 throw new SecurityException(
11245 "Unable to find app for caller " + caller
11246 + " (pid=" + Binder.getCallingPid()
11247 + ") when registering receiver " + receiver);
11248 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011249 if (callerApp.info.uid != Process.SYSTEM_UID &&
11250 !callerApp.pkgList.contains(callerPackage)) {
11251 throw new SecurityException("Given caller package " + callerPackage
11252 + " is not running in process " + callerApp);
11253 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011254 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011255 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011256 } else {
11257 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011258 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011259 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 }
11261
Dianne Hackborn139748f2012-09-24 11:36:57 -070011262 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011263 true, true, "registerReceiver", callerPackage);
11264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 List allSticky = null;
11266
11267 // Look for any matching sticky broadcasts...
11268 Iterator actions = filter.actionsIterator();
11269 if (actions != null) {
11270 while (actions.hasNext()) {
11271 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011272 allSticky = getStickiesLocked(action, filter, allSticky,
11273 UserHandle.USER_ALL);
11274 allSticky = getStickiesLocked(action, filter, allSticky,
11275 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 }
11277 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011278 allSticky = getStickiesLocked(null, filter, allSticky,
11279 UserHandle.USER_ALL);
11280 allSticky = getStickiesLocked(null, filter, allSticky,
11281 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 }
11283
11284 // The first sticky in the list is returned directly back to
11285 // the client.
11286 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11287
Joe Onorato8a9b2202010-02-26 18:56:32 -080011288 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011289 + ": " + sticky);
11290
11291 if (receiver == null) {
11292 return sticky;
11293 }
11294
11295 ReceiverList rl
11296 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11297 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011298 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11299 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011300 if (rl.app != null) {
11301 rl.app.receivers.add(rl);
11302 } else {
11303 try {
11304 receiver.asBinder().linkToDeath(rl, 0);
11305 } catch (RemoteException e) {
11306 return sticky;
11307 }
11308 rl.linkedToDeath = true;
11309 }
11310 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011311 } else if (rl.uid != callingUid) {
11312 throw new IllegalArgumentException(
11313 "Receiver requested to register for uid " + callingUid
11314 + " was previously registered for uid " + rl.uid);
11315 } else if (rl.pid != callingPid) {
11316 throw new IllegalArgumentException(
11317 "Receiver requested to register for pid " + callingPid
11318 + " was previously registered for pid " + rl.pid);
11319 } else if (rl.userId != userId) {
11320 throw new IllegalArgumentException(
11321 "Receiver requested to register for user " + userId
11322 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011324 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011325 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011326 rl.add(bf);
11327 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011328 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 }
11330 mReceiverResolver.addFilter(bf);
11331
11332 // Enqueue broadcasts for all existing stickies that match
11333 // this filter.
11334 if (allSticky != null) {
11335 ArrayList receivers = new ArrayList();
11336 receivers.add(bf);
11337
11338 int N = allSticky.size();
11339 for (int i=0; i<N; i++) {
11340 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011341 BroadcastQueue queue = broadcastQueueForIntent(intent);
11342 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011343 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11344 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011345 queue.enqueueParallelBroadcastLocked(r);
11346 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347 }
11348 }
11349
11350 return sticky;
11351 }
11352 }
11353
11354 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011355 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356
Christopher Tatef46723b2012-01-26 14:19:24 -080011357 final long origId = Binder.clearCallingIdentity();
11358 try {
11359 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360
Christopher Tatef46723b2012-01-26 14:19:24 -080011361 synchronized(this) {
11362 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011363 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011364 if (rl != null) {
11365 if (rl.curBroadcast != null) {
11366 BroadcastRecord r = rl.curBroadcast;
11367 final boolean doNext = finishReceiverLocked(
11368 receiver.asBinder(), r.resultCode, r.resultData,
11369 r.resultExtras, r.resultAbort, true);
11370 if (doNext) {
11371 doTrim = true;
11372 r.queue.processNextBroadcast(false);
11373 }
11374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375
Christopher Tatef46723b2012-01-26 14:19:24 -080011376 if (rl.app != null) {
11377 rl.app.receivers.remove(rl);
11378 }
11379 removeReceiverLocked(rl);
11380 if (rl.linkedToDeath) {
11381 rl.linkedToDeath = false;
11382 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011384 }
11385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386
Christopher Tatef46723b2012-01-26 14:19:24 -080011387 // If we actually concluded any broadcasts, we might now be able
11388 // to trim the recipients' apps from our working set
11389 if (doTrim) {
11390 trimApplications();
11391 return;
11392 }
11393
11394 } finally {
11395 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011397 }
11398
11399 void removeReceiverLocked(ReceiverList rl) {
11400 mRegisteredReceivers.remove(rl.receiver.asBinder());
11401 int N = rl.size();
11402 for (int i=0; i<N; i++) {
11403 mReceiverResolver.removeFilter(rl.get(i));
11404 }
11405 }
11406
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011407 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011408 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11409 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011410 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011411 try {
11412 r.thread.dispatchPackageBroadcast(cmd, packages);
11413 } catch (RemoteException ex) {
11414 }
11415 }
11416 }
11417 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011418
11419 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11420 int[] users) {
11421 List<ResolveInfo> receivers = null;
11422 try {
11423 HashSet<ComponentName> singleUserReceivers = null;
11424 boolean scannedFirstReceivers = false;
11425 for (int user : users) {
11426 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11427 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011428 if (user != 0 && newReceivers != null) {
11429 // If this is not the primary user, we need to check for
11430 // any receivers that should be filtered out.
11431 for (int i=0; i<newReceivers.size(); i++) {
11432 ResolveInfo ri = newReceivers.get(i);
11433 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11434 newReceivers.remove(i);
11435 i--;
11436 }
11437 }
11438 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011439 if (newReceivers != null && newReceivers.size() == 0) {
11440 newReceivers = null;
11441 }
11442 if (receivers == null) {
11443 receivers = newReceivers;
11444 } else if (newReceivers != null) {
11445 // We need to concatenate the additional receivers
11446 // found with what we have do far. This would be easy,
11447 // but we also need to de-dup any receivers that are
11448 // singleUser.
11449 if (!scannedFirstReceivers) {
11450 // Collect any single user receivers we had already retrieved.
11451 scannedFirstReceivers = true;
11452 for (int i=0; i<receivers.size(); i++) {
11453 ResolveInfo ri = receivers.get(i);
11454 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11455 ComponentName cn = new ComponentName(
11456 ri.activityInfo.packageName, ri.activityInfo.name);
11457 if (singleUserReceivers == null) {
11458 singleUserReceivers = new HashSet<ComponentName>();
11459 }
11460 singleUserReceivers.add(cn);
11461 }
11462 }
11463 }
11464 // Add the new results to the existing results, tracking
11465 // and de-dupping single user receivers.
11466 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011467 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011468 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11469 ComponentName cn = new ComponentName(
11470 ri.activityInfo.packageName, ri.activityInfo.name);
11471 if (singleUserReceivers == null) {
11472 singleUserReceivers = new HashSet<ComponentName>();
11473 }
11474 if (!singleUserReceivers.contains(cn)) {
11475 singleUserReceivers.add(cn);
11476 receivers.add(ri);
11477 }
11478 } else {
11479 receivers.add(ri);
11480 }
11481 }
11482 }
11483 }
11484 } catch (RemoteException ex) {
11485 // pm is in same process, this will never happen.
11486 }
11487 return receivers;
11488 }
11489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 private final int broadcastIntentLocked(ProcessRecord callerApp,
11491 String callerPackage, Intent intent, String resolvedType,
11492 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011493 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011494 boolean ordered, boolean sticky, int callingPid, int callingUid,
11495 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 intent = new Intent(intent);
11497
Dianne Hackborne7f97212011-02-24 14:40:20 -080011498 // By default broadcasts do not go to stopped apps.
11499 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11500
Joe Onorato8a9b2202010-02-26 18:56:32 -080011501 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011503 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011505 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011507
Dianne Hackborn139748f2012-09-24 11:36:57 -070011508 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011509 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011510
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011511 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011512 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011513 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011514 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11515 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11516 Slog.w(TAG, "Skipping broadcast of " + intent
11517 + ": user " + userId + " is stopped");
11518 return ActivityManager.BROADCAST_SUCCESS;
11519 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011520 }
11521
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011522 /*
11523 * Prevent non-system code (defined here to be non-persistent
11524 * processes) from sending protected broadcasts.
11525 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011526 int callingAppId = UserHandle.getAppId(callingUid);
11527 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11528 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011529 callingUid == 0) {
11530 // Always okay.
11531 } else if (callerApp == null || !callerApp.persistent) {
11532 try {
11533 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11534 intent.getAction())) {
11535 String msg = "Permission Denial: not allowed to send broadcast "
11536 + intent.getAction() + " from pid="
11537 + callingPid + ", uid=" + callingUid;
11538 Slog.w(TAG, msg);
11539 throw new SecurityException(msg);
11540 }
11541 } catch (RemoteException e) {
11542 Slog.w(TAG, "Remote exception", e);
11543 return ActivityManager.BROADCAST_SUCCESS;
11544 }
11545 }
11546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 // Handle special intents: if this broadcast is from the package
11548 // manager about a package being removed, we need to remove all of
11549 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011550 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011551 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011552 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11553 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011554 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 || uidRemoved) {
11556 if (checkComponentPermission(
11557 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011558 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011559 == PackageManager.PERMISSION_GRANTED) {
11560 if (uidRemoved) {
11561 final Bundle intentExtras = intent.getExtras();
11562 final int uid = intentExtras != null
11563 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11564 if (uid >= 0) {
11565 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11566 synchronized (bs) {
11567 bs.removeUidStatsLocked(uid);
11568 }
11569 }
11570 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011571 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011572 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011573 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011574 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11575 if (list != null && (list.length > 0)) {
11576 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011577 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011578 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011579 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011580 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011581 }
11582 } else {
11583 Uri data = intent.getData();
11584 String ssp;
11585 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11586 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11587 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011588 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11589 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011590 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011591 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011592 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011593 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011594 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 }
11596 }
11597 }
11598 } else {
11599 String msg = "Permission Denial: " + intent.getAction()
11600 + " broadcast from " + callerPackage + " (pid=" + callingPid
11601 + ", uid=" + callingUid + ")"
11602 + " requires "
11603 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011604 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 throw new SecurityException(msg);
11606 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011607
11608 // Special case for adding a package: by default turn on compatibility
11609 // mode.
11610 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011611 Uri data = intent.getData();
11612 String ssp;
11613 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11614 mCompatModePackages.handlePackageAddedLocked(ssp,
11615 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 }
11618
11619 /*
11620 * If this is the time zone changed action, queue up a message that will reset the timezone
11621 * of all currently running processes. This message will get queued up before the broadcast
11622 * happens.
11623 */
11624 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11625 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11626 }
11627
Robert Greenwalt03595d02010-11-02 14:08:23 -070011628 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11629 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11630 }
11631
Robert Greenwalt434203a2010-10-11 16:00:27 -070011632 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11633 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11634 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11635 }
11636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 // Add to the sticky list if requested.
11638 if (sticky) {
11639 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11640 callingPid, callingUid)
11641 != PackageManager.PERMISSION_GRANTED) {
11642 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11643 + callingPid + ", uid=" + callingUid
11644 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011645 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 throw new SecurityException(msg);
11647 }
11648 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011649 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011651 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011652 }
11653 if (intent.getComponent() != null) {
11654 throw new SecurityException(
11655 "Sticky broadcasts can't target a specific component");
11656 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011657 // We use userId directly here, since the "all" target is maintained
11658 // as a separate set of sticky broadcasts.
11659 if (userId != UserHandle.USER_ALL) {
11660 // But first, if this is not a broadcast to all users, then
11661 // make sure it doesn't conflict with an existing broadcast to
11662 // all users.
11663 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11664 UserHandle.USER_ALL);
11665 if (stickies != null) {
11666 ArrayList<Intent> list = stickies.get(intent.getAction());
11667 if (list != null) {
11668 int N = list.size();
11669 int i;
11670 for (i=0; i<N; i++) {
11671 if (intent.filterEquals(list.get(i))) {
11672 throw new IllegalArgumentException(
11673 "Sticky broadcast " + intent + " for user "
11674 + userId + " conflicts with existing global broadcast");
11675 }
11676 }
11677 }
11678 }
11679 }
11680 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11681 if (stickies == null) {
11682 stickies = new HashMap<String, ArrayList<Intent>>();
11683 mStickyBroadcasts.put(userId, stickies);
11684 }
11685 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011686 if (list == null) {
11687 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011688 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 }
11690 int N = list.size();
11691 int i;
11692 for (i=0; i<N; i++) {
11693 if (intent.filterEquals(list.get(i))) {
11694 // This sticky already exists, replace it.
11695 list.set(i, new Intent(intent));
11696 break;
11697 }
11698 }
11699 if (i >= N) {
11700 list.add(new Intent(intent));
11701 }
11702 }
11703
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011704 int[] users;
11705 if (userId == UserHandle.USER_ALL) {
11706 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011707 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011708 } else {
11709 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011710 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011711 }
11712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 // Figure out who all will receive this broadcast.
11714 List receivers = null;
11715 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011716 // Need to resolve the intent to interested receivers...
11717 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11718 == 0) {
11719 receivers = collectReceiverComponents(intent, resolvedType, users);
11720 }
11721 if (intent.getComponent() == null) {
11722 registeredReceivers = mReceiverResolver.queryIntent(intent,
11723 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 }
11725
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011726 final boolean replacePending =
11727 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11728
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011730 + " replacePending=" + replacePending);
11731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011732 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11733 if (!ordered && NR > 0) {
11734 // If we are not serializing this broadcast, then send the
11735 // registered receivers separately so they don't wait for the
11736 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011737 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11738 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011739 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011741 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011742 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011743 TAG, "Enqueueing parallel broadcast " + r);
11744 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011745 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011746 queue.enqueueParallelBroadcastLocked(r);
11747 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749 registeredReceivers = null;
11750 NR = 0;
11751 }
11752
11753 // Merge into one list.
11754 int ir = 0;
11755 if (receivers != null) {
11756 // A special case for PACKAGE_ADDED: do not allow the package
11757 // being added to see this broadcast. This prevents them from
11758 // using this as a back door to get run as soon as they are
11759 // installed. Maybe in the future we want to have a special install
11760 // broadcast or such for apps, but we'd like to deliberately make
11761 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011762 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011763 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11764 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11765 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011766 Uri data = intent.getData();
11767 if (data != null) {
11768 String pkgName = data.getSchemeSpecificPart();
11769 if (pkgName != null) {
11770 skipPackages = new String[] { pkgName };
11771 }
11772 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011773 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011774 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011775 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011776 if (skipPackages != null && (skipPackages.length > 0)) {
11777 for (String skipPackage : skipPackages) {
11778 if (skipPackage != null) {
11779 int NT = receivers.size();
11780 for (int it=0; it<NT; it++) {
11781 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11782 if (curt.activityInfo.packageName.equals(skipPackage)) {
11783 receivers.remove(it);
11784 it--;
11785 NT--;
11786 }
11787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 }
11789 }
11790 }
11791
11792 int NT = receivers != null ? receivers.size() : 0;
11793 int it = 0;
11794 ResolveInfo curt = null;
11795 BroadcastFilter curr = null;
11796 while (it < NT && ir < NR) {
11797 if (curt == null) {
11798 curt = (ResolveInfo)receivers.get(it);
11799 }
11800 if (curr == null) {
11801 curr = registeredReceivers.get(ir);
11802 }
11803 if (curr.getPriority() >= curt.priority) {
11804 // Insert this broadcast record into the final list.
11805 receivers.add(it, curr);
11806 ir++;
11807 curr = null;
11808 it++;
11809 NT++;
11810 } else {
11811 // Skip to the next ResolveInfo in the final list.
11812 it++;
11813 curt = null;
11814 }
11815 }
11816 }
11817 while (ir < NR) {
11818 if (receivers == null) {
11819 receivers = new ArrayList();
11820 }
11821 receivers.add(registeredReceivers.get(ir));
11822 ir++;
11823 }
11824
11825 if ((receivers != null && receivers.size() > 0)
11826 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011827 BroadcastQueue queue = broadcastQueueForIntent(intent);
11828 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011829 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011830 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011831 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011832 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011833 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011834 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011835 if (DEBUG_BROADCAST) {
11836 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011837 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011838 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011839 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011840 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011841 queue.enqueueOrderedBroadcastLocked(r);
11842 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 }
11845
Dianne Hackborna4972e92012-03-14 10:38:05 -070011846 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 }
11848
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011849 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850 // Refuse possible leaked file descriptors
11851 if (intent != null && intent.hasFileDescriptors() == true) {
11852 throw new IllegalArgumentException("File descriptors passed in Intent");
11853 }
11854
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011855 int flags = intent.getFlags();
11856
11857 if (!mProcessesReady) {
11858 // if the caller really truly claims to know what they're doing, go
11859 // ahead and allow the broadcast without launching any receivers
11860 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11861 intent = new Intent(intent);
11862 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11863 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11864 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11865 + " before boot completion");
11866 throw new IllegalStateException("Cannot broadcast before boot completed");
11867 }
11868 }
11869
11870 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11871 throw new IllegalArgumentException(
11872 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11873 }
11874
11875 return intent;
11876 }
11877
11878 public final int broadcastIntent(IApplicationThread caller,
11879 Intent intent, String resolvedType, IIntentReceiver resultTo,
11880 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011881 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011882 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011883 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011884 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11887 final int callingPid = Binder.getCallingPid();
11888 final int callingUid = Binder.getCallingUid();
11889 final long origId = Binder.clearCallingIdentity();
11890 int res = broadcastIntentLocked(callerApp,
11891 callerApp != null ? callerApp.info.packageName : null,
11892 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011893 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070011894 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011895 Binder.restoreCallingIdentity(origId);
11896 return res;
11897 }
11898 }
11899
11900 int broadcastIntentInPackage(String packageName, int uid,
11901 Intent intent, String resolvedType, IIntentReceiver resultTo,
11902 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011903 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011905 intent = verifyBroadcastLocked(intent);
11906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011907 final long origId = Binder.clearCallingIdentity();
11908 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11909 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011910 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 Binder.restoreCallingIdentity(origId);
11912 return res;
11913 }
11914 }
11915
Amith Yamasani742a6712011-05-04 14:49:28 -070011916 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 // Refuse possible leaked file descriptors
11918 if (intent != null && intent.hasFileDescriptors() == true) {
11919 throw new IllegalArgumentException("File descriptors passed in Intent");
11920 }
11921
Dianne Hackborn139748f2012-09-24 11:36:57 -070011922 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011923 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 synchronized(this) {
11926 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11927 != PackageManager.PERMISSION_GRANTED) {
11928 String msg = "Permission Denial: unbroadcastIntent() from pid="
11929 + Binder.getCallingPid()
11930 + ", uid=" + Binder.getCallingUid()
11931 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011932 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 throw new SecurityException(msg);
11934 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011935 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11936 if (stickies != null) {
11937 ArrayList<Intent> list = stickies.get(intent.getAction());
11938 if (list != null) {
11939 int N = list.size();
11940 int i;
11941 for (i=0; i<N; i++) {
11942 if (intent.filterEquals(list.get(i))) {
11943 list.remove(i);
11944 break;
11945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011947 if (list.size() <= 0) {
11948 stickies.remove(intent.getAction());
11949 }
11950 }
11951 if (stickies.size() <= 0) {
11952 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953 }
11954 }
11955 }
11956 }
11957
11958 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11959 String resultData, Bundle resultExtras, boolean resultAbort,
11960 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011961 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11962 if (r == null) {
11963 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011964 return false;
11965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966
Christopher Tatef46723b2012-01-26 14:19:24 -080011967 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11968 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 }
11970
11971 public void finishReceiver(IBinder who, int resultCode, String resultData,
11972 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011973 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974
11975 // Refuse possible leaked file descriptors
11976 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11977 throw new IllegalArgumentException("File descriptors passed in Bundle");
11978 }
11979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011981 try {
11982 boolean doNext = false;
11983 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984
Christopher Tatef46723b2012-01-26 14:19:24 -080011985 synchronized(this) {
11986 r = broadcastRecordForReceiverLocked(who);
11987 if (r != null) {
11988 doNext = r.queue.finishReceiverLocked(r, resultCode,
11989 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011992
Christopher Tatef46723b2012-01-26 14:19:24 -080011993 if (doNext) {
11994 r.queue.processNextBroadcast(false);
11995 }
11996 trimApplications();
11997 } finally {
11998 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 // =========================================================
12003 // INSTRUMENTATION
12004 // =========================================================
12005
12006 public boolean startInstrumentation(ComponentName className,
12007 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012008 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
12009 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012010 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012011 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012012 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012013 // Refuse possible leaked file descriptors
12014 if (arguments != null && arguments.hasFileDescriptors()) {
12015 throw new IllegalArgumentException("File descriptors passed in Bundle");
12016 }
12017
12018 synchronized(this) {
12019 InstrumentationInfo ii = null;
12020 ApplicationInfo ai = null;
12021 try {
12022 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012023 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012024 ai = AppGlobals.getPackageManager().getApplicationInfo(
12025 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012026 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012027 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 }
12029 if (ii == null) {
12030 reportStartInstrumentationFailure(watcher, className,
12031 "Unable to find instrumentation info for: " + className);
12032 return false;
12033 }
12034 if (ai == null) {
12035 reportStartInstrumentationFailure(watcher, className,
12036 "Unable to find instrumentation target package: " + ii.targetPackage);
12037 return false;
12038 }
12039
12040 int match = mContext.getPackageManager().checkSignatures(
12041 ii.targetPackage, ii.packageName);
12042 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12043 String msg = "Permission Denial: starting instrumentation "
12044 + className + " from pid="
12045 + Binder.getCallingPid()
12046 + ", uid=" + Binder.getCallingPid()
12047 + " not allowed because package " + ii.packageName
12048 + " does not have a signature matching the target "
12049 + ii.targetPackage;
12050 reportStartInstrumentationFailure(watcher, className, msg);
12051 throw new SecurityException(msg);
12052 }
12053
12054 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012055 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012056 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012057 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012059 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 app.instrumentationProfileFile = profileFile;
12061 app.instrumentationArguments = arguments;
12062 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012063 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012064 app.instrumentationResultClass = className;
12065 Binder.restoreCallingIdentity(origId);
12066 }
12067
12068 return true;
12069 }
12070
12071 /**
12072 * Report errors that occur while attempting to start Instrumentation. Always writes the
12073 * error to the logs, but if somebody is watching, send the report there too. This enables
12074 * the "am" command to report errors with more information.
12075 *
12076 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12077 * @param cn The component name of the instrumentation.
12078 * @param report The error report.
12079 */
12080 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12081 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012082 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 try {
12084 if (watcher != null) {
12085 Bundle results = new Bundle();
12086 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12087 results.putString("Error", report);
12088 watcher.instrumentationStatus(cn, -1, results);
12089 }
12090 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012091 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 }
12093 }
12094
12095 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12096 if (app.instrumentationWatcher != null) {
12097 try {
12098 // NOTE: IInstrumentationWatcher *must* be oneway here
12099 app.instrumentationWatcher.instrumentationFinished(
12100 app.instrumentationClass,
12101 resultCode,
12102 results);
12103 } catch (RemoteException e) {
12104 }
12105 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012106 if (app.instrumentationUiAutomationConnection != null) {
12107 try {
12108 app.instrumentationUiAutomationConnection.shutdown();
12109 } catch (RemoteException re) {
12110 /* ignore */
12111 }
12112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012114 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012116 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 app.instrumentationProfileFile = null;
12118 app.instrumentationArguments = null;
12119
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012120 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012121 }
12122
12123 public void finishInstrumentation(IApplicationThread target,
12124 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012125 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 // Refuse possible leaked file descriptors
12127 if (results != null && results.hasFileDescriptors()) {
12128 throw new IllegalArgumentException("File descriptors passed in Intent");
12129 }
12130
12131 synchronized(this) {
12132 ProcessRecord app = getRecordForAppLocked(target);
12133 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012134 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012135 return;
12136 }
12137 final long origId = Binder.clearCallingIdentity();
12138 finishInstrumentationLocked(app, resultCode, results);
12139 Binder.restoreCallingIdentity(origId);
12140 }
12141 }
12142
12143 // =========================================================
12144 // CONFIGURATION
12145 // =========================================================
12146
12147 public ConfigurationInfo getDeviceConfigurationInfo() {
12148 ConfigurationInfo config = new ConfigurationInfo();
12149 synchronized (this) {
12150 config.reqTouchScreen = mConfiguration.touchscreen;
12151 config.reqKeyboardType = mConfiguration.keyboard;
12152 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012153 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12154 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012155 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12156 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012157 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12158 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012159 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12160 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012161 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012162 }
12163 return config;
12164 }
12165
12166 public Configuration getConfiguration() {
12167 Configuration ci;
12168 synchronized(this) {
12169 ci = new Configuration(mConfiguration);
12170 }
12171 return ci;
12172 }
12173
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012174 public void updatePersistentConfiguration(Configuration values) {
12175 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12176 "updateConfiguration()");
12177 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12178 "updateConfiguration()");
12179 if (values == null) {
12180 throw new NullPointerException("Configuration must not be null");
12181 }
12182
12183 synchronized(this) {
12184 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012185 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012186 Binder.restoreCallingIdentity(origId);
12187 }
12188 }
12189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 public void updateConfiguration(Configuration values) {
12191 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12192 "updateConfiguration()");
12193
12194 synchronized(this) {
12195 if (values == null && mWindowManager != null) {
12196 // sentinel: fetch the current configuration from the window manager
12197 values = mWindowManager.computeNewConfiguration();
12198 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012199
12200 if (mWindowManager != null) {
12201 mProcessList.applyDisplaySize(mWindowManager);
12202 }
12203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012204 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012205 if (values != null) {
12206 Settings.System.clearConfiguration(values);
12207 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012208 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 Binder.restoreCallingIdentity(origId);
12210 }
12211 }
12212
12213 /**
12214 * Do either or both things: (1) change the current configuration, and (2)
12215 * make sure the given activity is running with the (now) current
12216 * configuration. Returns true if the activity has been left running, or
12217 * false if <var>starting</var> is being destroyed to match the new
12218 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012219 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012221 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012222 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012223 // do nothing if we are headless
12224 if (mHeadless) return true;
12225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012226 int changes = 0;
12227
12228 boolean kept = true;
12229
12230 if (values != null) {
12231 Configuration newConfig = new Configuration(mConfiguration);
12232 changes = newConfig.updateFrom(values);
12233 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012234 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012235 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 }
12237
Doug Zongker2bec3d42009-12-04 12:52:44 -080012238 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239
Dianne Hackborn813075a62011-11-14 17:45:19 -080012240 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241 saveLocaleLocked(values.locale,
12242 !values.locale.equals(mConfiguration.locale),
12243 values.userSetLocale);
12244 }
12245
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012246 mConfigurationSeq++;
12247 if (mConfigurationSeq <= 0) {
12248 mConfigurationSeq = 1;
12249 }
12250 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012252 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012253
12254 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012255
12256 // TODO: If our config changes, should we auto dismiss any currently
12257 // showing dialogs?
12258 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012259
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012260 AttributeCache ac = AttributeCache.instance();
12261 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012262 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012265 // Make sure all resources in our process are updated
12266 // right now, so that anyone who is going to retrieve
12267 // resource values after we return will be sure to get
12268 // the new ones. This is especially important during
12269 // boot, where the first config change needs to guarantee
12270 // all resources have that config before following boot
12271 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012272 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012273
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012274 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012275 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012276 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012277 mHandler.sendMessage(msg);
12278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012279
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012280 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12281 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012282 try {
12283 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012284 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012285 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012286 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012287 }
12288 } catch (Exception e) {
12289 }
12290 }
12291 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012292 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012293 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12294 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012296 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12297 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012298 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012299 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12300 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12301 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012302 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12303 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 }
12306 }
12307
12308 if (changes != 0 && starting == null) {
12309 // If the configuration changed, and the caller is not already
12310 // in the process of starting an activity, then find the top
12311 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012312 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 }
12314
12315 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012316 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012317 // And we need to make sure at this point that all other activities
12318 // are made visible with the correct configuration.
12319 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 }
12321
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012322 if (values != null && mWindowManager != null) {
12323 mWindowManager.setNewConfiguration(mConfiguration);
12324 }
12325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012326 return kept;
12327 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012328
12329 /**
12330 * Decide based on the configuration whether we should shouw the ANR,
12331 * crash, etc dialogs. The idea is that if there is no affordnace to
12332 * press the on-screen buttons, we shouldn't show the dialog.
12333 *
12334 * A thought: SystemUI might also want to get told about this, the Power
12335 * dialog / global actions also might want different behaviors.
12336 */
12337 private static final boolean shouldShowDialogs(Configuration config) {
12338 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12339 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341
12342 /**
12343 * Save the locale. You must be inside a synchronized (this) block.
12344 */
12345 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12346 if(isDiff) {
12347 SystemProperties.set("user.language", l.getLanguage());
12348 SystemProperties.set("user.region", l.getCountry());
12349 }
12350
12351 if(isPersist) {
12352 SystemProperties.set("persist.sys.language", l.getLanguage());
12353 SystemProperties.set("persist.sys.country", l.getCountry());
12354 SystemProperties.set("persist.sys.localevar", l.getVariant());
12355 }
12356 }
12357
Adam Powelldd8fab22012-03-22 17:47:27 -070012358 @Override
12359 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12360 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012361 return srec != null && srec.task.affinity != null &&
12362 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012363 }
12364
12365 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12366 Intent resultData) {
12367 ComponentName dest = destIntent.getComponent();
12368
12369 synchronized (this) {
12370 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012371 if (srec == null) {
12372 return false;
12373 }
Craig Mautnercae015f2013-02-08 14:31:27 -080012374 ActivityStack stack = srec.stack;
12375 final int start = stack.indexOfActivityLocked(srec);
Adam Powelldd8fab22012-03-22 17:47:27 -070012376 if (start < 0) {
12377 // Current activity is not in history stack; do nothing.
12378 return false;
12379 }
12380 int finishTo = start - 1;
12381 ActivityRecord parent = null;
12382 boolean foundParentInTask = false;
12383 if (dest != null) {
12384 TaskRecord tr = srec.task;
12385 for (int i = start - 1; i >= 0; i--) {
Craig Mautnercae015f2013-02-08 14:31:27 -080012386 ActivityRecord r = stack.getActivityAtIndex(i);
Adam Powelldd8fab22012-03-22 17:47:27 -070012387 if (tr != r.task) {
12388 // Couldn't find parent in the same task; stop at the one above this.
12389 // (Root of current task; in-app "home" behavior)
12390 // Always at least finish the current activity.
12391 finishTo = Math.min(start - 1, i + 1);
Craig Mautnercae015f2013-02-08 14:31:27 -080012392 parent = stack.getActivityAtIndex(finishTo);
Adam Powelldd8fab22012-03-22 17:47:27 -070012393 break;
12394 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12395 r.info.name.equals(dest.getClassName())) {
12396 finishTo = i;
12397 parent = r;
12398 foundParentInTask = true;
12399 break;
12400 }
12401 }
12402 }
12403
12404 if (mController != null) {
12405 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12406 if (next != null) {
12407 // ask watcher if this is allowed
12408 boolean resumeOK = true;
12409 try {
12410 resumeOK = mController.activityResuming(next.packageName);
12411 } catch (RemoteException e) {
12412 mController = null;
12413 }
12414
12415 if (!resumeOK) {
12416 return false;
12417 }
12418 }
12419 }
12420 final long origId = Binder.clearCallingIdentity();
12421 for (int i = start; i > finishTo; i--) {
Craig Mautnercae015f2013-02-08 14:31:27 -080012422 ActivityRecord r = stack.getActivityAtIndex(i);
Adam Powelldd8fab22012-03-22 17:47:27 -070012423 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012424 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012425 // Only return the supplied result for the first activity finished
12426 resultCode = Activity.RESULT_CANCELED;
12427 resultData = null;
12428 }
12429
12430 if (parent != null && foundParentInTask) {
12431 final int parentLaunchMode = parent.info.launchMode;
12432 final int destIntentFlags = destIntent.getFlags();
12433 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12434 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12435 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12436 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012437 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012438 } else {
12439 try {
12440 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012441 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012442 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12443 null, aInfo, parent.appToken, null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012444 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
12445 0, null, true, null);
Adam Powelldd8fab22012-03-22 17:47:27 -070012446 foundParentInTask = res == ActivityManager.START_SUCCESS;
12447 } catch (RemoteException e) {
12448 foundParentInTask = false;
12449 }
12450 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012451 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012452 }
12453 }
12454 Binder.restoreCallingIdentity(origId);
12455 return foundParentInTask;
12456 }
12457 }
12458
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012459 public int getLaunchedFromUid(IBinder activityToken) {
12460 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12461 if (srec == null) {
12462 return -1;
12463 }
12464 return srec.launchedFromUid;
12465 }
12466
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012467 public String getLaunchedFromPackage(IBinder activityToken) {
12468 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12469 if (srec == null) {
12470 return null;
12471 }
12472 return srec.launchedFromPackage;
12473 }
12474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 // =========================================================
12476 // LIFETIME MANAGEMENT
12477 // =========================================================
12478
Christopher Tatef46723b2012-01-26 14:19:24 -080012479 // Returns which broadcast queue the app is the current [or imminent] receiver
12480 // on, or 'null' if the app is not an active broadcast recipient.
12481 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12482 BroadcastRecord r = app.curReceiver;
12483 if (r != null) {
12484 return r.queue;
12485 }
12486
12487 // It's not the current receiver, but it might be starting up to become one
12488 synchronized (this) {
12489 for (BroadcastQueue queue : mBroadcastQueues) {
12490 r = queue.mPendingBroadcast;
12491 if (r != null && r.curApp == app) {
12492 // found it; report which queue it's in
12493 return queue;
12494 }
12495 }
12496 }
12497
12498 return null;
12499 }
12500
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012501 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012502 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012503 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012504 // This adjustment has already been computed. If we are calling
12505 // from the top, we may have already computed our adjustment with
12506 // an earlier hidden adjustment that isn't really for us... if
12507 // so, use the new hidden adjustment.
12508 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012509 if (app.hasActivities) {
12510 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12511 } else if (app.hasClientActivities) {
12512 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12513 } else {
12514 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12515 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012516 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012517 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 }
12519
12520 if (app.thread == null) {
12521 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012522 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012523 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012524 }
12525
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012526 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12527 app.adjSource = null;
12528 app.adjTarget = null;
12529 app.empty = false;
12530 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012531 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012532
12533 final int activitiesSize = app.activities.size();
12534
Dianne Hackborn7d608422011-08-07 16:24:18 -070012535 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012536 // The max adjustment doesn't allow this app to be anything
12537 // below foreground, so it is not worth doing work for it.
12538 app.adjType = "fixed";
12539 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012540 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012541 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012542 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012543 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012544 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012545 // System process can do UI, and when they do we want to have
12546 // them trim their memory after the user leaves the UI. To
12547 // facilitate this, here we need to determine whether or not it
12548 // is currently showing UI.
12549 app.systemNoUi = true;
12550 if (app == TOP_APP) {
12551 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012552 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012553 } else if (activitiesSize > 0) {
12554 for (int j = 0; j < activitiesSize; j++) {
12555 final ActivityRecord r = app.activities.get(j);
12556 if (r.visible) {
12557 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012558 }
12559 if (r.app == app) {
12560 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012561 }
12562 }
12563 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012564 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012565 }
12566
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012567 app.keeping = false;
12568 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012569 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012570
The Android Open Source Project4df24232009-03-05 14:34:35 -080012571 // Determine the importance of the process, starting with most
12572 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012573 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012574 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012575 boolean foregroundActivities = false;
12576 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012577 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012578 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012579 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012580 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012581 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012582 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012583 foregroundActivities = true;
12584 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012585 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012586 } else if (app.instrumentationClass != null) {
12587 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012588 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012589 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012590 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012591 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012592 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012593 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012594 // counts as being in the foreground for OOM killer purposes.
12595 // It's placed in a sched group based on the nature of the
12596 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012597 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012598 schedGroup = (queue == mFgBroadcastQueue)
12599 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012600 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 } else if (app.executingServices.size() > 0) {
12602 // An app that is currently executing a service callback also
12603 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012604 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012605 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012606 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012607 } else {
12608 // Assume process is hidden (has activities); we will correct
12609 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012611 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012612 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012613 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012614 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012615
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012616 boolean hasStoppingActivities = false;
12617
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012618 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012619 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012620 for (int j = 0; j < activitiesSize; j++) {
12621 final ActivityRecord r = app.activities.get(j);
12622 if (r.visible) {
12623 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012624 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12625 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012626 app.adjType = "visible";
12627 }
12628 schedGroup = Process.THREAD_GROUP_DEFAULT;
12629 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012630 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012631 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012632 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012633 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012634 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12635 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012636 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012637 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012638 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012639 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012640 } else if (r.state == ActivityState.STOPPING) {
12641 // We will apply the actual adjustment later, because
12642 // we want to allow this process to immediately go through
12643 // any memory trimming that is in effect.
12644 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012645 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012646 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012647 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012648 if (r.app == app) {
12649 app.hasActivities = true;
12650 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012651 }
12652 }
12653
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012654 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012655 if (app.hasClientActivities) {
12656 adj = clientHiddenAdj;
12657 app.adjType = "bg-client-act";
12658 } else {
12659 // Whoops, this process is completely empty as far as we know
12660 // at this point.
12661 adj = emptyAdj;
12662 app.empty = true;
12663 app.adjType = "bg-empty";
12664 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012665 }
12666
Dianne Hackborn7d608422011-08-07 16:24:18 -070012667 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012668 if (app.foregroundServices) {
12669 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012670 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012671 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012672 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012673 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012674 } else if (app.forcingToForeground != null) {
12675 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012676 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012677 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012678 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012679 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012680 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012681 }
12682 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012683
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012684 if (app.foregroundServices) {
12685 interesting = true;
12686 }
12687
Dianne Hackborn7d608422011-08-07 16:24:18 -070012688 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012689 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012690 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012691 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012692 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012693 app.adjType = "heavy";
12694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695
Dianne Hackborn7d608422011-08-07 16:24:18 -070012696 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012697 // This process is hosting what we currently consider to be the
12698 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012699 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012700 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012701 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012702 app.adjType = "home";
12703 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012704
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012705 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12706 && app.activities.size() > 0) {
12707 // This was the previous process that showed UI to the user.
12708 // We want to try to keep it around more aggressively, to give
12709 // a good experience around switching between two apps.
12710 adj = ProcessList.PREVIOUS_APP_ADJ;
12711 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12712 app.hidden = false;
12713 app.adjType = "previous";
12714 }
12715
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012716 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12717 + " reason=" + app.adjType);
12718
The Android Open Source Project4df24232009-03-05 14:34:35 -080012719 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012720 // there are applications dependent on our services or providers, but
12721 // this gives us a baseline and makes sure we don't get into an
12722 // infinite recursion.
12723 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012724 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725
Christopher Tate6fa95972009-06-05 18:43:55 -070012726 if (mBackupTarget != null && app == mBackupTarget.app) {
12727 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012728 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012729 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012730 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012731 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012732 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012733 }
12734 }
12735
Dianne Hackborn7d608422011-08-07 16:24:18 -070012736 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012737 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 final long now = SystemClock.uptimeMillis();
12739 // This process is more important if the top activity is
12740 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012741 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012742 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012743 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012744 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012745 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012746 // If this process has shown some UI, let it immediately
12747 // go to the LRU list because it may be pretty heavy with
12748 // UI stuff. We'll tag it with a label just to help
12749 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012750 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012751 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012753 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012754 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012755 // This service has seen some activity within
12756 // recent memory, so we will keep its process ahead
12757 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012758 if (adj > ProcessList.SERVICE_ADJ) {
12759 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012760 app.adjType = "started-services";
12761 app.hidden = false;
12762 }
12763 }
12764 // If we have let the service slide into the background
12765 // state, still have some text describing what it is doing
12766 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012767 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012768 app.adjType = "started-bg-services";
12769 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012770 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012771 // Don't kill this process because it is doing work; it
12772 // has said it is doing work.
12773 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012774 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012775 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012776 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012777 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012778 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012779 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012780 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012781 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012782 // XXX should compute this based on the max of
12783 // all connected clients.
12784 ConnectionRecord cr = clist.get(i);
12785 if (cr.binding.client == app) {
12786 // Binding to ourself is not interesting.
12787 continue;
12788 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012789 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012790 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012791 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012792 int myHiddenAdj = hiddenAdj;
12793 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012794 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012795 myHiddenAdj = client.hiddenAdj;
12796 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012797 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012798 }
12799 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012800 int myClientHiddenAdj = clientHiddenAdj;
12801 if (myClientHiddenAdj > client.clientHiddenAdj) {
12802 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12803 myClientHiddenAdj = client.clientHiddenAdj;
12804 } else {
12805 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12806 }
12807 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012808 int myEmptyAdj = emptyAdj;
12809 if (myEmptyAdj > client.emptyAdj) {
12810 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12811 myEmptyAdj = client.emptyAdj;
12812 } else {
12813 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12814 }
12815 }
12816 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012817 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012818 String adjType = null;
12819 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12820 // Not doing bind OOM management, so treat
12821 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012822 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012823 // If this process has shown some UI, let it immediately
12824 // go to the LRU list because it may be pretty heavy with
12825 // UI stuff. We'll tag it with a label just to help
12826 // debug and understand what is going on.
12827 if (adj > clientAdj) {
12828 adjType = "bound-bg-ui-services";
12829 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012830 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012831 clientAdj = adj;
12832 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012833 if (now >= (s.lastActivity
12834 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012835 // This service has not seen activity within
12836 // recent memory, so allow it to drop to the
12837 // LRU list if there is no other reason to keep
12838 // it around. We'll also tag it with a label just
12839 // to help debug and undertand what is going on.
12840 if (adj > clientAdj) {
12841 adjType = "bound-bg-services";
12842 }
12843 clientAdj = adj;
12844 }
12845 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012846 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12847 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12848 // If this connection is keeping the service
12849 // created, then we want to try to better follow
12850 // its memory management semantics for activities.
12851 // That is, if it is sitting in the background
12852 // LRU list as a hidden process (with activities),
12853 // we don't want the service it is connected to
12854 // to go into the empty LRU and quickly get killed,
12855 // because I'll we'll do is just end up restarting
12856 // the service.
12857 app.hasClientActivities |= client.hasActivities;
12858 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012859 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012860 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012861 // If this process has recently shown UI, and
12862 // the process that is binding to it is less
12863 // important than being visible, then we don't
12864 // care about the binding as much as we care
12865 // about letting this process get into the LRU
12866 // list to be killed and restarted if needed for
12867 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012868 if (app.hasShownUi && app != mHomeProcess
12869 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012870 adjType = "bound-bg-ui-services";
12871 } else {
12872 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12873 |Context.BIND_IMPORTANT)) != 0) {
12874 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012875 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12876 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12877 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12878 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12879 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012880 adj = clientAdj;
12881 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012882 app.pendingUiClean = true;
12883 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12884 adj = ProcessList.VISIBLE_APP_ADJ;
12885 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012886 }
12887 if (!client.hidden) {
12888 app.hidden = false;
12889 }
12890 if (client.keeping) {
12891 app.keeping = true;
12892 }
12893 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012894 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012895 }
12896 if (adjType != null) {
12897 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012898 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12899 .REASON_SERVICE_IN_USE;
12900 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012901 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012902 app.adjTarget = s.name;
12903 }
12904 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12905 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12906 schedGroup = Process.THREAD_GROUP_DEFAULT;
12907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012908 }
12909 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012910 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012911 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012912 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012913 (a.visible || a.state == ActivityState.RESUMED
12914 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012915 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012916 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12917 schedGroup = Process.THREAD_GROUP_DEFAULT;
12918 }
12919 app.hidden = false;
12920 app.adjType = "service";
12921 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12922 .REASON_SERVICE_IN_USE;
12923 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012924 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012925 app.adjTarget = s.name;
12926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 }
12929 }
12930 }
12931 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012932
Dianne Hackborn287952c2010-09-22 22:34:31 -070012933 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012934 // would like to avoid killing it unless it would prevent the current
12935 // application from running. By default we put the process in
12936 // with the rest of the background processes; as we scan through
12937 // its services we may bump it up from there.
12938 if (adj > hiddenAdj) {
12939 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012940 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012941 app.adjType = "bg-services";
12942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 }
12944
Dianne Hackborn7d608422011-08-07 16:24:18 -070012945 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012946 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012947 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012948 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012949 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012950 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012951 for (int i = cpr.connections.size()-1;
12952 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12953 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12954 i--) {
12955 ContentProviderConnection conn = cpr.connections.get(i);
12956 ProcessRecord client = conn.client;
12957 if (client == app) {
12958 // Being our own client is not interesting.
12959 continue;
12960 }
12961 int myHiddenAdj = hiddenAdj;
12962 if (myHiddenAdj > client.hiddenAdj) {
12963 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12964 myHiddenAdj = client.hiddenAdj;
12965 } else {
12966 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012967 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012968 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012969 int myClientHiddenAdj = clientHiddenAdj;
12970 if (myClientHiddenAdj > client.clientHiddenAdj) {
12971 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
12972 myClientHiddenAdj = client.clientHiddenAdj;
12973 } else {
12974 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
12975 }
12976 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012977 int myEmptyAdj = emptyAdj;
12978 if (myEmptyAdj > client.emptyAdj) {
12979 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12980 myEmptyAdj = client.emptyAdj;
12981 } else {
12982 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12983 }
12984 }
12985 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012986 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012987 if (adj > clientAdj) {
12988 if (app.hasShownUi && app != mHomeProcess
12989 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12990 app.adjType = "bg-ui-provider";
12991 } else {
12992 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12993 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12994 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012996 if (!client.hidden) {
12997 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012999 if (client.keeping) {
13000 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013001 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013002 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13003 .REASON_PROVIDER_IN_USE;
13004 app.adjSource = client;
13005 app.adjSourceOom = clientAdj;
13006 app.adjTarget = cpr.name;
13007 }
13008 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13009 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 }
13011 }
13012 // If the provider has external (non-framework) process
13013 // dependencies, ensure that its adjustment is at least
13014 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013015 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013016 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13017 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013018 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013019 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013020 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013021 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013022 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013023 }
13024 }
13025 }
13026 }
13027
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013028 if (adj == ProcessList.SERVICE_ADJ) {
13029 if (doingAll) {
13030 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13031 mNewNumServiceProcs++;
13032 }
13033 if (app.serviceb) {
13034 adj = ProcessList.SERVICE_B_ADJ;
13035 }
13036 } else {
13037 app.serviceb = false;
13038 }
13039
13040 app.nonStoppingAdj = adj;
13041
13042 if (hasStoppingActivities) {
13043 // Only upgrade adjustment.
13044 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13045 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13046 app.adjType = "stopping";
13047 }
13048 }
13049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 app.curRawAdj = adj;
13051
Joe Onorato8a9b2202010-02-26 18:56:32 -080013052 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013053 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13054 if (adj > app.maxAdj) {
13055 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013056 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013057 schedGroup = Process.THREAD_GROUP_DEFAULT;
13058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013060 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013061 app.keeping = true;
13062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013064 if (app.hasAboveClient) {
13065 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13066 // then we need to drop its adjustment to be lower than the service's
13067 // in order to honor the request. We want to drop it by one adjustment
13068 // level... but there is special meaning applied to various levels so
13069 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013070 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013071 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013072 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13073 adj = ProcessList.VISIBLE_APP_ADJ;
13074 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13075 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13076 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13077 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013078 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013079 adj++;
13080 }
13081 }
13082
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013083 int importance = app.memImportance;
13084 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13085 app.curAdj = adj;
13086 app.curSchedGroup = schedGroup;
13087 if (!interesting) {
13088 // For this reporting, if there is not something explicitly
13089 // interesting in this process then we will push it to the
13090 // background importance.
13091 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13092 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13093 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13094 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13095 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13096 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13097 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13098 } else if (adj >= ProcessList.SERVICE_ADJ) {
13099 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13100 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13101 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13102 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13103 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13104 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13105 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13106 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13107 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13108 } else {
13109 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13110 }
13111 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013112
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013113 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13114 if (foregroundActivities != app.foregroundActivities) {
13115 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13116 }
13117 if (changes != 0) {
13118 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13119 app.memImportance = importance;
13120 app.foregroundActivities = foregroundActivities;
13121 int i = mPendingProcessChanges.size()-1;
13122 ProcessChangeItem item = null;
13123 while (i >= 0) {
13124 item = mPendingProcessChanges.get(i);
13125 if (item.pid == app.pid) {
13126 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13127 break;
13128 }
13129 i--;
13130 }
13131 if (i < 0) {
13132 // No existing item in pending changes; need a new one.
13133 final int NA = mAvailProcessChanges.size();
13134 if (NA > 0) {
13135 item = mAvailProcessChanges.remove(NA-1);
13136 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13137 } else {
13138 item = new ProcessChangeItem();
13139 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13140 }
13141 item.changes = 0;
13142 item.pid = app.pid;
13143 item.uid = app.info.uid;
13144 if (mPendingProcessChanges.size() == 0) {
13145 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13146 "*** Enqueueing dispatch processes changed!");
13147 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13148 }
13149 mPendingProcessChanges.add(item);
13150 }
13151 item.changes |= changes;
13152 item.importance = importance;
13153 item.foregroundActivities = foregroundActivities;
13154 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13155 + Integer.toHexString(System.identityHashCode(item))
13156 + " " + app.toShortString() + ": changes=" + item.changes
13157 + " importance=" + item.importance
13158 + " foreground=" + item.foregroundActivities
13159 + " type=" + app.adjType + " source=" + app.adjSource
13160 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013161 }
13162
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013163 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
13165
13166 /**
13167 * Ask a given process to GC right now.
13168 */
13169 final void performAppGcLocked(ProcessRecord app) {
13170 try {
13171 app.lastRequestedGc = SystemClock.uptimeMillis();
13172 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013173 if (app.reportLowMemory) {
13174 app.reportLowMemory = false;
13175 app.thread.scheduleLowMemory();
13176 } else {
13177 app.thread.processInBackground();
13178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 }
13180 } catch (Exception e) {
13181 // whatever.
13182 }
13183 }
13184
13185 /**
13186 * Returns true if things are idle enough to perform GCs.
13187 */
Josh Bartel7f208742010-02-25 11:01:44 -060013188 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013189 boolean processingBroadcasts = false;
13190 for (BroadcastQueue q : mBroadcastQueues) {
13191 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13192 processingBroadcasts = true;
13193 }
13194 }
13195 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013196 && (mSleeping || (mMainStack.mResumedActivity != null &&
13197 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 }
13199
13200 /**
13201 * Perform GCs on all processes that are waiting for it, but only
13202 * if things are idle.
13203 */
13204 final void performAppGcsLocked() {
13205 final int N = mProcessesToGc.size();
13206 if (N <= 0) {
13207 return;
13208 }
Josh Bartel7f208742010-02-25 11:01:44 -060013209 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 while (mProcessesToGc.size() > 0) {
13211 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013212 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013213 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13214 <= SystemClock.uptimeMillis()) {
13215 // To avoid spamming the system, we will GC processes one
13216 // at a time, waiting a few seconds between each.
13217 performAppGcLocked(proc);
13218 scheduleAppGcsLocked();
13219 return;
13220 } else {
13221 // It hasn't been long enough since we last GCed this
13222 // process... put it in the list to wait for its time.
13223 addProcessToGcListLocked(proc);
13224 break;
13225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226 }
13227 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013228
13229 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 }
13231 }
13232
13233 /**
13234 * If all looks good, perform GCs on all processes waiting for them.
13235 */
13236 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013237 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 performAppGcsLocked();
13239 return;
13240 }
13241 // Still not idle, wait some more.
13242 scheduleAppGcsLocked();
13243 }
13244
13245 /**
13246 * Schedule the execution of all pending app GCs.
13247 */
13248 final void scheduleAppGcsLocked() {
13249 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013250
13251 if (mProcessesToGc.size() > 0) {
13252 // Schedule a GC for the time to the next process.
13253 ProcessRecord proc = mProcessesToGc.get(0);
13254 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13255
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013256 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013257 long now = SystemClock.uptimeMillis();
13258 if (when < (now+GC_TIMEOUT)) {
13259 when = now + GC_TIMEOUT;
13260 }
13261 mHandler.sendMessageAtTime(msg, when);
13262 }
13263 }
13264
13265 /**
13266 * Add a process to the array of processes waiting to be GCed. Keeps the
13267 * list in sorted order by the last GC time. The process can't already be
13268 * on the list.
13269 */
13270 final void addProcessToGcListLocked(ProcessRecord proc) {
13271 boolean added = false;
13272 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13273 if (mProcessesToGc.get(i).lastRequestedGc <
13274 proc.lastRequestedGc) {
13275 added = true;
13276 mProcessesToGc.add(i+1, proc);
13277 break;
13278 }
13279 }
13280 if (!added) {
13281 mProcessesToGc.add(0, proc);
13282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013283 }
13284
13285 /**
13286 * Set up to ask a process to GC itself. This will either do it
13287 * immediately, or put it on the list of processes to gc the next
13288 * time things are idle.
13289 */
13290 final void scheduleAppGcLocked(ProcessRecord app) {
13291 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013292 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013293 return;
13294 }
13295 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013296 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 scheduleAppGcsLocked();
13298 }
13299 }
13300
Dianne Hackborn287952c2010-09-22 22:34:31 -070013301 final void checkExcessivePowerUsageLocked(boolean doKills) {
13302 updateCpuStatsNow();
13303
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013304 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013305 boolean doWakeKills = doKills;
13306 boolean doCpuKills = doKills;
13307 if (mLastPowerCheckRealtime == 0) {
13308 doWakeKills = false;
13309 }
13310 if (mLastPowerCheckUptime == 0) {
13311 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013312 }
13313 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013314 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013315 }
13316 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013317 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13318 final long curUptime = SystemClock.uptimeMillis();
13319 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13320 mLastPowerCheckRealtime = curRealtime;
13321 mLastPowerCheckUptime = curUptime;
13322 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13323 doWakeKills = false;
13324 }
13325 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13326 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013327 }
13328 int i = mLruProcesses.size();
13329 while (i > 0) {
13330 i--;
13331 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013332 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013333 long wtime;
13334 synchronized (stats) {
13335 wtime = stats.getProcessWakeTime(app.info.uid,
13336 app.pid, curRealtime);
13337 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013338 long wtimeUsed = wtime - app.lastWakeTime;
13339 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13340 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013341 StringBuilder sb = new StringBuilder(128);
13342 sb.append("Wake for ");
13343 app.toShortString(sb);
13344 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013345 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013346 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013347 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013348 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013349 sb.append((wtimeUsed*100)/realtimeSince);
13350 sb.append("%)");
13351 Slog.i(TAG, sb.toString());
13352 sb.setLength(0);
13353 sb.append("CPU for ");
13354 app.toShortString(sb);
13355 sb.append(": over ");
13356 TimeUtils.formatDuration(uptimeSince, sb);
13357 sb.append(" used ");
13358 TimeUtils.formatDuration(cputimeUsed, sb);
13359 sb.append(" (");
13360 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013361 sb.append("%)");
13362 Slog.i(TAG, sb.toString());
13363 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013364 // If a process has held a wake lock for more
13365 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013366 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013367 if (doWakeKills && realtimeSince > 0
13368 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13369 synchronized (stats) {
13370 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13371 realtimeSince, wtimeUsed);
13372 }
13373 Slog.w(TAG, "Excessive wake lock in " + app.processName
13374 + " (pid " + app.pid + "): held " + wtimeUsed
13375 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013376 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013377 app.processName, app.setAdj, "excessive wake lock");
13378 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013379 } else if (doCpuKills && uptimeSince > 0
13380 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13381 synchronized (stats) {
13382 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13383 uptimeSince, cputimeUsed);
13384 }
13385 Slog.w(TAG, "Excessive CPU in " + app.processName
13386 + " (pid " + app.pid + "): used " + cputimeUsed
13387 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013388 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013389 app.processName, app.setAdj, "excessive cpu");
13390 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013391 } else {
13392 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013393 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013394 }
13395 }
13396 }
13397 }
13398
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013399 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013400 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013401 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013402 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013403 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404
13405 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013406 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 }
13408
Dianne Hackborn287952c2010-09-22 22:34:31 -070013409 final boolean wasKeeping = app.keeping;
13410
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013411 boolean success = true;
13412
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013413 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013414
Jeff Brown10e89712011-07-08 18:52:57 -070013415 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013416 if (wasKeeping && !app.keeping) {
13417 // This app is no longer something we want to keep. Note
13418 // its current wake lock time to later know to kill it if
13419 // it is not behaving well.
13420 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13421 synchronized (stats) {
13422 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13423 app.pid, SystemClock.elapsedRealtime());
13424 }
13425 app.lastCpuTime = app.curCpuTime;
13426 }
13427
13428 app.setRawAdj = app.curRawAdj;
13429 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013430
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013431 if (app.curAdj != app.setAdj) {
13432 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013433 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013434 TAG, "Set " + app.pid + " " + app.processName +
13435 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013436 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013437 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013438 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013439 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013440 }
13441 }
13442 if (app.setSchedGroup != app.curSchedGroup) {
13443 app.setSchedGroup = app.curSchedGroup;
13444 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13445 "Setting process group of " + app.processName
13446 + " to " + app.curSchedGroup);
13447 if (app.waitingToKill != null &&
13448 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13449 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013450 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013451 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013452 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013453 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013454 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013455 } else {
13456 if (true) {
13457 long oldId = Binder.clearCallingIdentity();
13458 try {
13459 Process.setProcessGroup(app.pid, app.curSchedGroup);
13460 } catch (Exception e) {
13461 Slog.w(TAG, "Failed setting process group of " + app.pid
13462 + " to " + app.curSchedGroup);
13463 e.printStackTrace();
13464 } finally {
13465 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013466 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013467 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013468 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013469 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013470 app.thread.setSchedulingGroup(app.curSchedGroup);
13471 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013472 }
13473 }
13474 }
13475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013476 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013477 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013478 }
13479
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013480 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013481 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013483 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013485 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013486 }
13487 }
13488 return resumedActivity;
13489 }
13490
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013491 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013492 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013493 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13494 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013495 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13496 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013497
13498 mAdjSeq++;
13499
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013500 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13501 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13503 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013504 if (nowHidden != wasHidden) {
13505 // Changed to/from hidden state, so apps after it in the LRU
13506 // list may also be changed.
13507 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013508 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013509 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013510 }
13511
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013512 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013513 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013515 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516
13517 if (false) {
13518 RuntimeException e = new RuntimeException();
13519 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013520 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 }
13522
13523 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013524 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013526 final int emptyProcessLimit;
13527 final int hiddenProcessLimit;
13528 if (mProcessLimit <= 0) {
13529 emptyProcessLimit = hiddenProcessLimit = 0;
13530 } else if (mProcessLimit == 1) {
13531 emptyProcessLimit = 1;
13532 hiddenProcessLimit = 0;
13533 } else {
13534 emptyProcessLimit = (mProcessLimit*2)/3;
13535 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13536 }
13537
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013538 // Let's determine how many processes we have running vs.
13539 // how many slots we have for background processes; we may want
13540 // to put multiple processes in a slot of there are enough of
13541 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013542 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13543 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013544 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13545 if (numEmptyProcs > hiddenProcessLimit) {
13546 // If there are more empty processes than our limit on hidden
13547 // processes, then use the hidden process limit for the factor.
13548 // This ensures that the really old empty processes get pushed
13549 // down to the bottom, so if we are running low on memory we will
13550 // have a better chance at keeping around more hidden processes
13551 // instead of a gazillion empty processes.
13552 numEmptyProcs = hiddenProcessLimit;
13553 }
13554 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013555 if (emptyFactor < 1) emptyFactor = 1;
13556 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13557 if (hiddenFactor < 1) hiddenFactor = 1;
13558 int stepHidden = 0;
13559 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013560 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013561 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013562 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013563
13564 mNumNonHiddenProcs = 0;
13565 mNumHiddenProcs = 0;
13566
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013567 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013568 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013569 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013570 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013571 int nextHiddenAdj = curHiddenAdj+1;
13572 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13573 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013574 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013575 while (i > 0) {
13576 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013577 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013578 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013579 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013580 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013581 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13582 // This process was assigned as a hidden process... step the
13583 // hidden level.
13584 mNumHiddenProcs++;
13585 if (curHiddenAdj != nextHiddenAdj) {
13586 stepHidden++;
13587 if (stepHidden >= hiddenFactor) {
13588 stepHidden = 0;
13589 curHiddenAdj = nextHiddenAdj;
13590 nextHiddenAdj += 2;
13591 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13592 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13593 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013594 if (curClientHiddenAdj <= curHiddenAdj) {
13595 curClientHiddenAdj = curHiddenAdj + 1;
13596 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13597 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13598 }
13599 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013600 }
13601 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013602 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013603 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013604 Slog.i(TAG, "No longer want " + app.processName
13605 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013606 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013607 app.processName, app.setAdj, "too many background");
13608 app.killedBackground = true;
13609 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013610 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013611 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13612 // This process has a client that has activities. We will have
13613 // given it the current hidden adj; here we will just leave it
13614 // without stepping the hidden adj.
13615 curClientHiddenAdj++;
13616 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13617 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13618 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013619 } else {
13620 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13621 // This process was assigned as an empty process... step the
13622 // empty level.
13623 if (curEmptyAdj != nextEmptyAdj) {
13624 stepEmpty++;
13625 if (stepEmpty >= emptyFactor) {
13626 stepEmpty = 0;
13627 curEmptyAdj = nextEmptyAdj;
13628 nextEmptyAdj += 2;
13629 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13630 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13631 }
13632 }
13633 }
13634 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13635 mNumNonHiddenProcs++;
13636 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013637 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13638 && !app.hasClientActivities) {
13639 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13640 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013641 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013642 + " (pid " + app.pid + "): empty for "
13643 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13644 / 1000) + "s");
13645 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13646 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013647 app.killedBackground = true;
13648 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013649 } else {
13650 numEmpty++;
13651 if (numEmpty > emptyProcessLimit) {
13652 Slog.i(TAG, "No longer want " + app.processName
13653 + " (pid " + app.pid + "): empty #" + numEmpty);
13654 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13655 app.processName, app.setAdj, "too many background");
13656 app.killedBackground = true;
13657 Process.killProcessQuiet(app.pid);
13658 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013659 }
13660 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013661 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013662 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013663 // If this is an isolated process, and there are no
13664 // services running in it, then the process is no longer
13665 // needed. We agressively kill these because we can by
13666 // definition not re-use the same process again, and it is
13667 // good to avoid having whatever code was running in them
13668 // left sitting around after no longer needed.
13669 Slog.i(TAG, "Isolated process " + app.processName
13670 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013671 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013672 app.processName, app.setAdj, "isolated not needed");
13673 app.killedBackground = true;
13674 Process.killProcessQuiet(app.pid);
13675 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013676 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13677 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13678 && !app.killedBackground) {
13679 numTrimming++;
13680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013681 }
13682 }
13683
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013684 mNumServiceProcs = mNewNumServiceProcs;
13685
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013686 // Now determine the memory trimming level of background processes.
13687 // Unfortunately we need to start at the back of the list to do this
13688 // properly. We only do this if the number of background apps we
13689 // are managing to keep around is less than half the maximum we desire;
13690 // if we are keeping a good number around, we'll let them use whatever
13691 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013692 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13693 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013694 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013695 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013696 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013697 int minFactor = 2;
13698 if (mHomeProcess != null) minFactor++;
13699 if (mPreviousProcess != null) minFactor++;
13700 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013701 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013702 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013703 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013704 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013705 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013706 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13707 } else {
13708 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13709 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013710 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013711 for (i=0; i<N; i++) {
13712 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013713 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13714 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013715 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013716 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13717 try {
13718 app.thread.scheduleTrimMemory(curLevel);
13719 } catch (RemoteException e) {
13720 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013721 if (false) {
13722 // For now we won't do this; our memory trimming seems
13723 // to be good enough at this point that destroying
13724 // activities causes more harm than good.
13725 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13726 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013727 // Need to do this on its own message because the stack may not
13728 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013729 // For these apps we will also finish their activities
13730 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013731 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013732 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013733 }
13734 }
13735 app.trimMemoryLevel = curLevel;
13736 step++;
13737 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013738 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013739 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013740 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13741 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013742 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013743 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13744 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013745 break;
13746 }
13747 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013748 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013749 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013750 && app.thread != null) {
13751 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013752 app.thread.scheduleTrimMemory(
13753 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013754 } catch (RemoteException e) {
13755 }
13756 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013757 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013758 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013759 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013760 && app.pendingUiClean) {
13761 // If this application is now in the background and it
13762 // had done UI, then give it the special trim level to
13763 // have it free UI resources.
13764 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13765 if (app.trimMemoryLevel < level && app.thread != null) {
13766 try {
13767 app.thread.scheduleTrimMemory(level);
13768 } catch (RemoteException e) {
13769 }
13770 }
13771 app.pendingUiClean = false;
13772 }
13773 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013774 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013775 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013776 } catch (RemoteException e) {
13777 }
13778 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013779 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013780 }
13781 }
13782 } else {
13783 final int N = mLruProcesses.size();
13784 for (i=0; i<N; i++) {
13785 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013786 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013787 && app.pendingUiClean) {
13788 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13789 && app.thread != null) {
13790 try {
13791 app.thread.scheduleTrimMemory(
13792 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13793 } catch (RemoteException e) {
13794 }
13795 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013796 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013797 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013798 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013799 }
13800 }
13801
13802 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013803 // Need to do this on its own message because the stack may not
13804 // be in a consistent state at this point.
13805 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013807 }
13808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013809 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013810 synchronized (this) {
13811 int i;
13812
13813 // First remove any unused application processes whose package
13814 // has been removed.
13815 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13816 final ProcessRecord app = mRemovedProcesses.get(i);
13817 if (app.activities.size() == 0
13818 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013819 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 TAG, "Exiting empty application process "
13821 + app.processName + " ("
13822 + (app.thread != null ? app.thread.asBinder() : null)
13823 + ")\n");
13824 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013825 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013826 app.processName, app.setAdj, "empty");
13827 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013828 } else {
13829 try {
13830 app.thread.scheduleExit();
13831 } catch (Exception e) {
13832 // Ignore exceptions.
13833 }
13834 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013835 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013836 mRemovedProcesses.remove(i);
13837
13838 if (app.persistent) {
13839 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013840 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013841 }
13842 }
13843 }
13844 }
13845
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013846 // Now update the oom adj for all processes.
13847 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013848 }
13849 }
13850
13851 /** This method sends the specified signal to each of the persistent apps */
13852 public void signalPersistentProcesses(int sig) throws RemoteException {
13853 if (sig != Process.SIGNAL_USR1) {
13854 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13855 }
13856
13857 synchronized (this) {
13858 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13859 != PackageManager.PERMISSION_GRANTED) {
13860 throw new SecurityException("Requires permission "
13861 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13862 }
13863
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013864 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13865 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013866 if (r.thread != null && r.persistent) {
13867 Process.sendSignal(r.pid, sig);
13868 }
13869 }
13870 }
13871 }
13872
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013873 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13874 if (proc == null || proc == mProfileProc) {
13875 proc = mProfileProc;
13876 path = mProfileFile;
13877 profileType = mProfileType;
13878 clearProfilerLocked();
13879 }
13880 if (proc == null) {
13881 return;
13882 }
13883 try {
13884 proc.thread.profilerControl(false, path, null, profileType);
13885 } catch (RemoteException e) {
13886 throw new IllegalStateException("Process disappeared");
13887 }
13888 }
13889
13890 private void clearProfilerLocked() {
13891 if (mProfileFd != null) {
13892 try {
13893 mProfileFd.close();
13894 } catch (IOException e) {
13895 }
13896 }
13897 mProfileApp = null;
13898 mProfileProc = null;
13899 mProfileFile = null;
13900 mProfileType = 0;
13901 mAutoStopProfiler = false;
13902 }
13903
Dianne Hackborn1676c852012-09-10 14:52:30 -070013904 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013905 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013906
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013907 try {
13908 synchronized (this) {
13909 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13910 // its own permission.
13911 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13912 != PackageManager.PERMISSION_GRANTED) {
13913 throw new SecurityException("Requires permission "
13914 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013915 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013916
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013917 if (start && fd == null) {
13918 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013919 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013920
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013921 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013922 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013923 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013924 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013925
13926 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013927 throw new IllegalArgumentException("Unknown process: " + process);
13928 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013929
13930 if (start) {
13931 stopProfilerLocked(null, null, 0);
13932 setProfileApp(proc.info, proc.processName, path, fd, false);
13933 mProfileProc = proc;
13934 mProfileType = profileType;
13935 try {
13936 fd = fd.dup();
13937 } catch (IOException e) {
13938 fd = null;
13939 }
13940 proc.thread.profilerControl(start, path, fd, profileType);
13941 fd = null;
13942 mProfileFd = null;
13943 } else {
13944 stopProfilerLocked(proc, path, profileType);
13945 if (fd != null) {
13946 try {
13947 fd.close();
13948 } catch (IOException e) {
13949 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013950 }
13951 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013952
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013953 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013954 }
13955 } catch (RemoteException e) {
13956 throw new IllegalStateException("Process disappeared");
13957 } finally {
13958 if (fd != null) {
13959 try {
13960 fd.close();
13961 } catch (IOException e) {
13962 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013963 }
13964 }
13965 }
Andy McFadden824c5102010-07-09 16:26:57 -070013966
Dianne Hackborn1676c852012-09-10 14:52:30 -070013967 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013968 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013969 userId, true, true, callName, null);
13970 ProcessRecord proc = null;
13971 try {
13972 int pid = Integer.parseInt(process);
13973 synchronized (mPidsSelfLocked) {
13974 proc = mPidsSelfLocked.get(pid);
13975 }
13976 } catch (NumberFormatException e) {
13977 }
13978
13979 if (proc == null) {
13980 HashMap<String, SparseArray<ProcessRecord>> all
13981 = mProcessNames.getMap();
13982 SparseArray<ProcessRecord> procs = all.get(process);
13983 if (procs != null && procs.size() > 0) {
13984 proc = procs.valueAt(0);
13985 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13986 for (int i=1; i<procs.size(); i++) {
13987 ProcessRecord thisProc = procs.valueAt(i);
13988 if (thisProc.userId == userId) {
13989 proc = thisProc;
13990 break;
13991 }
13992 }
13993 }
13994 }
13995 }
13996
13997 return proc;
13998 }
13999
14000 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014001 String path, ParcelFileDescriptor fd) throws RemoteException {
14002
14003 try {
14004 synchronized (this) {
14005 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14006 // its own permission (same as profileControl).
14007 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14008 != PackageManager.PERMISSION_GRANTED) {
14009 throw new SecurityException("Requires permission "
14010 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14011 }
14012
14013 if (fd == null) {
14014 throw new IllegalArgumentException("null fd");
14015 }
14016
Dianne Hackborn1676c852012-09-10 14:52:30 -070014017 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014018 if (proc == null || proc.thread == null) {
14019 throw new IllegalArgumentException("Unknown process: " + process);
14020 }
14021
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014022 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14023 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014024 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14025 throw new SecurityException("Process not debuggable: " + proc);
14026 }
14027 }
14028
14029 proc.thread.dumpHeap(managed, path, fd);
14030 fd = null;
14031 return true;
14032 }
14033 } catch (RemoteException e) {
14034 throw new IllegalStateException("Process disappeared");
14035 } finally {
14036 if (fd != null) {
14037 try {
14038 fd.close();
14039 } catch (IOException e) {
14040 }
14041 }
14042 }
14043 }
14044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014045 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14046 public void monitor() {
14047 synchronized (this) { }
14048 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014049
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014050 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014051 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14052 ProcessRecord processRecord = mLruProcesses.get(i);
14053 try {
14054 if (processRecord.thread != null) {
14055 processRecord.thread.setCoreSettings(settings);
14056 }
14057 } catch (RemoteException re) {
14058 /* ignore */
14059 }
14060 }
14061 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014062
14063 // Multi-user methods
14064
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014065 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014066 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014067 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14068 != PackageManager.PERMISSION_GRANTED) {
14069 String msg = "Permission Denial: switchUser() from pid="
14070 + Binder.getCallingPid()
14071 + ", uid=" + Binder.getCallingUid()
14072 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14073 Slog.w(TAG, msg);
14074 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014075 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014076
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014077 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014078 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014079 synchronized (this) {
14080 final int oldUserId = mCurrentUserId;
14081 if (oldUserId == userId) {
14082 return true;
14083 }
14084
14085 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14086 if (userInfo == null) {
14087 Slog.w(TAG, "No user info for user #" + userId);
14088 return false;
14089 }
14090
14091 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14092 R.anim.screen_user_enter);
14093
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014094 boolean needStart = false;
14095
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014096 // If the user we are switching to is not currently started, then
14097 // we need to start it now.
14098 if (mStartedUsers.get(userId) == null) {
14099 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014100 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014101 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014102 }
14103
14104 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014105 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014106 final Integer userIdInt = Integer.valueOf(userId);
14107 mUserLru.remove(userIdInt);
14108 mUserLru.add(userIdInt);
14109
Craig Mautnerf1b67412012-09-19 13:18:29 -070014110 mWindowManager.setCurrentUser(userId);
14111
Adam Cohenf7522022012-10-03 20:03:18 -070014112 // Once the internal notion of the active user has switched, we lock the device
14113 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014114 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014115
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014116 final UserStartedState uss = mStartedUsers.get(userId);
14117
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014118 // Make sure user is in the started state. If it is currently
14119 // stopping, we need to knock that off.
14120 if (uss.mState == UserStartedState.STATE_STOPPING) {
14121 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14122 // so we can just fairly silently bring the user back from
14123 // the almost-dead.
14124 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014125 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014126 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014127 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14128 // This means ACTION_SHUTDOWN has been sent, so we will
14129 // need to treat this as a new boot of the user.
14130 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014131 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014132 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014133 }
14134
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014135 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14136 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14137 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14138 oldUserId, userId, uss));
14139 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14140 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014141 if (needStart) {
14142 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14143 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14144 | Intent.FLAG_RECEIVER_FOREGROUND);
14145 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14146 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014147 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014148 false, false, MY_PID, Process.SYSTEM_UID, userId);
14149 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014150
14151 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14152 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014153 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014154 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014155 broadcastIntentLocked(null, null, intent, null,
14156 new IIntentReceiver.Stub() {
14157 public void performReceive(Intent intent, int resultCode,
14158 String data, Bundle extras, boolean ordered,
14159 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014160 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014161 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014162 }, 0, null, null, null, AppOpsManager.OP_NONE,
14163 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014164 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014165 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014166 } else {
14167 getUserManagerLocked().makeInitialized(userInfo.id);
14168 }
14169 }
14170
14171 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14172 if (!haveActivities) {
14173 startHomeActivityLocked(userId);
14174 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014175
Jeff Sharkey86597df2012-11-09 15:00:31 -080014176 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014177 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014178 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014179 if (needStart) {
14180 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14181 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14182 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14183 broadcastIntentLocked(null, null, intent,
14184 null, new IIntentReceiver.Stub() {
14185 @Override
14186 public void performReceive(Intent intent, int resultCode, String data,
14187 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14188 throws RemoteException {
14189 }
14190 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014191 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014192 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014193 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014194 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014195 } finally {
14196 Binder.restoreCallingIdentity(ident);
14197 }
Amith Yamasani13593602012-03-22 16:16:17 -070014198
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014199 return true;
14200 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014201
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014202 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14203 long ident = Binder.clearCallingIdentity();
14204 try {
14205 Intent intent;
14206 if (oldUserId >= 0) {
14207 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014208 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14209 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014210 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14211 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014212 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014213 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14214 }
14215 if (newUserId >= 0) {
14216 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14218 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014219 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14220 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014221 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014222 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14223 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014224 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14225 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014226 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14227 broadcastIntentLocked(null, null, intent,
14228 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014229 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014230 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14231 }
14232 } finally {
14233 Binder.restoreCallingIdentity(ident);
14234 }
14235 }
14236
14237 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14238 final int newUserId) {
14239 final int N = mUserSwitchObservers.beginBroadcast();
14240 if (N > 0) {
14241 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14242 int mCount = 0;
14243 @Override
14244 public void sendResult(Bundle data) throws RemoteException {
14245 synchronized (ActivityManagerService.this) {
14246 if (mCurUserSwitchCallback == this) {
14247 mCount++;
14248 if (mCount == N) {
14249 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14250 }
14251 }
14252 }
14253 }
14254 };
14255 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014256 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014257 mCurUserSwitchCallback = callback;
14258 }
14259 for (int i=0; i<N; i++) {
14260 try {
14261 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14262 newUserId, callback);
14263 } catch (RemoteException e) {
14264 }
14265 }
14266 } else {
14267 synchronized (this) {
14268 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14269 }
14270 }
14271 mUserSwitchObservers.finishBroadcast();
14272 }
14273
14274 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14275 synchronized (this) {
14276 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14277 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14278 }
14279 }
14280
14281 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14282 mCurUserSwitchCallback = null;
14283 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14284 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14285 oldUserId, newUserId, uss));
14286 }
14287
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014288 void userInitialized(UserStartedState uss, int newUserId) {
14289 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014290 }
14291
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014292 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014293 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014294 }
14295
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014296 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14297 boolean clearInitializing, boolean clearSwitching) {
14298 boolean unfrozen = false;
14299 synchronized (this) {
14300 if (clearInitializing) {
14301 uss.initializing = false;
14302 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14303 }
14304 if (clearSwitching) {
14305 uss.switching = false;
14306 }
14307 if (!uss.switching && !uss.initializing) {
14308 mWindowManager.stopFreezingScreen();
14309 unfrozen = true;
14310 }
14311 }
14312 if (unfrozen) {
14313 final int N = mUserSwitchObservers.beginBroadcast();
14314 for (int i=0; i<N; i++) {
14315 try {
14316 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14317 } catch (RemoteException e) {
14318 }
14319 }
14320 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014321 }
14322 }
14323
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014324 void finishUserSwitch(UserStartedState uss) {
14325 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014326 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014327 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14328 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014329 final int userId = uss.mHandle.getIdentifier();
14330 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14331 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14332 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014333 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014334 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014335 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014336 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014337 int num = mUserLru.size();
14338 int i = 0;
14339 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14340 Integer oldUserId = mUserLru.get(i);
14341 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14342 if (oldUss == null) {
14343 // Shouldn't happen, but be sane if it does.
14344 mUserLru.remove(i);
14345 num--;
14346 continue;
14347 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014348 if (oldUss.mState == UserStartedState.STATE_STOPPING
14349 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014350 // This user is already stopping, doesn't count.
14351 num--;
14352 i++;
14353 continue;
14354 }
14355 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14356 // Owner and current can't be stopped, but count as running.
14357 i++;
14358 continue;
14359 }
14360 // This is a user to be stopped.
14361 stopUserLocked(oldUserId, null);
14362 num--;
14363 i++;
14364 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014365 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014366 }
14367
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014368 @Override
14369 public int stopUser(final int userId, final IStopUserCallback callback) {
14370 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14371 != PackageManager.PERMISSION_GRANTED) {
14372 String msg = "Permission Denial: switchUser() from pid="
14373 + Binder.getCallingPid()
14374 + ", uid=" + Binder.getCallingUid()
14375 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14376 Slog.w(TAG, msg);
14377 throw new SecurityException(msg);
14378 }
14379 if (userId <= 0) {
14380 throw new IllegalArgumentException("Can't stop primary user " + userId);
14381 }
Amith Yamasani13593602012-03-22 16:16:17 -070014382 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014383 return stopUserLocked(userId, callback);
14384 }
14385 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014386
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014387 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14388 if (mCurrentUserId == userId) {
14389 return ActivityManager.USER_OP_IS_CURRENT;
14390 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014391
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014392 final UserStartedState uss = mStartedUsers.get(userId);
14393 if (uss == null) {
14394 // User is not started, nothing to do... but we do need to
14395 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014396 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014397 mHandler.post(new Runnable() {
14398 @Override
14399 public void run() {
14400 try {
14401 callback.userStopped(userId);
14402 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014403 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014404 }
14405 });
14406 }
14407 return ActivityManager.USER_OP_SUCCESS;
14408 }
14409
14410 if (callback != null) {
14411 uss.mStopCallbacks.add(callback);
14412 }
14413
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014414 if (uss.mState != UserStartedState.STATE_STOPPING
14415 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014416 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014417 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014418
14419 long ident = Binder.clearCallingIdentity();
14420 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014421 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014422 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014423 // stop the user.
14424 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14425 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14426 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14427 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14428 // This is the result receiver for the final shutdown broadcast.
14429 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014430 @Override
14431 public void performReceive(Intent intent, int resultCode, String data,
14432 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14433 finishUserStop(uss);
14434 }
14435 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014436 // This is the result receiver for the initial stopping broadcast.
14437 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14438 @Override
14439 public void performReceive(Intent intent, int resultCode, String data,
14440 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14441 // On to the next.
14442 synchronized (ActivityManagerService.this) {
14443 if (uss.mState != UserStartedState.STATE_STOPPING) {
14444 // Whoops, we are being started back up. Abort, abort!
14445 return;
14446 }
14447 uss.mState = UserStartedState.STATE_SHUTDOWN;
14448 }
14449 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014450 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014451 true, false, MY_PID, Process.SYSTEM_UID, userId);
14452 }
14453 };
14454 // Kick things off.
14455 broadcastIntentLocked(null, null, stoppingIntent,
14456 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014457 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014458 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014459 } finally {
14460 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014461 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014462 }
Amith Yamasani13593602012-03-22 16:16:17 -070014463
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014464 return ActivityManager.USER_OP_SUCCESS;
14465 }
14466
14467 void finishUserStop(UserStartedState uss) {
14468 final int userId = uss.mHandle.getIdentifier();
14469 boolean stopped;
14470 ArrayList<IStopUserCallback> callbacks;
14471 synchronized (this) {
14472 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014473 if (mStartedUsers.get(userId) != uss) {
14474 stopped = false;
14475 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014476 stopped = false;
14477 } else {
14478 stopped = true;
14479 // User can no longer run.
14480 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014481 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014482 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014483
14484 // Clean up all state and processes associated with the user.
14485 // Kill all the processes for the user.
14486 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014487 }
14488 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014489
14490 for (int i=0; i<callbacks.size(); i++) {
14491 try {
14492 if (stopped) callbacks.get(i).userStopped(userId);
14493 else callbacks.get(i).userStopAborted(userId);
14494 } catch (RemoteException e) {
14495 }
14496 }
14497 }
14498
14499 @Override
14500 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014501 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14502 != PackageManager.PERMISSION_GRANTED) && (
14503 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14504 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014505 String msg = "Permission Denial: getCurrentUser() from pid="
14506 + Binder.getCallingPid()
14507 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014508 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014509 Slog.w(TAG, msg);
14510 throw new SecurityException(msg);
14511 }
14512 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014513 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014514 }
Amith Yamasani13593602012-03-22 16:16:17 -070014515 }
14516
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014517 int getCurrentUserIdLocked() {
14518 return mCurrentUserId;
14519 }
14520
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014521 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014522 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014523 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14524 != PackageManager.PERMISSION_GRANTED) {
14525 String msg = "Permission Denial: isUserRunning() from pid="
14526 + Binder.getCallingPid()
14527 + ", uid=" + Binder.getCallingUid()
14528 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14529 Slog.w(TAG, msg);
14530 throw new SecurityException(msg);
14531 }
14532 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014533 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014534 }
14535 }
14536
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014537 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014538 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014539 if (state == null) {
14540 return false;
14541 }
14542 if (orStopped) {
14543 return true;
14544 }
14545 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014546 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014547 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014548
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014549 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014550 public int[] getRunningUserIds() {
14551 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14552 != PackageManager.PERMISSION_GRANTED) {
14553 String msg = "Permission Denial: isUserRunning() from pid="
14554 + Binder.getCallingPid()
14555 + ", uid=" + Binder.getCallingUid()
14556 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14557 Slog.w(TAG, msg);
14558 throw new SecurityException(msg);
14559 }
14560 synchronized (this) {
14561 return mStartedUserArray;
14562 }
14563 }
14564
14565 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014566 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014567 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014568 UserStartedState uss = mStartedUsers.valueAt(i);
14569 // This list does not include stopping users.
14570 if (uss.mState != UserStartedState.STATE_STOPPING
14571 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14572 num++;
14573 }
14574 }
14575 mStartedUserArray = new int[num];
14576 num = 0;
14577 for (int i=0; i<mStartedUsers.size(); i++) {
14578 UserStartedState uss = mStartedUsers.valueAt(i);
14579 if (uss.mState != UserStartedState.STATE_STOPPING
14580 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14581 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14582 num++;
14583 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014584 }
14585 }
14586
14587 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014588 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14589 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14590 != PackageManager.PERMISSION_GRANTED) {
14591 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14592 + Binder.getCallingPid()
14593 + ", uid=" + Binder.getCallingUid()
14594 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14595 Slog.w(TAG, msg);
14596 throw new SecurityException(msg);
14597 }
14598
14599 mUserSwitchObservers.register(observer);
14600 }
14601
14602 @Override
14603 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14604 mUserSwitchObservers.unregister(observer);
14605 }
14606
Dianne Hackborn1676c852012-09-10 14:52:30 -070014607 private boolean userExists(int userId) {
14608 if (userId == 0) {
14609 return true;
14610 }
14611 UserManagerService ums = getUserManagerLocked();
14612 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14613 }
14614
14615 int[] getUsersLocked() {
14616 UserManagerService ums = getUserManagerLocked();
14617 return ums != null ? ums.getUserIds() : new int[] { 0 };
14618 }
14619
14620 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014621 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014622 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14623 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014624 }
14625 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014626 }
14627
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014628 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014629 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014630
14631 throw new SecurityException("Caller uid=" + uid
14632 + " is not privileged to communicate with user=" + userId);
14633 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014634
14635 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014636 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014637 }
14638
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014639 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014640 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014641 ApplicationInfo newInfo = new ApplicationInfo(info);
14642 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014643 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14644 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014645 return newInfo;
14646 }
14647
14648 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014649 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014650 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014651 return aInfo;
14652 }
14653
14654 ActivityInfo info = new ActivityInfo(aInfo);
14655 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14656 return info;
14657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014658}