blob: f62c3d3e3b7e3bd00014900d1ebfda4f4fa2b8cb [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) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002841 mMainStack.finishActivityLocked(r, Activity.RESULT_CANCELED,
2842 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002843 }
2844 }
2845
Dianne Hackborn41203752012-08-31 14:05:51 -07002846 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2847 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002848 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002849 }
2850 }
2851
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002852 public void crashApplication(int uid, int initialPid, String packageName,
2853 String message) {
2854 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2855 != PackageManager.PERMISSION_GRANTED) {
2856 String msg = "Permission Denial: crashApplication() from pid="
2857 + Binder.getCallingPid()
2858 + ", uid=" + Binder.getCallingUid()
2859 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2860 Slog.w(TAG, msg);
2861 throw new SecurityException(msg);
2862 }
2863
2864 synchronized(this) {
2865 ProcessRecord proc = null;
2866
2867 // Figure out which process to kill. We don't trust that initialPid
2868 // still has any relation to current pids, so must scan through the
2869 // list.
2870 synchronized (mPidsSelfLocked) {
2871 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2872 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002873 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002874 continue;
2875 }
2876 if (p.pid == initialPid) {
2877 proc = p;
2878 break;
2879 }
2880 for (String str : p.pkgList) {
2881 if (str.equals(packageName)) {
2882 proc = p;
2883 }
2884 }
2885 }
2886 }
2887
2888 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002889 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002890 + " initialPid=" + initialPid
2891 + " packageName=" + packageName);
2892 return;
2893 }
2894
2895 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002896 if (proc.pid == Process.myPid()) {
2897 Log.w(TAG, "crashApplication: trying to crash self!");
2898 return;
2899 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002900 long ident = Binder.clearCallingIdentity();
2901 try {
2902 proc.thread.scheduleCrash(message);
2903 } catch (RemoteException e) {
2904 }
2905 Binder.restoreCallingIdentity(ident);
2906 }
2907 }
2908 }
2909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 public final void finishSubActivity(IBinder token, String resultWho,
2911 int requestCode) {
2912 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002914 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 Binder.restoreCallingIdentity(origId);
2916 }
2917 }
2918
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002919 public boolean finishActivityAffinity(IBinder token) {
2920 synchronized(this) {
2921 final long origId = Binder.clearCallingIdentity();
2922 boolean res = mMainStack.finishActivityAffinityLocked(token);
2923 Binder.restoreCallingIdentity(origId);
2924 return res;
2925 }
2926 }
2927
Craig Mautnercae015f2013-02-08 14:31:27 -08002928 @Override
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002929 public boolean willActivityBeVisible(IBinder token) {
2930 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08002931 return mMainStack.willActivityBeVisibleLocked(token);
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002932 }
2933 }
Craig Mautnercae015f2013-02-08 14:31:27 -08002934
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002935 public void overridePendingTransition(IBinder token, String packageName,
2936 int enterAnim, int exitAnim) {
2937 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002938 ActivityRecord self = mMainStack.isInStackLocked(token);
2939 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002940 return;
2941 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002942
2943 final long origId = Binder.clearCallingIdentity();
2944
2945 if (self.state == ActivityState.RESUMED
2946 || self.state == ActivityState.PAUSING) {
2947 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002948 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002949 }
2950
2951 Binder.restoreCallingIdentity(origId);
2952 }
2953 }
2954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 * Main function for removing an existing process from the activity manager
2957 * as a result of that process going away. Clears out all connections
2958 * to the process.
2959 */
2960 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002961 boolean restarting, boolean allowRestart) {
2962 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002964 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 }
2966
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002967 if (mProfileProc == app) {
2968 clearProfilerLocked();
2969 }
2970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002972 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002973 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2974 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002975 mMainStack.mPausingActivity = null;
2976 }
2977 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2978 mMainStack.mLastPausedActivity = null;
2979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980
2981 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002982 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983
2984 app.activities.clear();
2985
2986 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002987 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 + " running instrumentation " + app.instrumentationClass);
2989 Bundle info = new Bundle();
2990 info.putString("shortMsg", "Process crashed.");
2991 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2992 }
2993
2994 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002995 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 // If there was nothing to resume, and we are not already
2997 // restarting this process, but there is a visible activity that
2998 // is hosted by the process... then make sure all visible
2999 // activities are running, taking care of restarting this
3000 // process.
3001 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003002 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004 }
3005 }
3006 }
3007
3008 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3009 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003011 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3012 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3014 return i;
3015 }
3016 }
3017 return -1;
3018 }
3019
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003020 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 IApplicationThread thread) {
3022 if (thread == null) {
3023 return null;
3024 }
3025
3026 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003027 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 }
3029
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003030 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 IApplicationThread thread) {
3032
3033 mProcDeaths[0]++;
3034
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003035 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3036 synchronized (stats) {
3037 stats.noteProcessDiedLocked(app.info.uid, pid);
3038 }
3039
Magnus Edlund7bb25812010-02-24 15:45:06 +01003040 // Clean up already done if the process has been re-started.
3041 if (app.pid == pid && app.thread != null &&
3042 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003043 if (!app.killedBackground) {
3044 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3045 + ") has died.");
3046 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003047 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003048 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 TAG, "Dying app: " + app + ", pid: " + pid
3050 + ", thread: " + thread.asBinder());
3051 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003052 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053
3054 if (doLowMem) {
3055 // If there are no longer any background processes running,
3056 // and the app that died was not running instrumentation,
3057 // then tell everyone we are now low on memory.
3058 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003059 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3060 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003061 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 haveBg = true;
3063 break;
3064 }
3065 }
3066
3067 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003068 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003069 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003070 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3071 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003072 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003073 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3074 // The low memory report is overriding any current
3075 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003076 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003077 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003078 rec.lastRequestedGc = 0;
3079 } else {
3080 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003082 rec.reportLowMemory = true;
3083 rec.lastLowMemory = now;
3084 mProcessesToGc.remove(rec);
3085 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 }
3087 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003088 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003089 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 }
3091 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003092 } else if (app.pid != pid) {
3093 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003094 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003095 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003096 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003097 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003098 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 + thread.asBinder());
3100 }
3101 }
3102
Dan Egnor42471dd2010-01-07 17:25:22 -08003103 /**
3104 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003105 * @param clearTraces causes the dump file to be erased prior to the new
3106 * traces being written, if true; when false, the new traces will be
3107 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003108 * @param firstPids of dalvik VM processes to dump stack traces for first
3109 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003110 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 * @return file containing stack traces, or null if no dump file is configured
3112 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003113 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003114 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003115 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3116 if (tracesPath == null || tracesPath.length() == 0) {
3117 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003119
3120 File tracesFile = new File(tracesPath);
3121 try {
3122 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003123 if (!tracesDir.exists()) {
3124 tracesFile.mkdirs();
3125 if (!SELinux.restorecon(tracesDir)) {
3126 return null;
3127 }
3128 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003129 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3130
Christopher Tate6ee412d2010-05-28 12:01:56 -07003131 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003132 tracesFile.createNewFile();
3133 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3134 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003135 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003136 return null;
3137 }
3138
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003139 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003140 return tracesFile;
3141 }
3142
3143 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003144 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003145 // Use a FileObserver to detect when traces finish writing.
3146 // The order of traces is considered important to maintain for legibility.
3147 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3148 public synchronized void onEvent(int event, String path) { notify(); }
3149 };
3150
3151 try {
3152 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003153
3154 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003155 if (firstPids != null) {
3156 try {
3157 int num = firstPids.size();
3158 for (int i = 0; i < num; i++) {
3159 synchronized (observer) {
3160 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3161 observer.wait(200); // Wait for write-close, give up after 200msec
3162 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003163 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003164 } catch (InterruptedException e) {
3165 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003166 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003167 }
3168
3169 // Next measure CPU usage.
3170 if (processStats != null) {
3171 processStats.init();
3172 System.gc();
3173 processStats.update();
3174 try {
3175 synchronized (processStats) {
3176 processStats.wait(500); // measure over 1/2 second.
3177 }
3178 } catch (InterruptedException e) {
3179 }
3180 processStats.update();
3181
3182 // We'll take the stack crawls of just the top apps using CPU.
3183 final int N = processStats.countWorkingStats();
3184 int numProcs = 0;
3185 for (int i=0; i<N && numProcs<5; i++) {
3186 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3187 if (lastPids.indexOfKey(stats.pid) >= 0) {
3188 numProcs++;
3189 try {
3190 synchronized (observer) {
3191 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3192 observer.wait(200); // Wait for write-close, give up after 200msec
3193 }
3194 } catch (InterruptedException e) {
3195 Log.wtf(TAG, e);
3196 }
3197
3198 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003199 }
3200 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003201
Dan Egnor42471dd2010-01-07 17:25:22 -08003202 } finally {
3203 observer.stopWatching();
3204 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003205
3206 if (nativeProcs != null) {
3207 int[] pids = Process.getPidsForCommands(nativeProcs);
3208 if (pids != null) {
3209 for (int pid : pids) {
3210 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3211 }
3212 }
3213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
3215
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003216 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003217 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003218 return;
3219 }
3220 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3221 if (tracesPath == null || tracesPath.length() == 0) {
3222 return;
3223 }
3224
3225 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3226 StrictMode.allowThreadDiskWrites();
3227 try {
3228 final File tracesFile = new File(tracesPath);
3229 final File tracesDir = tracesFile.getParentFile();
3230 final File tracesTmp = new File(tracesDir, "__tmp__");
3231 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003232 if (!tracesDir.exists()) {
3233 tracesFile.mkdirs();
3234 if (!SELinux.restorecon(tracesDir.getPath())) {
3235 return;
3236 }
3237 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003238 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3239
3240 if (tracesFile.exists()) {
3241 tracesTmp.delete();
3242 tracesFile.renameTo(tracesTmp);
3243 }
3244 StringBuilder sb = new StringBuilder();
3245 Time tobj = new Time();
3246 tobj.set(System.currentTimeMillis());
3247 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3248 sb.append(": ");
3249 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3250 sb.append(" since ");
3251 sb.append(msg);
3252 FileOutputStream fos = new FileOutputStream(tracesFile);
3253 fos.write(sb.toString().getBytes());
3254 if (app == null) {
3255 fos.write("\n*** No application process!".getBytes());
3256 }
3257 fos.close();
3258 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3259 } catch (IOException e) {
3260 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3261 return;
3262 }
3263
3264 if (app != null) {
3265 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3266 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003267 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003268 }
3269
3270 File lastTracesFile = null;
3271 File curTracesFile = null;
3272 for (int i=9; i>=0; i--) {
3273 String name = String.format("slow%02d.txt", i);
3274 curTracesFile = new File(tracesDir, name);
3275 if (curTracesFile.exists()) {
3276 if (lastTracesFile != null) {
3277 curTracesFile.renameTo(lastTracesFile);
3278 } else {
3279 curTracesFile.delete();
3280 }
3281 }
3282 lastTracesFile = curTracesFile;
3283 }
3284 tracesFile.renameTo(curTracesFile);
3285 if (tracesTmp.exists()) {
3286 tracesTmp.renameTo(tracesFile);
3287 }
3288 } finally {
3289 StrictMode.setThreadPolicy(oldPolicy);
3290 }
3291 }
3292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003293 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003294 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003295 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3296 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3297
Dianne Hackborn287952c2010-09-22 22:34:31 -07003298 if (mController != null) {
3299 try {
3300 // 0 == continue, -1 = kill process immediately
3301 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3302 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3303 } catch (RemoteException e) {
3304 mController = null;
3305 }
3306 }
3307
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003308 long anrTime = SystemClock.uptimeMillis();
3309 if (MONITOR_CPU_USAGE) {
3310 updateCpuStatsNow();
3311 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003312
3313 synchronized (this) {
3314 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3315 if (mShuttingDown) {
3316 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3317 return;
3318 } else if (app.notResponding) {
3319 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3320 return;
3321 } else if (app.crashing) {
3322 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3323 return;
3324 }
3325
3326 // In case we come through here for the same app before completing
3327 // this one, mark as anring now so we will bail out.
3328 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003329
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003330 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003331 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3332 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003333
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003334 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003335 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003336
3337 int parentPid = app.pid;
3338 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003339 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003340
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003341 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003342
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003343 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3344 ProcessRecord r = mLruProcesses.get(i);
3345 if (r != null && r.thread != null) {
3346 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003347 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3348 if (r.persistent) {
3349 firstPids.add(pid);
3350 } else {
3351 lastPids.put(pid, Boolean.TRUE);
3352 }
3353 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 }
3356 }
3357
Dan Egnor42471dd2010-01-07 17:25:22 -08003358 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003359 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003360 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003361 info.append("ANR in ").append(app.processName);
3362 if (activity != null && activity.shortComponentName != null) {
3363 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003364 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003365 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003367 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003369 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003370 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372
Dianne Hackborn287952c2010-09-22 22:34:31 -07003373 final ProcessStats processStats = new ProcessStats(true);
3374
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003375 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003376
Dan Egnor42471dd2010-01-07 17:25:22 -08003377 String cpuInfo = null;
3378 if (MONITOR_CPU_USAGE) {
3379 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003380 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003381 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003382 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003383 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003384 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 }
3386
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003387 info.append(processStats.printCurrentState(anrTime));
3388
Joe Onorato8a9b2202010-02-26 18:56:32 -08003389 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003390 if (tracesFile == null) {
3391 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3392 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3393 }
3394
Jeff Sharkeya353d262011-10-28 11:12:06 -07003395 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3396 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003397
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003398 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003400 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3401 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003403 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3404 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 }
3406 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003407 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 }
3409 }
3410
Dan Egnor42471dd2010-01-07 17:25:22 -08003411 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3412 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3413 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003414
3415 synchronized (this) {
3416 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003417 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003418 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003419 app.processName, app.setAdj, "background ANR");
3420 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003421 return;
3422 }
3423
3424 // Set the app's notResponding state, and look up the errorReportReceiver
3425 makeAppNotRespondingLocked(app,
3426 activity != null ? activity.shortComponentName : null,
3427 annotation != null ? "ANR " + annotation : "ANR",
3428 info.toString());
3429
3430 // Bring up the infamous App Not Responding dialog
3431 Message msg = Message.obtain();
3432 HashMap map = new HashMap();
3433 msg.what = SHOW_NOT_RESPONDING_MSG;
3434 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003435 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003436 map.put("app", app);
3437 if (activity != null) {
3438 map.put("activity", activity);
3439 }
3440
3441 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003445 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3446 if (!mLaunchWarningShown) {
3447 mLaunchWarningShown = true;
3448 mHandler.post(new Runnable() {
3449 @Override
3450 public void run() {
3451 synchronized (ActivityManagerService.this) {
3452 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3453 d.show();
3454 mHandler.postDelayed(new Runnable() {
3455 @Override
3456 public void run() {
3457 synchronized (ActivityManagerService.this) {
3458 d.dismiss();
3459 mLaunchWarningShown = false;
3460 }
3461 }
3462 }, 4000);
3463 }
3464 }
3465 });
3466 }
3467 }
3468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003470 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003471 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 int uid = Binder.getCallingUid();
3473 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003474 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003475 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 long callingId = Binder.clearCallingIdentity();
3477 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003478 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 int pkgUid = -1;
3480 synchronized(this) {
3481 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003482 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 } catch (RemoteException e) {
3484 }
3485 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003486 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 return false;
3488 }
3489 if (uid == pkgUid || checkComponentPermission(
3490 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003491 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003493 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 } else {
3495 throw new SecurityException(pid+" does not have permission:"+
3496 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3497 "for process:"+packageName);
3498 }
3499 }
3500
3501 try {
3502 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003503 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3505 Uri.fromParts("package", packageName, null));
3506 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003507 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003508 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 } catch (RemoteException e) {
3510 }
3511 } finally {
3512 Binder.restoreCallingIdentity(callingId);
3513 }
3514 return true;
3515 }
3516
Dianne Hackborn1676c852012-09-10 14:52:30 -07003517 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3519 != PackageManager.PERMISSION_GRANTED &&
3520 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3521 != PackageManager.PERMISSION_GRANTED) {
3522 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 + Binder.getCallingPid()
3524 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003525 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003526 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 throw new SecurityException(msg);
3528 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003529
Dianne Hackborn139748f2012-09-24 11:36:57 -07003530 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003531 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 long callingId = Binder.clearCallingIdentity();
3533 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003534 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003536 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003538 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 } catch (RemoteException e) {
3540 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003541 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003542 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 return;
3544 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003545 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003546 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3547 }
3548 } finally {
3549 Binder.restoreCallingIdentity(callingId);
3550 }
3551 }
3552
3553 public void killAllBackgroundProcesses() {
3554 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3555 != PackageManager.PERMISSION_GRANTED) {
3556 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3557 + Binder.getCallingPid()
3558 + ", uid=" + Binder.getCallingUid()
3559 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3560 Slog.w(TAG, msg);
3561 throw new SecurityException(msg);
3562 }
3563
3564 long callingId = Binder.clearCallingIdentity();
3565 try {
3566 synchronized(this) {
3567 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3568 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3569 final int NA = apps.size();
3570 for (int ia=0; ia<NA; ia++) {
3571 ProcessRecord app = apps.valueAt(ia);
3572 if (app.persistent) {
3573 // we don't kill persistent processes
3574 continue;
3575 }
3576 if (app.removed) {
3577 procs.add(app);
3578 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3579 app.removed = true;
3580 procs.add(app);
3581 }
3582 }
3583 }
3584
3585 int N = procs.size();
3586 for (int i=0; i<N; i++) {
3587 removeProcessLocked(procs.get(i), false, true, "kill all background");
3588 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003589 }
3590 } finally {
3591 Binder.restoreCallingIdentity(callingId);
3592 }
3593 }
3594
Dianne Hackborn1676c852012-09-10 14:52:30 -07003595 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003596 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3597 != PackageManager.PERMISSION_GRANTED) {
3598 String msg = "Permission Denial: forceStopPackage() from pid="
3599 + Binder.getCallingPid()
3600 + ", uid=" + Binder.getCallingUid()
3601 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003602 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003603 throw new SecurityException(msg);
3604 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003605 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003606 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003607 long callingId = Binder.clearCallingIdentity();
3608 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003609 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003610 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003611 int[] users = userId == UserHandle.USER_ALL
3612 ? getUsersLocked() : new int[] { userId };
3613 for (int user : users) {
3614 int pkgUid = -1;
3615 try {
3616 pkgUid = pm.getPackageUid(packageName, user);
3617 } catch (RemoteException e) {
3618 }
3619 if (pkgUid == -1) {
3620 Slog.w(TAG, "Invalid packageName: " + packageName);
3621 continue;
3622 }
3623 try {
3624 pm.setPackageStoppedState(packageName, true, user);
3625 } catch (RemoteException e) {
3626 } catch (IllegalArgumentException e) {
3627 Slog.w(TAG, "Failed trying to unstop package "
3628 + packageName + ": " + e);
3629 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003630 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003631 forceStopPackageLocked(packageName, pkgUid);
3632 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 }
3635 } finally {
3636 Binder.restoreCallingIdentity(callingId);
3637 }
3638 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003639
3640 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003641 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003642 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003643 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003644 if (pkg == null) {
3645 return;
3646 }
3647 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003648 if (appid < 0) {
3649 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003650 return;
3651 }
3652 int callerUid = Binder.getCallingUid();
3653 // Only the system server can kill an application
3654 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003655 // Post an aysnc message to kill the application
3656 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003657 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003658 msg.arg2 = 0;
3659 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003660 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003661 } else {
3662 throw new SecurityException(callerUid + " cannot kill pkg: " +
3663 pkg);
3664 }
3665 }
3666
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003667 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003668 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003669
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003670 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003671 final int uid = Binder.getCallingUid();
3672 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003673 try {
3674 synchronized (this) {
3675 // Only allow this from foreground processes, so that background
3676 // applications can't abuse it to prevent system UI from being shown.
3677 if (uid >= Process.FIRST_APPLICATION_UID) {
3678 ProcessRecord proc;
3679 synchronized (mPidsSelfLocked) {
3680 proc = mPidsSelfLocked.get(pid);
3681 }
3682 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3683 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3684 + " from background process " + proc);
3685 return;
3686 }
3687 }
3688 closeSystemDialogsLocked(reason);
3689 }
3690 } finally {
3691 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003692 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003693 }
3694
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003695 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003696 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3698 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003699 if (reason != null) {
3700 intent.putExtra("reason", reason);
3701 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003702 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003703
Craig Mautnercae015f2013-02-08 14:31:27 -08003704 mMainStack.closeSystemDialogsLocked();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003705
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003706 broadcastIntentLocked(null, null, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003707 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003708 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003709 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003710
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003711 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003712 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003713 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003714 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3715 for (int i=pids.length-1; i>=0; i--) {
3716 infos[i] = new Debug.MemoryInfo();
3717 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003718 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003719 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003720 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003721
Dianne Hackbornb437e092011-08-05 17:50:29 -07003722 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003723 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003724 long[] pss = new long[pids.length];
3725 for (int i=pids.length-1; i>=0; i--) {
3726 pss[i] = Debug.getPss(pids[i]);
3727 }
3728 return pss;
3729 }
3730
Christopher Tate5e1ab332009-09-01 20:32:49 -07003731 public void killApplicationProcess(String processName, int uid) {
3732 if (processName == null) {
3733 return;
3734 }
3735
3736 int callerUid = Binder.getCallingUid();
3737 // Only the system server can kill an application
3738 if (callerUid == Process.SYSTEM_UID) {
3739 synchronized (this) {
3740 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003741 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003742 try {
3743 app.thread.scheduleSuicide();
3744 } catch (RemoteException e) {
3745 // If the other end already died, then our work here is done.
3746 }
3747 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003748 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003749 + processName + " / " + uid);
3750 }
3751 }
3752 } else {
3753 throw new SecurityException(callerUid + " cannot kill app process: " +
3754 processName);
3755 }
3756 }
3757
Dianne Hackborn03abb812010-01-04 18:43:19 -08003758 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003759 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3760 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3762 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003763 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003764 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3765 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003768 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003770 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -07003771 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003772 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003774
3775 private void forceStopUserLocked(int userId) {
3776 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3777 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003778 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3779 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003780 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3781 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003782 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003783 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003784 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003785 }
3786
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003787 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003788 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3789 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003790 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791
Dianne Hackborn03abb812010-01-04 18:43:19 -08003792 // Remove all processes this package may have touched: all with the
3793 // same UID (except for the system or root user), and all whose name
3794 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003795 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003796 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3797 final int NA = apps.size();
3798 for (int ia=0; ia<NA; ia++) {
3799 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003800 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003801 // we don't kill persistent processes
3802 continue;
3803 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003804 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003805 if (doit) {
3806 procs.add(app);
3807 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003808 continue;
3809 }
3810
3811 // Skip process if it doesn't meet our oom adj requirement.
3812 if (app.setAdj < minOomAdj) {
3813 continue;
3814 }
3815
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003816 // If no package is specified, we call all processes under the
3817 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003818 if (packageName == null) {
3819 if (app.userId != userId) {
3820 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003821 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003822 // Package has been specified, we want to hit all processes
3823 // that match it. We need to qualify this by the processes
3824 // that are running under the specified app and user ID.
3825 } else {
3826 if (UserHandle.getAppId(app.uid) != appId) {
3827 continue;
3828 }
3829 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3830 continue;
3831 }
3832 if (!app.pkgList.contains(packageName)) {
3833 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003834 }
3835 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003836
3837 // Process has passed all conditions, kill it!
3838 if (!doit) {
3839 return true;
3840 }
3841 app.removed = true;
3842 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003843 }
3844 }
3845
3846 int N = procs.size();
3847 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003848 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003849 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003850 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003851 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003852
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003853 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003854 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003855 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003856 int i;
3857 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003859 if (userId == UserHandle.USER_ALL && name == null) {
3860 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3861 }
3862
3863 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003865 appId = UserHandle.getAppId(
3866 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 } catch (RemoteException e) {
3868 }
3869 }
3870
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003871 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003872 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003873 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3874 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003875 } else {
3876 Slog.i(TAG, "Force stopping user " + userId);
3877 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003878
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003879 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3880 while (badApps.hasNext()) {
3881 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003882 for (i=ba.size()-1; i>=0; i--) {
3883 boolean remove = false;
3884 final int entUid = ba.keyAt(i);
3885 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003886 if (userId == UserHandle.USER_ALL) {
3887 if (UserHandle.getAppId(entUid) == appId) {
3888 remove = true;
3889 }
3890 } else {
3891 if (entUid == UserHandle.getUid(userId, appId)) {
3892 remove = true;
3893 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003894 }
3895 } else if (UserHandle.getUserId(entUid) == userId) {
3896 remove = true;
3897 }
3898 if (remove) {
3899 ba.removeAt(i);
3900 }
3901 }
3902 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003903 badApps.remove();
3904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003907
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003908 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003909 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003910 name == null ? ("force stop user " + userId) : ("force stop " + name));
Craig Mautnercae015f2013-02-08 14:31:27 -08003911
3912 if (mMainStack.forceStopPackageLocked(name, doit, evenPersistent, userId)) {
3913 if (!doit) {
3914 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003916 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 }
3918
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003919 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3920 if (!doit) {
3921 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003923 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003925
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003926 if (name == null) {
3927 // Remove all sticky broadcasts from this user.
3928 mStickyBroadcasts.remove(userId);
3929 }
3930
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003931 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003932 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3933 userId, providers)) {
3934 if (!doit) {
3935 return true;
3936 }
3937 didSomething = true;
3938 }
3939 N = providers.size();
3940 for (i=0; i<N; i++) {
3941 removeDyingProviderLocked(null, providers.get(i), true);
3942 }
3943
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003944 if (name == null) {
3945 // Remove pending intents. For now we only do this when force
3946 // stopping users, because we have some problems when doing this
3947 // for packages -- app widgets are not currently cleaned up for
3948 // such packages, so they can be left with bad pending intents.
3949 if (mIntentSenderRecords.size() > 0) {
3950 Iterator<WeakReference<PendingIntentRecord>> it
3951 = mIntentSenderRecords.values().iterator();
3952 while (it.hasNext()) {
3953 WeakReference<PendingIntentRecord> wpir = it.next();
3954 if (wpir == null) {
3955 it.remove();
3956 continue;
3957 }
3958 PendingIntentRecord pir = wpir.get();
3959 if (pir == null) {
3960 it.remove();
3961 continue;
3962 }
3963 if (name == null) {
3964 // Stopping user, remove all objects for the user.
3965 if (pir.key.userId != userId) {
3966 // Not the same user, skip it.
3967 continue;
3968 }
3969 } else {
3970 if (UserHandle.getAppId(pir.uid) != appId) {
3971 // Different app id, skip it.
3972 continue;
3973 }
3974 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3975 // Different user, skip it.
3976 continue;
3977 }
3978 if (!pir.key.packageName.equals(name)) {
3979 // Different package, skip it.
3980 continue;
3981 }
3982 }
3983 if (!doit) {
3984 return true;
3985 }
3986 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003987 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003988 pir.canceled = true;
3989 if (pir.key.activity != null) {
3990 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003991 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003992 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003993 }
3994 }
3995
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003996 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003997 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003998 AttributeCache ac = AttributeCache.instance();
3999 if (ac != null) {
4000 ac.removePackage(name);
4001 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004002 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004003 if (mBooted) {
4004 mMainStack.resumeTopActivityLocked(null);
4005 mMainStack.scheduleIdleLocked();
4006 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004007 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004008
4009 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004012 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004013 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004015 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004016 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004017 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 + "/" + uid + ")");
4019
4020 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004021 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004022 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004023 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4024 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004025 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 boolean needRestart = false;
4028 if (app.pid > 0 && app.pid != MY_PID) {
4029 int pid = app.pid;
4030 synchronized (mPidsSelfLocked) {
4031 mPidsSelfLocked.remove(pid);
4032 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4033 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004034 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004035 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004036 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004037 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004039 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004041 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 } else {
4043 needRestart = true;
4044 }
4045 }
4046 } else {
4047 mRemovedProcesses.add(app);
4048 }
4049
4050 return needRestart;
4051 }
4052
4053 private final void processStartTimedOutLocked(ProcessRecord app) {
4054 final int pid = app.pid;
4055 boolean gone = false;
4056 synchronized (mPidsSelfLocked) {
4057 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4058 if (knownApp != null && knownApp.thread == null) {
4059 mPidsSelfLocked.remove(pid);
4060 gone = true;
4061 }
4062 }
4063
4064 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004065 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004066 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4067 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004068 mProcessNames.remove(app.processName, app.uid);
4069 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004070 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004071 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4072 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004073 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004074 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004075 // Take care of any launching providers waiting for this process.
4076 checkAppInLaunchingProvidersLocked(app, true);
4077 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004078 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004079 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004080 app.processName, app.setAdj, "start timeout");
4081 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004082 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004083 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004084 try {
4085 IBackupManager bm = IBackupManager.Stub.asInterface(
4086 ServiceManager.getService(Context.BACKUP_SERVICE));
4087 bm.agentDisconnected(app.info.packageName);
4088 } catch (RemoteException e) {
4089 // Can't happen; the backup manager is local
4090 }
4091 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004092 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004093 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004094 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004097 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 }
4099 }
4100
4101 private final boolean attachApplicationLocked(IApplicationThread thread,
4102 int pid) {
4103
4104 // Find the application record that is being attached... either via
4105 // the pid if we are running in multiple processes, or just pull the
4106 // next app record if we are emulating process with anonymous threads.
4107 ProcessRecord app;
4108 if (pid != MY_PID && pid >= 0) {
4109 synchronized (mPidsSelfLocked) {
4110 app = mPidsSelfLocked.get(pid);
4111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112 } else {
4113 app = null;
4114 }
4115
4116 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004117 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004119 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004121 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 } else {
4123 try {
4124 thread.scheduleExit();
4125 } catch (Exception e) {
4126 // Ignore exceptions.
4127 }
4128 }
4129 return false;
4130 }
4131
4132 // If this application record is still attached to a previous
4133 // process, clean it up now.
4134 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004135 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 }
4137
4138 // Tell the process all about itself.
4139
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 TAG, "Binding process pid " + pid + " to record " + app);
4142
4143 String processName = app.processName;
4144 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004145 AppDeathRecipient adr = new AppDeathRecipient(
4146 app, pid, thread);
4147 thread.asBinder().linkToDeath(adr, 0);
4148 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004149 } catch (RemoteException e) {
4150 app.resetPackageList();
4151 startProcessLocked(app, "link fail", processName);
4152 return false;
4153 }
4154
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004155 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156
4157 app.thread = thread;
4158 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004159 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4160 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 app.forcingToForeground = null;
4162 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004163 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 app.debugging = false;
4165
4166 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4167
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004168 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004169 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004171 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004172 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004173 }
4174
Joe Onorato8a9b2202010-02-26 18:56:32 -08004175 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 TAG, "New app record " + app
4177 + " thread=" + thread.asBinder() + " pid=" + pid);
4178 try {
4179 int testMode = IApplicationThread.DEBUG_OFF;
4180 if (mDebugApp != null && mDebugApp.equals(processName)) {
4181 testMode = mWaitForDebugger
4182 ? IApplicationThread.DEBUG_WAIT
4183 : IApplicationThread.DEBUG_ON;
4184 app.debugging = true;
4185 if (mDebugTransient) {
4186 mDebugApp = mOrigDebugApp;
4187 mWaitForDebugger = mOrigWaitForDebugger;
4188 }
4189 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004190 String profileFile = app.instrumentationProfileFile;
4191 ParcelFileDescriptor profileFd = null;
4192 boolean profileAutoStop = false;
4193 if (mProfileApp != null && mProfileApp.equals(processName)) {
4194 mProfileProc = app;
4195 profileFile = mProfileFile;
4196 profileFd = mProfileFd;
4197 profileAutoStop = mAutoStopProfiler;
4198 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004199 boolean enableOpenGlTrace = false;
4200 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4201 enableOpenGlTrace = true;
4202 mOpenGlTraceApp = null;
4203 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004204
Christopher Tate181fafa2009-05-14 11:12:14 -07004205 // If the app is being launched for restore or full backup, set it up specially
4206 boolean isRestrictedBackupMode = false;
4207 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4208 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004209 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004210 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4211 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004212
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004213 ensurePackageDexOpt(app.instrumentationInfo != null
4214 ? app.instrumentationInfo.packageName
4215 : app.info.packageName);
4216 if (app.instrumentationClass != null) {
4217 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004218 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004219 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004220 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004221 ApplicationInfo appInfo = app.instrumentationInfo != null
4222 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004223 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004224 if (profileFd != null) {
4225 profileFd = profileFd.dup();
4226 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004227 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004228 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08004229 app.instrumentationArguments, app.instrumentationWatcher,
4230 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
4231 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004232 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004233 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004234 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004235 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 } catch (Exception e) {
4237 // todo: Yikes! What should we do? For now we will try to
4238 // start another process, but that could easily get us in
4239 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004240 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241
4242 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004243 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 startProcessLocked(app, "bind fail", processName);
4245 return false;
4246 }
4247
4248 // Remove this record from the list of starting applications.
4249 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004250 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4251 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 mProcessesOnHold.remove(app);
4253
4254 boolean badApp = false;
4255 boolean didSomething = false;
4256
4257 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004258 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004259 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004260 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 && processName.equals(hr.processName)) {
4262 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004263 if (mHeadless) {
4264 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4265 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 didSomething = true;
4267 }
4268 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004269 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 + hr.intent.getComponent().flattenToShortString(), e);
4271 badApp = true;
4272 }
4273 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004274 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004275 }
4276 }
4277
4278 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004279 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004281 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 badApp = true;
4284 }
4285 }
4286
Christopher Tatef46723b2012-01-26 14:19:24 -08004287 // Check if a next-broadcast receiver is in this process...
4288 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004290 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004292 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 }
4295 }
4296
Christopher Tate181fafa2009-05-14 11:12:14 -07004297 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004298 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004299 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004300 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004301 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004302 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4303 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4304 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004305 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004306 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004307 e.printStackTrace();
4308 }
4309 }
4310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 if (badApp) {
4312 // todo: Also need to kill application to deal with all
4313 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004314 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 return false;
4316 }
4317
4318 if (!didSomething) {
4319 updateOomAdjLocked();
4320 }
4321
4322 return true;
4323 }
4324
4325 public final void attachApplication(IApplicationThread thread) {
4326 synchronized (this) {
4327 int callingPid = Binder.getCallingPid();
4328 final long origId = Binder.clearCallingIdentity();
4329 attachApplicationLocked(thread, callingPid);
4330 Binder.restoreCallingIdentity(origId);
4331 }
4332 }
4333
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004334 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004336 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4337 if (stopProfiling) {
4338 synchronized (this) {
4339 if (mProfileProc == r.app) {
4340 if (mProfileFd != null) {
4341 try {
4342 mProfileFd.close();
4343 } catch (IOException e) {
4344 }
4345 clearProfilerLocked();
4346 }
4347 }
4348 }
4349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 Binder.restoreCallingIdentity(origId);
4351 }
4352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004353 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004354 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004355 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004357
4358 synchronized (this) {
4359 updateEventDispatchingLocked();
4360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
4362
Dianne Hackborn661cd522011-08-22 00:26:20 -07004363 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004364 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004365 mWindowManager.showBootMessage(msg, always);
4366 }
4367
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004368 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004369 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004370 final long token = Binder.clearCallingIdentity();
4371 try {
4372 synchronized (this) {
4373 if (mLockScreenShown) {
4374 mLockScreenShown = false;
4375 comeOutOfSleepIfNeededLocked();
4376 }
4377 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004378 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004379 } finally {
4380 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004381 }
4382 }
4383
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004384 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004385 IntentFilter pkgFilter = new IntentFilter();
4386 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4387 pkgFilter.addDataScheme("package");
4388 mContext.registerReceiver(new BroadcastReceiver() {
4389 @Override
4390 public void onReceive(Context context, Intent intent) {
4391 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4392 if (pkgs != null) {
4393 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004394 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004395 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4396 setResultCode(Activity.RESULT_OK);
4397 return;
4398 }
4399 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004400 }
4401 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004402 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004403 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004404
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004405 synchronized (this) {
4406 // Ensure that any processes we had put on hold are now started
4407 // up.
4408 final int NP = mProcessesOnHold.size();
4409 if (NP > 0) {
4410 ArrayList<ProcessRecord> procs =
4411 new ArrayList<ProcessRecord>(mProcessesOnHold);
4412 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004413 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4414 + procs.get(ip));
4415 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004416 }
4417 }
4418
4419 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004420 // Start looking for apps that are abusing wake locks.
4421 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004422 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004423 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004424 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004425 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004426 for (int i=0; i<mStartedUsers.size(); i++) {
4427 UserStartedState uss = mStartedUsers.valueAt(i);
4428 if (uss.mState == UserStartedState.STATE_BOOTING) {
4429 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004430 final int userId = mStartedUsers.keyAt(i);
4431 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4432 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4433 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004434 null, null, 0, null, null,
4435 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08004436 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID,
4437 userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004438 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004439 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004440 }
4441 }
4442 }
4443
4444 final void ensureBootCompleted() {
4445 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004446 boolean enableScreen;
4447 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004448 booting = mBooting;
4449 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004450 enableScreen = !mBooted;
4451 mBooted = true;
4452 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004453
4454 if (booting) {
4455 finishBooting();
4456 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004457
4458 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004459 enableScreenAfterBoot();
4460 }
4461 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004462
4463 public final void activityResumed(IBinder token) {
4464 final long origId = Binder.clearCallingIdentity();
4465 mMainStack.activityResumed(token);
4466 Binder.restoreCallingIdentity(origId);
4467 }
4468
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004469 public final void activityPaused(IBinder token) {
4470 final long origId = Binder.clearCallingIdentity();
4471 mMainStack.activityPaused(token, false);
4472 Binder.restoreCallingIdentity(origId);
4473 }
4474
4475 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4476 CharSequence description) {
4477 if (localLOGV) Slog.v(
4478 TAG, "Activity stopped: token=" + token);
4479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 // Refuse possible leaked file descriptors
4481 if (icicle != null && icicle.hasFileDescriptors()) {
4482 throw new IllegalArgumentException("File descriptors passed in Bundle");
4483 }
4484
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004485 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004486
4487 final long origId = Binder.clearCallingIdentity();
4488
4489 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004490 r = mMainStack.isInStackLocked(token);
4491 if (r != null) {
4492 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 }
4494 }
4495
4496 if (r != null) {
4497 sendPendingThumbnail(r, null, null, null, false);
4498 }
4499
4500 trimApplications();
4501
4502 Binder.restoreCallingIdentity(origId);
4503 }
4504
4505 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004506 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004507 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509
4510 public String getCallingPackage(IBinder token) {
4511 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004512 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004513 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 }
4515 }
4516
4517 public ComponentName getCallingActivity(IBinder token) {
4518 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004519 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 return r != null ? r.intent.getComponent() : null;
4521 }
4522 }
4523
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004524 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004525 ActivityRecord r = mMainStack.isInStackLocked(token);
4526 if (r == null) {
4527 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004528 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004529 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531
4532 public ComponentName getActivityClassForToken(IBinder token) {
4533 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004534 ActivityRecord r = mMainStack.isInStackLocked(token);
4535 if (r == null) {
4536 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004538 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 }
4540 }
4541
4542 public String getPackageForToken(IBinder token) {
4543 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004544 ActivityRecord r = mMainStack.isInStackLocked(token);
4545 if (r == null) {
4546 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004548 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 }
4550 }
4551
4552 public IIntentSender getIntentSender(int type,
4553 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004554 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004555 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004556 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004558 if (intents != null) {
4559 if (intents.length < 1) {
4560 throw new IllegalArgumentException("Intents array length must be >= 1");
4561 }
4562 for (int i=0; i<intents.length; i++) {
4563 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004564 if (intent != null) {
4565 if (intent.hasFileDescriptors()) {
4566 throw new IllegalArgumentException("File descriptors passed in Intent");
4567 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004568 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004569 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4570 throw new IllegalArgumentException(
4571 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4572 }
4573 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004574 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004575 }
4576 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004577 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004578 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004579 }
4580 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004581 if (options != null) {
4582 if (options.hasFileDescriptors()) {
4583 throw new IllegalArgumentException("File descriptors passed in options");
4584 }
4585 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 synchronized(this) {
4588 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004589 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004590 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004591 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004592 "getIntentSender", null);
4593 if (origUserId == UserHandle.USER_CURRENT) {
4594 // We don't want to evaluate this until the pending intent is
4595 // actually executed. However, we do want to always do the
4596 // security checking for it above.
4597 userId = UserHandle.USER_CURRENT;
4598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004600 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004601 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004602 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4603 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 String msg = "Permission Denial: getIntentSender() from pid="
4605 + Binder.getCallingPid()
4606 + ", uid=" + Binder.getCallingUid()
4607 + ", (need uid=" + uid + ")"
4608 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004609 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 throw new SecurityException(msg);
4611 }
4612 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004613
4614 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004615 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004617 } catch (RemoteException e) {
4618 throw new SecurityException(e);
4619 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 }
4621 }
4622
Dianne Hackborn41203752012-08-31 14:05:51 -07004623 IIntentSender getIntentSenderLocked(int type, String packageName,
4624 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004625 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4626 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004627 if (DEBUG_MU)
4628 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004629 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004630 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004631 activity = mMainStack.isInStackLocked(token);
4632 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004633 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004635 if (activity.finishing) {
4636 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004637 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004638 }
4639
4640 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4641 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4642 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4643 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4644 |PendingIntent.FLAG_UPDATE_CURRENT);
4645
4646 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4647 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004648 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004649 WeakReference<PendingIntentRecord> ref;
4650 ref = mIntentSenderRecords.get(key);
4651 PendingIntentRecord rec = ref != null ? ref.get() : null;
4652 if (rec != null) {
4653 if (!cancelCurrent) {
4654 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004655 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004656 rec.key.requestIntent.replaceExtras(intents != null ?
4657 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004658 }
4659 if (intents != null) {
4660 intents[intents.length-1] = rec.key.requestIntent;
4661 rec.key.allIntents = intents;
4662 rec.key.allResolvedTypes = resolvedTypes;
4663 } else {
4664 rec.key.allIntents = null;
4665 rec.key.allResolvedTypes = null;
4666 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 return rec;
4669 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004670 rec.canceled = true;
4671 mIntentSenderRecords.remove(key);
4672 }
4673 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 return rec;
4675 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004676 rec = new PendingIntentRecord(this, key, callingUid);
4677 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004678 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004679 if (activity.pendingResults == null) {
4680 activity.pendingResults
4681 = new HashSet<WeakReference<PendingIntentRecord>>();
4682 }
4683 activity.pendingResults.add(rec.ref);
4684 }
4685 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 }
4687
4688 public void cancelIntentSender(IIntentSender sender) {
4689 if (!(sender instanceof PendingIntentRecord)) {
4690 return;
4691 }
4692 synchronized(this) {
4693 PendingIntentRecord rec = (PendingIntentRecord)sender;
4694 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004695 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004696 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4697 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 String msg = "Permission Denial: cancelIntentSender() from pid="
4699 + Binder.getCallingPid()
4700 + ", uid=" + Binder.getCallingUid()
4701 + " is not allowed to cancel packges "
4702 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004703 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004704 throw new SecurityException(msg);
4705 }
4706 } catch (RemoteException e) {
4707 throw new SecurityException(e);
4708 }
4709 cancelIntentSenderLocked(rec, true);
4710 }
4711 }
4712
4713 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4714 rec.canceled = true;
4715 mIntentSenderRecords.remove(rec.key);
4716 if (cleanActivity && rec.key.activity != null) {
4717 rec.key.activity.pendingResults.remove(rec.ref);
4718 }
4719 }
4720
4721 public String getPackageForIntentSender(IIntentSender pendingResult) {
4722 if (!(pendingResult instanceof PendingIntentRecord)) {
4723 return null;
4724 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004725 try {
4726 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4727 return res.key.packageName;
4728 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 }
4730 return null;
4731 }
4732
Christopher Tatec4a07d12012-04-06 14:19:13 -07004733 public int getUidForIntentSender(IIntentSender sender) {
4734 if (sender instanceof PendingIntentRecord) {
4735 try {
4736 PendingIntentRecord res = (PendingIntentRecord)sender;
4737 return res.uid;
4738 } catch (ClassCastException e) {
4739 }
4740 }
4741 return -1;
4742 }
4743
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004744 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4745 if (!(pendingResult instanceof PendingIntentRecord)) {
4746 return false;
4747 }
4748 try {
4749 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4750 if (res.key.allIntents == null) {
4751 return false;
4752 }
4753 for (int i=0; i<res.key.allIntents.length; i++) {
4754 Intent intent = res.key.allIntents[i];
4755 if (intent.getPackage() != null && intent.getComponent() != null) {
4756 return false;
4757 }
4758 }
4759 return true;
4760 } catch (ClassCastException e) {
4761 }
4762 return false;
4763 }
4764
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004765 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4766 if (!(pendingResult instanceof PendingIntentRecord)) {
4767 return false;
4768 }
4769 try {
4770 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4771 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4772 return true;
4773 }
4774 return false;
4775 } catch (ClassCastException e) {
4776 }
4777 return false;
4778 }
4779
Dianne Hackborn81038902012-11-26 17:04:09 -08004780 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4781 if (!(pendingResult instanceof PendingIntentRecord)) {
4782 return null;
4783 }
4784 try {
4785 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4786 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4787 } catch (ClassCastException e) {
4788 }
4789 return null;
4790 }
4791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004792 public void setProcessLimit(int max) {
4793 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4794 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004795 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004796 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004797 mProcessLimitOverride = max;
4798 }
4799 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004800 }
4801
4802 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004803 synchronized (this) {
4804 return mProcessLimitOverride;
4805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004806 }
4807
4808 void foregroundTokenDied(ForegroundToken token) {
4809 synchronized (ActivityManagerService.this) {
4810 synchronized (mPidsSelfLocked) {
4811 ForegroundToken cur
4812 = mForegroundProcesses.get(token.pid);
4813 if (cur != token) {
4814 return;
4815 }
4816 mForegroundProcesses.remove(token.pid);
4817 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4818 if (pr == null) {
4819 return;
4820 }
4821 pr.forcingToForeground = null;
4822 pr.foregroundServices = false;
4823 }
4824 updateOomAdjLocked();
4825 }
4826 }
4827
4828 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4829 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4830 "setProcessForeground()");
4831 synchronized(this) {
4832 boolean changed = false;
4833
4834 synchronized (mPidsSelfLocked) {
4835 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004836 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004837 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004838 return;
4839 }
4840 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4841 if (oldToken != null) {
4842 oldToken.token.unlinkToDeath(oldToken, 0);
4843 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004844 if (pr != null) {
4845 pr.forcingToForeground = null;
4846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 changed = true;
4848 }
4849 if (isForeground && token != null) {
4850 ForegroundToken newToken = new ForegroundToken() {
4851 public void binderDied() {
4852 foregroundTokenDied(this);
4853 }
4854 };
4855 newToken.pid = pid;
4856 newToken.token = token;
4857 try {
4858 token.linkToDeath(newToken, 0);
4859 mForegroundProcesses.put(pid, newToken);
4860 pr.forcingToForeground = token;
4861 changed = true;
4862 } catch (RemoteException e) {
4863 // If the process died while doing this, we will later
4864 // do the cleanup with the process death link.
4865 }
4866 }
4867 }
4868
4869 if (changed) {
4870 updateOomAdjLocked();
4871 }
4872 }
4873 }
4874
4875 // =========================================================
4876 // PERMISSIONS
4877 // =========================================================
4878
4879 static class PermissionController extends IPermissionController.Stub {
4880 ActivityManagerService mActivityManagerService;
4881 PermissionController(ActivityManagerService activityManagerService) {
4882 mActivityManagerService = activityManagerService;
4883 }
4884
4885 public boolean checkPermission(String permission, int pid, int uid) {
4886 return mActivityManagerService.checkPermission(permission, pid,
4887 uid) == PackageManager.PERMISSION_GRANTED;
4888 }
4889 }
4890
4891 /**
4892 * This can be called with or without the global lock held.
4893 */
4894 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004895 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 // We might be performing an operation on behalf of an indirect binder
4897 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4898 // client identity accordingly before proceeding.
4899 Identity tlsIdentity = sCallerIdentity.get();
4900 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004901 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4903 uid = tlsIdentity.uid;
4904 pid = tlsIdentity.pid;
4905 }
4906
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004907 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004908 return PackageManager.PERMISSION_GRANTED;
4909 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004910
4911 return ActivityManager.checkComponentPermission(permission, uid,
4912 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
4914
4915 /**
4916 * As the only public entry point for permissions checking, this method
4917 * can enforce the semantic that requesting a check on a null global
4918 * permission is automatically denied. (Internally a null permission
4919 * string is used when calling {@link #checkComponentPermission} in cases
4920 * when only uid-based security is needed.)
4921 *
4922 * This can be called with or without the global lock held.
4923 */
4924 public int checkPermission(String permission, int pid, int uid) {
4925 if (permission == null) {
4926 return PackageManager.PERMISSION_DENIED;
4927 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004928 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 }
4930
4931 /**
4932 * Binder IPC calls go through the public entry point.
4933 * This can be called with or without the global lock held.
4934 */
4935 int checkCallingPermission(String permission) {
4936 return checkPermission(permission,
4937 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004938 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 }
4940
4941 /**
4942 * This can be called with or without the global lock held.
4943 */
4944 void enforceCallingPermission(String permission, String func) {
4945 if (checkCallingPermission(permission)
4946 == PackageManager.PERMISSION_GRANTED) {
4947 return;
4948 }
4949
4950 String msg = "Permission Denial: " + func + " from pid="
4951 + Binder.getCallingPid()
4952 + ", uid=" + Binder.getCallingUid()
4953 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004954 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 throw new SecurityException(msg);
4956 }
4957
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004958 /**
4959 * Determine if UID is holding permissions required to access {@link Uri} in
4960 * the given {@link ProviderInfo}. Final permission checking is always done
4961 * in {@link ContentProvider}.
4962 */
4963 private final boolean checkHoldingPermissionsLocked(
4964 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004965 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4966 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004967
4968 if (pi.applicationInfo.uid == uid) {
4969 return true;
4970 } else if (!pi.exported) {
4971 return false;
4972 }
4973
4974 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4975 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004977 // check if target holds top-level <provider> permissions
4978 if (!readMet && pi.readPermission != null
4979 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4980 readMet = true;
4981 }
4982 if (!writeMet && pi.writePermission != null
4983 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4984 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004985 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004986
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004987 // track if unprotected read/write is allowed; any denied
4988 // <path-permission> below removes this ability
4989 boolean allowDefaultRead = pi.readPermission == null;
4990 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004991
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004992 // check if target holds any <path-permission> that match uri
4993 final PathPermission[] pps = pi.pathPermissions;
4994 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004995 final String path = uri.getPath();
4996 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004997 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004998 i--;
4999 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005000 if (pp.match(path)) {
5001 if (!readMet) {
5002 final String pprperm = pp.getReadPermission();
5003 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5004 + pprperm + " for " + pp.getPath()
5005 + ": match=" + pp.match(path)
5006 + " check=" + pm.checkUidPermission(pprperm, uid));
5007 if (pprperm != null) {
5008 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5009 readMet = true;
5010 } else {
5011 allowDefaultRead = false;
5012 }
5013 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005014 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005015 if (!writeMet) {
5016 final String ppwperm = pp.getWritePermission();
5017 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5018 + ppwperm + " for " + pp.getPath()
5019 + ": match=" + pp.match(path)
5020 + " check=" + pm.checkUidPermission(ppwperm, uid));
5021 if (ppwperm != null) {
5022 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5023 writeMet = true;
5024 } else {
5025 allowDefaultWrite = false;
5026 }
5027 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005028 }
5029 }
5030 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005031 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005032
5033 // grant unprotected <provider> read/write, if not blocked by
5034 // <path-permission> above
5035 if (allowDefaultRead) readMet = true;
5036 if (allowDefaultWrite) writeMet = true;
5037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 } catch (RemoteException e) {
5039 return false;
5040 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005041
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005042 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 }
5044
5045 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5046 int modeFlags) {
5047 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005048 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005049 return true;
5050 }
5051 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5052 if (perms == null) return false;
5053 UriPermission perm = perms.get(uri);
5054 if (perm == null) return false;
5055 return (modeFlags&perm.modeFlags) == modeFlags;
5056 }
5057
5058 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005059 enforceNotIsolatedCaller("checkUriPermission");
5060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 // Another redirected-binder-call permissions check as in
5062 // {@link checkComponentPermission}.
5063 Identity tlsIdentity = sCallerIdentity.get();
5064 if (tlsIdentity != null) {
5065 uid = tlsIdentity.uid;
5066 pid = tlsIdentity.pid;
5067 }
5068
5069 // Our own process gets to do everything.
5070 if (pid == MY_PID) {
5071 return PackageManager.PERMISSION_GRANTED;
5072 }
5073 synchronized(this) {
5074 return checkUriPermissionLocked(uri, uid, modeFlags)
5075 ? PackageManager.PERMISSION_GRANTED
5076 : PackageManager.PERMISSION_DENIED;
5077 }
5078 }
5079
Dianne Hackborn39792d22010-08-19 18:01:52 -07005080 /**
5081 * Check if the targetPkg can be granted permission to access uri by
5082 * the callingUid using the given modeFlags. Throws a security exception
5083 * if callingUid is not allowed to do this. Returns the uid of the target
5084 * if the URI permission grant should be performed; returns -1 if it is not
5085 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005086 * If you already know the uid of the target, you can supply it in
5087 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005088 */
5089 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005090 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5092 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5093 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005094 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005095 }
5096
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005097 if (targetPkg != null) {
5098 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5099 "Checking grant " + targetPkg + " permission to " + uri);
5100 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005101
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005102 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005103
5104 // If this is not a content: uri, we can't do anything with it.
5105 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005106 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005107 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005108 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110
5111 String name = uri.getAuthority();
5112 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005113 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005114 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005115 if (cpr != null) {
5116 pi = cpr.info;
5117 } else {
5118 try {
5119 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005120 PackageManager.GET_URI_PERMISSION_PATTERNS,
5121 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 } catch (RemoteException ex) {
5123 }
5124 }
5125 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005126 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005127 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005128 }
5129
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005130 int targetUid = lastTargetUid;
5131 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005132 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005133 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005134 if (targetUid < 0) {
5135 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5136 "Can't grant URI permission no uid for: " + targetPkg);
5137 return -1;
5138 }
5139 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005140 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 }
5143
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005144 if (targetUid >= 0) {
5145 // First... does the target actually need this permission?
5146 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5147 // No need to grant the target this permission.
5148 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5149 "Target " + targetPkg + " already has full permission to " + uri);
5150 return -1;
5151 }
5152 } else {
5153 // First... there is no target package, so can anyone access it?
5154 boolean allowed = pi.exported;
5155 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5156 if (pi.readPermission != null) {
5157 allowed = false;
5158 }
5159 }
5160 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5161 if (pi.writePermission != null) {
5162 allowed = false;
5163 }
5164 }
5165 if (allowed) {
5166 return -1;
5167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005168 }
5169
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005170 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 if (!pi.grantUriPermissions) {
5172 throw new SecurityException("Provider " + pi.packageName
5173 + "/" + pi.name
5174 + " does not allow granting of Uri permissions (uri "
5175 + uri + ")");
5176 }
5177 if (pi.uriPermissionPatterns != null) {
5178 final int N = pi.uriPermissionPatterns.length;
5179 boolean allowed = false;
5180 for (int i=0; i<N; i++) {
5181 if (pi.uriPermissionPatterns[i] != null
5182 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5183 allowed = true;
5184 break;
5185 }
5186 }
5187 if (!allowed) {
5188 throw new SecurityException("Provider " + pi.packageName
5189 + "/" + pi.name
5190 + " does not allow granting of permission to path of Uri "
5191 + uri);
5192 }
5193 }
5194
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005195 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005197 if (callingUid != Process.myUid()) {
5198 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5199 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5200 throw new SecurityException("Uid " + callingUid
5201 + " does not have permission to uri " + uri);
5202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 }
5204 }
5205
Dianne Hackborn39792d22010-08-19 18:01:52 -07005206 return targetUid;
5207 }
5208
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005209 public int checkGrantUriPermission(int callingUid, String targetPkg,
5210 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005211 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005212 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005213 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005214 }
5215 }
5216
Dianne Hackborn39792d22010-08-19 18:01:52 -07005217 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5218 Uri uri, int modeFlags, UriPermissionOwner owner) {
5219 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5220 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5221 if (modeFlags == 0) {
5222 return;
5223 }
5224
5225 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005226 // to the uri, and the target doesn't. Let's now give this to
5227 // the target.
5228
Joe Onorato8a9b2202010-02-26 18:56:32 -08005229 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005230 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 HashMap<Uri, UriPermission> targetUris
5233 = mGrantedUriPermissions.get(targetUid);
5234 if (targetUris == null) {
5235 targetUris = new HashMap<Uri, UriPermission>();
5236 mGrantedUriPermissions.put(targetUid, targetUris);
5237 }
5238
5239 UriPermission perm = targetUris.get(uri);
5240 if (perm == null) {
5241 perm = new UriPermission(targetUid, uri);
5242 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005246 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005247 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005248 } else {
5249 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5250 perm.readOwners.add(owner);
5251 owner.addReadPermission(perm);
5252 }
5253 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5254 perm.writeOwners.add(owner);
5255 owner.addWritePermission(perm);
5256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 }
5258 }
5259
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005260 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5261 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005262 if (targetPkg == null) {
5263 throw new NullPointerException("targetPkg");
5264 }
5265
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005266 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005267 if (targetUid < 0) {
5268 return;
5269 }
5270
5271 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5272 }
5273
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005274 static class NeededUriGrants extends ArrayList<Uri> {
5275 final String targetPkg;
5276 final int targetUid;
5277 final int flags;
5278
5279 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5280 targetPkg = _targetPkg;
5281 targetUid = _targetUid;
5282 flags = _flags;
5283 }
5284 }
5285
Dianne Hackborn39792d22010-08-19 18:01:52 -07005286 /**
5287 * Like checkGrantUriPermissionLocked, but takes an Intent.
5288 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005289 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5290 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005291 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005292 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5293 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005294 + " from " + intent + "; flags=0x"
5295 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5296
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005297 if (targetPkg == null) {
5298 throw new NullPointerException("targetPkg");
5299 }
5300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005301 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005302 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
5304 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005305 ClipData clip = intent.getClipData();
5306 if (data == null && clip == null) {
5307 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005308 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005309 if (data != null) {
5310 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5311 mode, needed != null ? needed.targetUid : -1);
5312 if (target > 0) {
5313 if (needed == null) {
5314 needed = new NeededUriGrants(targetPkg, target, mode);
5315 }
5316 needed.add(data);
5317 }
5318 }
5319 if (clip != null) {
5320 for (int i=0; i<clip.getItemCount(); i++) {
5321 Uri uri = clip.getItemAt(i).getUri();
5322 if (uri != null) {
5323 int target = -1;
5324 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5325 mode, needed != null ? needed.targetUid : -1);
5326 if (target > 0) {
5327 if (needed == null) {
5328 needed = new NeededUriGrants(targetPkg, target, mode);
5329 }
5330 needed.add(uri);
5331 }
5332 } else {
5333 Intent clipIntent = clip.getItemAt(i).getIntent();
5334 if (clipIntent != null) {
5335 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5336 callingUid, targetPkg, clipIntent, mode, needed);
5337 if (newNeeded != null) {
5338 needed = newNeeded;
5339 }
5340 }
5341 }
5342 }
5343 }
5344
5345 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005346 }
5347
5348 /**
5349 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5350 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005351 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5352 UriPermissionOwner owner) {
5353 if (needed != null) {
5354 for (int i=0; i<needed.size(); i++) {
5355 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5356 needed.get(i), needed.flags, owner);
5357 }
5358 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005359 }
5360
5361 void grantUriPermissionFromIntentLocked(int callingUid,
5362 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005363 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005364 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005365 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 return;
5367 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005368
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005369 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 }
5371
5372 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5373 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005374 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005375 synchronized(this) {
5376 final ProcessRecord r = getRecordForAppLocked(caller);
5377 if (r == null) {
5378 throw new SecurityException("Unable to find app for caller "
5379 + caller
5380 + " when granting permission to uri " + uri);
5381 }
5382 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005383 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 }
5385 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005386 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005387 }
5388
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005389 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005390 null);
5391 }
5392 }
5393
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005394 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5396 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5397 HashMap<Uri, UriPermission> perms
5398 = mGrantedUriPermissions.get(perm.uid);
5399 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005400 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005401 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 perms.remove(perm.uri);
5403 if (perms.size() == 0) {
5404 mGrantedUriPermissions.remove(perm.uid);
5405 }
5406 }
5407 }
5408 }
5409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5411 int modeFlags) {
5412 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5413 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5414 if (modeFlags == 0) {
5415 return;
5416 }
5417
Joe Onorato8a9b2202010-02-26 18:56:32 -08005418 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005419 "Revoking all granted permissions to " + uri);
5420
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005421 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422
5423 final String authority = uri.getAuthority();
5424 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005425 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005426 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 if (cpr != null) {
5428 pi = cpr.info;
5429 } else {
5430 try {
5431 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005432 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 } catch (RemoteException ex) {
5434 }
5435 }
5436 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005437 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 return;
5439 }
5440
5441 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005442 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 // Right now, if you are not the original owner of the permission,
5444 // you are not allowed to revoke it.
5445 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5446 throw new SecurityException("Uid " + callingUid
5447 + " does not have permission to uri " + uri);
5448 //}
5449 }
5450
5451 // Go through all of the permissions and remove any that match.
5452 final List<String> SEGMENTS = uri.getPathSegments();
5453 if (SEGMENTS != null) {
5454 final int NS = SEGMENTS.size();
5455 int N = mGrantedUriPermissions.size();
5456 for (int i=0; i<N; i++) {
5457 HashMap<Uri, UriPermission> perms
5458 = mGrantedUriPermissions.valueAt(i);
5459 Iterator<UriPermission> it = perms.values().iterator();
5460 toploop:
5461 while (it.hasNext()) {
5462 UriPermission perm = it.next();
5463 Uri targetUri = perm.uri;
5464 if (!authority.equals(targetUri.getAuthority())) {
5465 continue;
5466 }
5467 List<String> targetSegments = targetUri.getPathSegments();
5468 if (targetSegments == null) {
5469 continue;
5470 }
5471 if (targetSegments.size() < NS) {
5472 continue;
5473 }
5474 for (int j=0; j<NS; j++) {
5475 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5476 continue toploop;
5477 }
5478 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005479 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005480 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 perm.clearModes(modeFlags);
5482 if (perm.modeFlags == 0) {
5483 it.remove();
5484 }
5485 }
5486 if (perms.size() == 0) {
5487 mGrantedUriPermissions.remove(
5488 mGrantedUriPermissions.keyAt(i));
5489 N--;
5490 i--;
5491 }
5492 }
5493 }
5494 }
5495
5496 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5497 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005498 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 synchronized(this) {
5500 final ProcessRecord r = getRecordForAppLocked(caller);
5501 if (r == null) {
5502 throw new SecurityException("Unable to find app for caller "
5503 + caller
5504 + " when revoking permission to uri " + uri);
5505 }
5506 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005507 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 return;
5509 }
5510
5511 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5512 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5513 if (modeFlags == 0) {
5514 return;
5515 }
5516
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005517 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518
5519 final String authority = uri.getAuthority();
5520 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005521 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 if (cpr != null) {
5523 pi = cpr.info;
5524 } else {
5525 try {
5526 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005527 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 } catch (RemoteException ex) {
5529 }
5530 }
5531 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005532 Slog.w(TAG, "No content provider found for permission revoke: "
5533 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 return;
5535 }
5536
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005537 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 }
5539 }
5540
Dianne Hackborn7e269642010-08-25 19:50:20 -07005541 @Override
5542 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005543 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005544 synchronized(this) {
5545 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5546 return owner.getExternalTokenLocked();
5547 }
5548 }
5549
5550 @Override
5551 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5552 Uri uri, int modeFlags) {
5553 synchronized(this) {
5554 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5555 if (owner == null) {
5556 throw new IllegalArgumentException("Unknown owner: " + token);
5557 }
5558 if (fromUid != Binder.getCallingUid()) {
5559 if (Binder.getCallingUid() != Process.myUid()) {
5560 // Only system code can grant URI permissions on behalf
5561 // of other users.
5562 throw new SecurityException("nice try");
5563 }
5564 }
5565 if (targetPkg == null) {
5566 throw new IllegalArgumentException("null target");
5567 }
5568 if (uri == null) {
5569 throw new IllegalArgumentException("null uri");
5570 }
5571
5572 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5573 }
5574 }
5575
5576 @Override
5577 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5578 synchronized(this) {
5579 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5580 if (owner == null) {
5581 throw new IllegalArgumentException("Unknown owner: " + token);
5582 }
5583
5584 if (uri == null) {
5585 owner.removeUriPermissionsLocked(mode);
5586 } else {
5587 owner.removeUriPermissionLocked(uri, mode);
5588 }
5589 }
5590 }
5591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5593 synchronized (this) {
5594 ProcessRecord app =
5595 who != null ? getRecordForAppLocked(who) : null;
5596 if (app == null) return;
5597
5598 Message msg = Message.obtain();
5599 msg.what = WAIT_FOR_DEBUGGER_MSG;
5600 msg.obj = app;
5601 msg.arg1 = waiting ? 1 : 0;
5602 mHandler.sendMessage(msg);
5603 }
5604 }
5605
5606 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005607 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5608 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005610 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005611 outInfo.threshold = homeAppMem;
5612 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5613 outInfo.hiddenAppThreshold = hiddenAppMem;
5614 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005615 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005616 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5617 ProcessList.VISIBLE_APP_ADJ);
5618 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5619 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005620 }
5621
5622 // =========================================================
5623 // TASK MANAGEMENT
5624 // =========================================================
5625
Craig Mautnercae015f2013-02-08 14:31:27 -08005626 @Override
5627 public List<RunningTaskInfo> getTasks(int maxNum, int flags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 IThumbnailReceiver receiver) {
Craig Mautnercae015f2013-02-08 14:31:27 -08005629 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630
Craig Mautnercae015f2013-02-08 14:31:27 -08005631 PendingThumbnailsRecord pending = new PendingThumbnailsRecord(receiver);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005632 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633
5634 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005635 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5637 + ", receiver=" + receiver);
5638
5639 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5640 != PackageManager.PERMISSION_GRANTED) {
5641 if (receiver != null) {
5642 // If the caller wants to wait for pending thumbnails,
5643 // it ain't gonna get them.
5644 try {
5645 receiver.finished();
5646 } catch (RemoteException ex) {
5647 }
5648 }
5649 String msg = "Permission Denial: getTasks() from pid="
5650 + Binder.getCallingPid()
5651 + ", uid=" + Binder.getCallingUid()
5652 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005653 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 throw new SecurityException(msg);
5655 }
5656
Craig Mautnercae015f2013-02-08 14:31:27 -08005657 topRecord = mMainStack.getTasksLocked(maxNum, receiver, pending, list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658
Craig Mautnercae015f2013-02-08 14:31:27 -08005659 if (!pending.pendingRecords.isEmpty()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 mPendingThumbnails.add(pending);
5661 }
5662 }
5663
Joe Onorato8a9b2202010-02-26 18:56:32 -08005664 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665
Craig Mautnercae015f2013-02-08 14:31:27 -08005666 if (topRecord != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005667 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 try {
Craig Mautnercae015f2013-02-08 14:31:27 -08005669 IApplicationThread topThumbnail = topRecord.app.thread;
Dianne Hackbornbe707852011-11-11 14:32:10 -08005670 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005672 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005673 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 }
5675 }
5676
5677 if (pending == null && receiver != null) {
5678 // In this case all thumbnails were available and the client
5679 // is being asked to be told when the remaining ones come in...
5680 // which is unusually, since the top-most currently running
5681 // activity should never have a canned thumbnail! Oh well.
5682 try {
5683 receiver.finished();
5684 } catch (RemoteException ex) {
5685 }
5686 }
5687
5688 return list;
5689 }
5690
5691 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005692 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005693 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5694 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 synchronized (this) {
5697 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5698 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005699 final boolean detailed = checkCallingPermission(
5700 android.Manifest.permission.GET_DETAILED_TASKS)
5701 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005703 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 final int N = mRecentTasks.size();
5706 ArrayList<ActivityManager.RecentTaskInfo> res
5707 = new ArrayList<ActivityManager.RecentTaskInfo>(
5708 maxNum < N ? maxNum : N);
5709 for (int i=0; i<N && maxNum > 0; i++) {
5710 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005711 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005712 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005713 // Return the entry if desired by the caller. We always return
5714 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005715 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005716 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5717 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005718
Dianne Hackborn905577f2011-09-07 18:31:28 -07005719 if (i == 0
5720 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 || (tr.intent == null)
5722 || ((tr.intent.getFlags()
5723 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5724 ActivityManager.RecentTaskInfo rti
5725 = new ActivityManager.RecentTaskInfo();
5726 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005727 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 rti.baseIntent = new Intent(
5729 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005730 if (!detailed) {
5731 rti.baseIntent.replaceExtras((Bundle)null);
5732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005734 rti.description = tr.lastDescription;
5735
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005736 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5737 // Check whether this activity is currently available.
5738 try {
5739 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005740 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005741 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005742 continue;
5743 }
5744 } else if (rti.baseIntent != null) {
5745 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005746 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005747 continue;
5748 }
5749 }
5750 } catch (RemoteException e) {
5751 // Will never happen.
5752 }
5753 }
5754
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 res.add(rti);
5756 maxNum--;
5757 }
5758 }
5759 return res;
5760 }
5761 }
5762
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005763 private TaskRecord taskForIdLocked(int id) {
5764 final int N = mRecentTasks.size();
5765 for (int i=0; i<N; i++) {
5766 TaskRecord tr = mRecentTasks.get(i);
5767 if (tr.taskId == id) {
5768 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005769 }
5770 }
5771 return null;
5772 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005773
5774 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5775 synchronized (this) {
5776 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5777 "getTaskThumbnails()");
5778 TaskRecord tr = taskForIdLocked(id);
5779 if (tr != null) {
5780 return mMainStack.getTaskThumbnailsLocked(tr);
5781 }
5782 }
5783 return null;
5784 }
5785
Dianne Hackborn15491c62012-09-19 10:59:14 -07005786 public Bitmap getTaskTopThumbnail(int id) {
5787 synchronized (this) {
5788 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5789 "getTaskTopThumbnail()");
5790 TaskRecord tr = taskForIdLocked(id);
5791 if (tr != null) {
5792 return mMainStack.getTaskTopThumbnailLocked(tr);
5793 }
5794 }
5795 return null;
5796 }
5797
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005798 public boolean removeSubTask(int taskId, int subTaskIndex) {
5799 synchronized (this) {
5800 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5801 "removeSubTask()");
5802 long ident = Binder.clearCallingIdentity();
5803 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005804 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5805 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005806 } finally {
5807 Binder.restoreCallingIdentity(ident);
5808 }
5809 }
5810 }
5811
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005812 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5813 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005814 Intent baseIntent = new Intent(
5815 tr.intent != null ? tr.intent : tr.affinityIntent);
5816 ComponentName component = baseIntent.getComponent();
5817 if (component == null) {
5818 Slog.w(TAG, "Now component for base intent of task: " + tr);
5819 return;
5820 }
5821
5822 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005823 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005824
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005825 if (killProcesses) {
5826 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005827 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005828 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005829 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5830 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5831 for (int i=0; i<uids.size(); i++) {
5832 ProcessRecord proc = uids.valueAt(i);
5833 if (proc.userId != tr.userId) {
5834 continue;
5835 }
5836 if (!proc.pkgList.contains(pkg)) {
5837 continue;
5838 }
5839 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005840 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005841 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005842
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005843 // Kill the running processes.
5844 for (int i=0; i<procs.size(); i++) {
5845 ProcessRecord pr = procs.get(i);
5846 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5847 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005848 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005849 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005850 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005851 Process.killProcessQuiet(pr.pid);
5852 } else {
5853 pr.waitingToKill = "remove task";
5854 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005855 }
5856 }
5857 }
5858
5859 public boolean removeTask(int taskId, int flags) {
5860 synchronized (this) {
5861 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5862 "removeTask()");
5863 long ident = Binder.clearCallingIdentity();
5864 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005865 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5866 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005867 if (r != null) {
5868 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005869 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005871 } else {
5872 TaskRecord tr = null;
5873 int i=0;
5874 while (i < mRecentTasks.size()) {
5875 TaskRecord t = mRecentTasks.get(i);
5876 if (t.taskId == taskId) {
5877 tr = t;
5878 break;
5879 }
5880 i++;
5881 }
5882 if (tr != null) {
5883 if (tr.numActivities <= 0) {
5884 // Caller is just removing a recent task that is
5885 // not actively running. That is easy!
5886 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005887 cleanUpRemovedTaskLocked(tr, flags);
5888 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005889 } else {
5890 Slog.w(TAG, "removeTask: task " + taskId
5891 + " does not have activities to remove, "
5892 + " but numActivities=" + tr.numActivities
5893 + ": " + tr);
5894 }
5895 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005896 }
5897 } finally {
5898 Binder.restoreCallingIdentity(ident);
5899 }
5900 }
5901 return false;
5902 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005905 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005907 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5909 "moveTaskToFront()");
5910
5911 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005912 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5913 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005914 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005915 return;
5916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 final long origId = Binder.clearCallingIdentity();
5918 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005919 TaskRecord tr = taskForIdLocked(task);
5920 if (tr != null) {
5921 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5922 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005924 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5925 // Caller wants the home activity moved with it. To accomplish this,
5926 // we'll just move the home task to the top first.
5927 mMainStack.moveHomeToFrontLocked();
5928 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005929 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005930 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005932 if (mMainStack.findTaskToMoveToFrontLocked(task, flags, options)) {
5933 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
5935 } finally {
5936 Binder.restoreCallingIdentity(origId);
5937 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005938 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005939 }
5940 }
5941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 public void moveTaskToBack(int task) {
5943 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5944 "moveTaskToBack()");
5945
5946 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005947 if (mMainStack.mResumedActivity != null
5948 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005949 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5950 Binder.getCallingUid(), "Task to back")) {
5951 return;
5952 }
5953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005955 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 Binder.restoreCallingIdentity(origId);
5957 }
5958 }
5959
5960 /**
5961 * Moves an activity, and all of the other activities within the same task, to the bottom
5962 * of the history stack. The activity's order within the task is unchanged.
5963 *
5964 * @param token A reference to the activity we wish to move
5965 * @param nonRoot If false then this only works if the activity is the root
5966 * of a task; if true it will work for any activity in a task.
5967 * @return Returns true if the move completed, false if not.
5968 */
5969 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005970 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 synchronized(this) {
5972 final long origId = Binder.clearCallingIdentity();
Craig Mautnercae015f2013-02-08 14:31:27 -08005973 int taskId = mMainStack.getTaskForActivityLocked(token, !nonRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005975 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
5977 Binder.restoreCallingIdentity(origId);
5978 }
5979 return false;
5980 }
5981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 public void moveTaskBackwards(int task) {
5983 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5984 "moveTaskBackwards()");
5985
5986 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005987 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5988 Binder.getCallingUid(), "Task backwards")) {
5989 return;
5990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 final long origId = Binder.clearCallingIdentity();
5992 moveTaskBackwardsLocked(task);
5993 Binder.restoreCallingIdentity(origId);
5994 }
5995 }
5996
5997 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005998 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 }
6000
6001 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6002 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08006003 return mMainStack.getTaskForActivityLocked(token, onlyRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
6005 }
6006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 // =========================================================
6008 // THUMBNAILS
6009 // =========================================================
6010
6011 public void reportThumbnail(IBinder token,
6012 Bitmap thumbnail, CharSequence description) {
6013 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6014 final long origId = Binder.clearCallingIdentity();
6015 sendPendingThumbnail(null, token, thumbnail, description, true);
6016 Binder.restoreCallingIdentity(origId);
6017 }
6018
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006019 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 Bitmap thumbnail, CharSequence description, boolean always) {
6021 TaskRecord task = null;
6022 ArrayList receivers = null;
6023
6024 //System.out.println("Send pending thumbnail: " + r);
6025
6026 synchronized(this) {
6027 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006028 r = mMainStack.isInStackLocked(token);
6029 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 return;
6031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006033 if (thumbnail == null && r.thumbHolder != null) {
6034 thumbnail = r.thumbHolder.lastThumbnail;
6035 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 }
6037 if (thumbnail == null && !always) {
6038 // If there is no thumbnail, and this entry is not actually
6039 // going away, then abort for now and pick up the next
6040 // thumbnail we get.
6041 return;
6042 }
6043 task = r.task;
6044
6045 int N = mPendingThumbnails.size();
6046 int i=0;
6047 while (i<N) {
6048 PendingThumbnailsRecord pr =
6049 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6050 //System.out.println("Looking in " + pr.pendingRecords);
6051 if (pr.pendingRecords.remove(r)) {
6052 if (receivers == null) {
6053 receivers = new ArrayList();
6054 }
6055 receivers.add(pr);
6056 if (pr.pendingRecords.size() == 0) {
6057 pr.finished = true;
6058 mPendingThumbnails.remove(i);
6059 N--;
6060 continue;
6061 }
6062 }
6063 i++;
6064 }
6065 }
6066
6067 if (receivers != null) {
6068 final int N = receivers.size();
6069 for (int i=0; i<N; i++) {
6070 try {
6071 PendingThumbnailsRecord pr =
6072 (PendingThumbnailsRecord)receivers.get(i);
6073 pr.receiver.newThumbnail(
6074 task != null ? task.taskId : -1, thumbnail, description);
6075 if (pr.finished) {
6076 pr.receiver.finished();
6077 }
6078 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006079 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081 }
6082 }
6083 }
6084
6085 // =========================================================
6086 // CONTENT PROVIDERS
6087 // =========================================================
6088
Jeff Brown10e89712011-07-08 18:52:57 -07006089 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6090 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006092 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006093 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006094 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 } catch (RemoteException ex) {
6096 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006097 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006098 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6099 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006101 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 for (int i=0; i<N; i++) {
6103 ProviderInfo cpi =
6104 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006105 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6106 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006107 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006108 // This is a singleton provider, but a user besides the
6109 // default user is asking to initialize a process it runs
6110 // in... well, no, it doesn't actually run in this process,
6111 // it runs in the process of the default user. Get rid of it.
6112 providers.remove(i);
6113 N--;
6114 continue;
6115 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006116
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006117 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006118 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006120 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006121 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006123 if (DEBUG_MU)
6124 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 app.pubProviders.put(cpi.name, cpr);
6126 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006127 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 }
6129 }
6130 return providers;
6131 }
6132
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006133 /**
6134 * Check if {@link ProcessRecord} has a possible chance at accessing the
6135 * given {@link ProviderInfo}. Final permission checking is always done
6136 * in {@link ContentProvider}.
6137 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006139 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006141 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006143 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006144 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 return null;
6146 }
6147 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006148 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 == PackageManager.PERMISSION_GRANTED) {
6150 return null;
6151 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006152
6153 PathPermission[] pps = cpi.pathPermissions;
6154 if (pps != null) {
6155 int i = pps.length;
6156 while (i > 0) {
6157 i--;
6158 PathPermission pp = pps[i];
6159 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006160 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006161 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006162 return null;
6163 }
6164 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006165 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006166 == PackageManager.PERMISSION_GRANTED) {
6167 return null;
6168 }
6169 }
6170 }
6171
Dianne Hackbornb424b632010-08-18 15:59:05 -07006172 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6173 if (perms != null) {
6174 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6175 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6176 return null;
6177 }
6178 }
6179 }
6180
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006181 String msg;
6182 if (!cpi.exported) {
6183 msg = "Permission Denial: opening provider " + cpi.name
6184 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6185 + ", uid=" + callingUid + ") that is not exported from uid "
6186 + cpi.applicationInfo.uid;
6187 } else {
6188 msg = "Permission Denial: opening provider " + cpi.name
6189 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6190 + ", uid=" + callingUid + ") requires "
6191 + cpi.readPermission + " or " + cpi.writePermission;
6192 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006193 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 return msg;
6195 }
6196
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006197 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6198 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006199 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006200 for (int i=0; i<r.conProviders.size(); i++) {
6201 ContentProviderConnection conn = r.conProviders.get(i);
6202 if (conn.provider == cpr) {
6203 if (DEBUG_PROVIDER) Slog.v(TAG,
6204 "Adding provider requested by "
6205 + r.processName + " from process "
6206 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6207 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6208 if (stable) {
6209 conn.stableCount++;
6210 conn.numStableIncs++;
6211 } else {
6212 conn.unstableCount++;
6213 conn.numUnstableIncs++;
6214 }
6215 return conn;
6216 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006217 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006218 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6219 if (stable) {
6220 conn.stableCount = 1;
6221 conn.numStableIncs = 1;
6222 } else {
6223 conn.unstableCount = 1;
6224 conn.numUnstableIncs = 1;
6225 }
6226 cpr.connections.add(conn);
6227 r.conProviders.add(conn);
6228 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006229 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006230 cpr.addExternalProcessHandleLocked(externalProcessToken);
6231 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006232 }
6233
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006234 boolean decProviderCountLocked(ContentProviderConnection conn,
6235 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6236 if (conn != null) {
6237 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006238 if (DEBUG_PROVIDER) Slog.v(TAG,
6239 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006240 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006241 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006242 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6243 if (stable) {
6244 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006245 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006246 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006247 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006248 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6249 cpr.connections.remove(conn);
6250 conn.client.conProviders.remove(conn);
6251 return true;
6252 }
6253 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006254 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006255 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 return false;
6257 }
6258
Amith Yamasani742a6712011-05-04 14:49:28 -07006259 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006260 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006262 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 ProviderInfo cpi = null;
6264
6265 synchronized(this) {
6266 ProcessRecord r = null;
6267 if (caller != null) {
6268 r = getRecordForAppLocked(caller);
6269 if (r == null) {
6270 throw new SecurityException(
6271 "Unable to find app for caller " + caller
6272 + " (pid=" + Binder.getCallingPid()
6273 + ") when getting content provider " + name);
6274 }
6275 }
6276
6277 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006278 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006279 boolean providerRunning = cpr != null;
6280 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006282 String msg;
6283 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6284 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
6286
6287 if (r != null && cpr.canRunHere(r)) {
6288 // This provider has been published or is in the process
6289 // of being published... but it is also allowed to run
6290 // in the caller's process, so don't make a connection
6291 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006292 ContentProviderHolder holder = cpr.newHolder(null);
6293 // don't give caller the provider object, it needs
6294 // to make its own.
6295 holder.provider = null;
6296 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
6298
6299 final long origId = Binder.clearCallingIdentity();
6300
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006301 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006303 conn = incProviderCountLocked(r, cpr, token, stable);
6304 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006305 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006306 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006307 // make sure to count it as being accessed and thus
6308 // back up on the LRU list. This is good because
6309 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006310 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006311 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006312 }
6313
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006314 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006315 if (false) {
6316 if (cpr.name.flattenToShortString().equals(
6317 "com.android.providers.calendar/.CalendarProvider2")) {
6318 Slog.v(TAG, "****************** KILLING "
6319 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006320 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006321 }
6322 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006323 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006324 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6325 // NOTE: there is still a race here where a signal could be
6326 // pending on the process even though we managed to update its
6327 // adj level. Not sure what to do about this, but at least
6328 // the race is now smaller.
6329 if (!success) {
6330 // Uh oh... it looks like the provider's process
6331 // has been killed on us. We need to wait for a new
6332 // process to be started, and make sure its death
6333 // doesn't kill our process.
6334 Slog.i(TAG,
6335 "Existing provider " + cpr.name.flattenToShortString()
6336 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006337 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006338 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006339 if (!lastRef) {
6340 // This wasn't the last ref our process had on
6341 // the provider... we have now been killed, bail.
6342 return null;
6343 }
6344 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006345 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 }
6348
6349 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006350 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006352 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006353 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006355 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006356 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006357 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 } catch (RemoteException ex) {
6359 }
6360 if (cpi == null) {
6361 return null;
6362 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006363 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6364 cpi.name, cpi.flags);
6365 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006366 userId = 0;
6367 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006368 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006369
Dianne Hackbornb424b632010-08-18 15:59:05 -07006370 String msg;
6371 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6372 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 }
6374
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006375 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006376 && !cpi.processName.equals("system")) {
6377 // If this content provider does not run in the system
6378 // process, and the system is not yet ready to run other
6379 // processes, then fail fast instead of hanging.
6380 throw new IllegalArgumentException(
6381 "Attempt to launch content provider before system ready");
6382 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006383
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006384 // Make sure that the user who owns this provider is started. If not,
6385 // we don't want to allow it to run.
6386 if (mStartedUsers.get(userId) == null) {
6387 Slog.w(TAG, "Unable to launch app "
6388 + cpi.applicationInfo.packageName + "/"
6389 + cpi.applicationInfo.uid + " for provider "
6390 + name + ": user " + userId + " is stopped");
6391 return null;
6392 }
6393
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006394 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006395 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 final boolean firstClass = cpr == null;
6397 if (firstClass) {
6398 try {
6399 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006400 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 getApplicationInfo(
6402 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006403 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006405 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 + cpi.name);
6407 return null;
6408 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006409 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006410 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 } catch (RemoteException ex) {
6412 // pm is in same process, this will never happen.
6413 }
6414 }
6415
6416 if (r != null && cpr.canRunHere(r)) {
6417 // If this is a multiprocess provider, then just return its
6418 // info and allow the caller to instantiate it. Only do
6419 // this if the provider is the same user as the caller's
6420 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006421 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 }
6423
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006424 if (DEBUG_PROVIDER) {
6425 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006426 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006427 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 }
6429
6430 // This is single process, and our app is now connecting to it.
6431 // See if we are already in the process of launching this
6432 // provider.
6433 final int N = mLaunchingProviders.size();
6434 int i;
6435 for (i=0; i<N; i++) {
6436 if (mLaunchingProviders.get(i) == cpr) {
6437 break;
6438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
6440
6441 // If the provider is not already being launched, then get it
6442 // started.
6443 if (i >= N) {
6444 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006445
6446 try {
6447 // Content provider is now in use, its package can't be stopped.
6448 try {
6449 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006450 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006451 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006452 } catch (IllegalArgumentException e) {
6453 Slog.w(TAG, "Failed trying to unstop package "
6454 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006455 }
6456
6457 ProcessRecord proc = startProcessLocked(cpi.processName,
6458 cpr.appInfo, false, 0, "content provider",
6459 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006460 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006461 if (proc == null) {
6462 Slog.w(TAG, "Unable to launch app "
6463 + cpi.applicationInfo.packageName + "/"
6464 + cpi.applicationInfo.uid + " for provider "
6465 + name + ": process is bad");
6466 return null;
6467 }
6468 cpr.launchingApp = proc;
6469 mLaunchingProviders.add(cpr);
6470 } finally {
6471 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
6474
6475 // Make sure the provider is published (the same provider class
6476 // may be published under multiple names).
6477 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006478 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006480
Amith Yamasani742a6712011-05-04 14:49:28 -07006481 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006482 conn = incProviderCountLocked(r, cpr, token, stable);
6483 if (conn != null) {
6484 conn.waiting = true;
6485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 }
6487 }
6488
6489 // Wait for the provider to be published...
6490 synchronized (cpr) {
6491 while (cpr.provider == null) {
6492 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006493 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 + cpi.applicationInfo.packageName + "/"
6495 + cpi.applicationInfo.uid + " for provider "
6496 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006497 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006498 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 cpi.applicationInfo.packageName,
6500 cpi.applicationInfo.uid, name);
6501 return null;
6502 }
6503 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006504 if (DEBUG_MU) {
6505 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6506 + cpr.launchingApp);
6507 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006508 if (conn != null) {
6509 conn.waiting = true;
6510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 cpr.wait();
6512 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006513 } finally {
6514 if (conn != null) {
6515 conn.waiting = false;
6516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 }
6518 }
6519 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006520 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 }
6522
6523 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006524 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006525 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 if (caller == null) {
6527 String msg = "null IApplicationThread when getting content provider "
6528 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006529 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 throw new SecurityException(msg);
6531 }
6532
Dianne Hackborn139748f2012-09-24 11:36:57 -07006533 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006534 false, true, "getContentProvider", null);
6535 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 }
6537
Jeff Sharkey6d515712012-09-20 16:06:08 -07006538 public ContentProviderHolder getContentProviderExternal(
6539 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006540 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6541 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006542 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006543 false, true, "getContentProvider", null);
6544 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006545 }
6546
Dianne Hackborn41203752012-08-31 14:05:51 -07006547 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6548 IBinder token, int userId) {
6549 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 }
6551
6552 /**
6553 * Drop a content provider from a ProcessRecord's bookkeeping
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006556 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006558 ContentProviderConnection conn;
6559 try {
6560 conn = (ContentProviderConnection)connection;
6561 } catch (ClassCastException e) {
6562 String msg ="removeContentProvider: " + connection
6563 + " not a ContentProviderConnection";
6564 Slog.w(TAG, msg);
6565 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006567 if (conn == null) {
6568 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006570 if (decProviderCountLocked(conn, null, null, stable)) {
6571 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 }
6574 }
6575
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006576 public void removeContentProviderExternal(String name, IBinder token) {
6577 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6578 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006579 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006580 }
6581
Dianne Hackborn41203752012-08-31 14:05:51 -07006582 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006584 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 if(cpr == null) {
6586 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006587 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 return;
6589 }
6590
6591 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006592 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006593 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006594 if (localCpr.hasExternalProcessHandles()) {
6595 if (localCpr.removeExternalProcessHandleLocked(token)) {
6596 updateOomAdjLocked();
6597 } else {
6598 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6599 + " with no external reference for token: "
6600 + token + ".");
6601 }
6602 } else {
6603 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6604 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607 }
6608
6609 public final void publishContentProviders(IApplicationThread caller,
6610 List<ContentProviderHolder> providers) {
6611 if (providers == null) {
6612 return;
6613 }
6614
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006615 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006616 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006618 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006619 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 if (r == null) {
6621 throw new SecurityException(
6622 "Unable to find app for caller " + caller
6623 + " (pid=" + Binder.getCallingPid()
6624 + ") when publishing content providers");
6625 }
6626
6627 final long origId = Binder.clearCallingIdentity();
6628
6629 final int N = providers.size();
6630 for (int i=0; i<N; i++) {
6631 ContentProviderHolder src = providers.get(i);
6632 if (src == null || src.info == null || src.provider == null) {
6633 continue;
6634 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006635 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006636 if (DEBUG_MU)
6637 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006639 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006640 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 String names[] = dst.info.authority.split(";");
6642 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006643 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006644 }
6645
6646 int NL = mLaunchingProviders.size();
6647 int j;
6648 for (j=0; j<NL; j++) {
6649 if (mLaunchingProviders.get(j) == dst) {
6650 mLaunchingProviders.remove(j);
6651 j--;
6652 NL--;
6653 }
6654 }
6655 synchronized (dst) {
6656 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006657 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 dst.notifyAll();
6659 }
6660 updateOomAdjLocked(r);
6661 }
6662 }
6663
6664 Binder.restoreCallingIdentity(origId);
6665 }
6666 }
6667
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006668 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6669 ContentProviderConnection conn;
6670 try {
6671 conn = (ContentProviderConnection)connection;
6672 } catch (ClassCastException e) {
6673 String msg ="refContentProvider: " + connection
6674 + " not a ContentProviderConnection";
6675 Slog.w(TAG, msg);
6676 throw new IllegalArgumentException(msg);
6677 }
6678 if (conn == null) {
6679 throw new NullPointerException("connection is null");
6680 }
6681
6682 synchronized (this) {
6683 if (stable > 0) {
6684 conn.numStableIncs += stable;
6685 }
6686 stable = conn.stableCount + stable;
6687 if (stable < 0) {
6688 throw new IllegalStateException("stableCount < 0: " + stable);
6689 }
6690
6691 if (unstable > 0) {
6692 conn.numUnstableIncs += unstable;
6693 }
6694 unstable = conn.unstableCount + unstable;
6695 if (unstable < 0) {
6696 throw new IllegalStateException("unstableCount < 0: " + unstable);
6697 }
6698
6699 if ((stable+unstable) <= 0) {
6700 throw new IllegalStateException("ref counts can't go to zero here: stable="
6701 + stable + " unstable=" + unstable);
6702 }
6703 conn.stableCount = stable;
6704 conn.unstableCount = unstable;
6705 return !conn.dead;
6706 }
6707 }
6708
6709 public void unstableProviderDied(IBinder connection) {
6710 ContentProviderConnection conn;
6711 try {
6712 conn = (ContentProviderConnection)connection;
6713 } catch (ClassCastException e) {
6714 String msg ="refContentProvider: " + connection
6715 + " not a ContentProviderConnection";
6716 Slog.w(TAG, msg);
6717 throw new IllegalArgumentException(msg);
6718 }
6719 if (conn == null) {
6720 throw new NullPointerException("connection is null");
6721 }
6722
6723 // Safely retrieve the content provider associated with the connection.
6724 IContentProvider provider;
6725 synchronized (this) {
6726 provider = conn.provider.provider;
6727 }
6728
6729 if (provider == null) {
6730 // Um, yeah, we're way ahead of you.
6731 return;
6732 }
6733
6734 // Make sure the caller is being honest with us.
6735 if (provider.asBinder().pingBinder()) {
6736 // Er, no, still looks good to us.
6737 synchronized (this) {
6738 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6739 + " says " + conn + " died, but we don't agree");
6740 return;
6741 }
6742 }
6743
6744 // Well look at that! It's dead!
6745 synchronized (this) {
6746 if (conn.provider.provider != provider) {
6747 // But something changed... good enough.
6748 return;
6749 }
6750
6751 ProcessRecord proc = conn.provider.proc;
6752 if (proc == null || proc.thread == null) {
6753 // Seems like the process is already cleaned up.
6754 return;
6755 }
6756
6757 // As far as we're concerned, this is just like receiving a
6758 // death notification... just a bit prematurely.
6759 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6760 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006761 final long ident = Binder.clearCallingIdentity();
6762 try {
6763 appDiedLocked(proc, proc.pid, proc.thread);
6764 } finally {
6765 Binder.restoreCallingIdentity(ident);
6766 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006767 }
6768 }
6769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006771 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006772 synchronized (mSelf) {
6773 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6774 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006775 if (providers != null) {
6776 for (int i=providers.size()-1; i>=0; i--) {
6777 ProviderInfo pi = (ProviderInfo)providers.get(i);
6778 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6779 Slog.w(TAG, "Not installing system proc provider " + pi.name
6780 + ": not system .apk");
6781 providers.remove(i);
6782 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006783 }
6784 }
6785 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006786 if (providers != null) {
6787 mSystemThread.installSystemProviders(providers);
6788 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006789
6790 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006791
6792 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 }
6794
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006795 /**
6796 * Allows app to retrieve the MIME type of a URI without having permission
6797 * to access its content provider.
6798 *
6799 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6800 *
6801 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6802 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6803 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006804 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006805 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006806 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006807 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006808 final String name = uri.getAuthority();
6809 final long ident = Binder.clearCallingIdentity();
6810 ContentProviderHolder holder = null;
6811
6812 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006813 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006814 if (holder != null) {
6815 return holder.provider.getType(uri);
6816 }
6817 } catch (RemoteException e) {
6818 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6819 return null;
6820 } finally {
6821 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006822 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006823 }
6824 Binder.restoreCallingIdentity(ident);
6825 }
6826
6827 return null;
6828 }
6829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 // =========================================================
6831 // GLOBAL MANAGEMENT
6832 // =========================================================
6833
6834 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006835 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 String proc = customProcess != null ? customProcess : info.processName;
6837 BatteryStatsImpl.Uid.Proc ps = null;
6838 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006839 int uid = info.uid;
6840 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006841 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006842 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6843 uid = 0;
6844 while (true) {
6845 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6846 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6847 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6848 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006849 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006850 mNextIsolatedProcessUid++;
6851 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6852 // No process for this uid, use it.
6853 break;
6854 }
6855 stepsLeft--;
6856 if (stepsLeft <= 0) {
6857 return null;
6858 }
6859 }
6860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 synchronized (stats) {
6862 ps = stats.getProcessStatsLocked(info.uid, proc);
6863 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006864 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006867 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6868 ProcessRecord app;
6869 if (!isolated) {
6870 app = getProcessRecordLocked(info.processName, info.uid);
6871 } else {
6872 app = null;
6873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874
6875 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006876 app = newProcessRecordLocked(null, info, null, isolated);
6877 mProcessNames.put(info.processName, app.uid, app);
6878 if (isolated) {
6879 mIsolatedProcesses.put(app.uid, app);
6880 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006881 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 }
6883
Dianne Hackborne7f97212011-02-24 14:40:20 -08006884 // This package really, really can not be stopped.
6885 try {
6886 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006887 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006888 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006889 } catch (IllegalArgumentException e) {
6890 Slog.w(TAG, "Failed trying to unstop package "
6891 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006892 }
6893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6895 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6896 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006897 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 }
6899 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6900 mPersistentStartingProcesses.add(app);
6901 startProcessLocked(app, "added application", app.processName);
6902 }
6903
6904 return app;
6905 }
6906
6907 public void unhandledBack() {
6908 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6909 "unhandledBack()");
6910
6911 synchronized(this) {
Craig Mautnercae015f2013-02-08 14:31:27 -08006912 final long origId = Binder.clearCallingIdentity();
6913 try {
6914 mMainStack.unhandledBackLocked();
6915 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006916 Binder.restoreCallingIdentity(origId);
6917 }
6918 }
6919 }
6920
6921 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006922 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006923 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006924 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006925 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 ParcelFileDescriptor pfd = null;
6927 if (cph != null) {
6928 // We record the binder invoker's uid in thread-local storage before
6929 // going to the content provider to open the file. Later, in the code
6930 // that handles all permissions checks, we look for this uid and use
6931 // that rather than the Activity Manager's own uid. The effect is that
6932 // we do the check against the caller's permissions even though it looks
6933 // to the content provider like the Activity Manager itself is making
6934 // the request.
6935 sCallerIdentity.set(new Identity(
6936 Binder.getCallingPid(), Binder.getCallingUid()));
6937 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08006938 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 } catch (FileNotFoundException e) {
6940 // do nothing; pfd will be returned null
6941 } finally {
6942 // Ensure that whatever happens, we clean up the identity state
6943 sCallerIdentity.remove();
6944 }
6945
6946 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07006947 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006949 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 }
6951 return pfd;
6952 }
6953
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006954 // Actually is sleeping or shutting down or whatever else in the future
6955 // is an inactive state.
6956 public boolean isSleeping() {
6957 return mSleeping || mShuttingDown;
6958 }
6959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006961 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6962 != PackageManager.PERMISSION_GRANTED) {
6963 throw new SecurityException("Requires permission "
6964 + android.Manifest.permission.DEVICE_POWER);
6965 }
6966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006968 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006969 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006970
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006971 if (!mSleeping) {
6972 mSleeping = true;
6973 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006974
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006975 // Initialize the wake times of all processes.
6976 checkExcessivePowerUsageLocked(false);
6977 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6978 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6979 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 }
6982 }
6983
Dianne Hackborn55280a92009-05-07 15:53:46 -07006984 public boolean shutdown(int timeout) {
6985 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6986 != PackageManager.PERMISSION_GRANTED) {
6987 throw new SecurityException("Requires permission "
6988 + android.Manifest.permission.SHUTDOWN);
6989 }
6990
6991 boolean timedout = false;
6992
6993 synchronized(this) {
6994 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006995 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006996
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006997 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006998 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006999 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007000 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007001 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007002 long delay = endTime - System.currentTimeMillis();
7003 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007004 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007005 timedout = true;
7006 break;
7007 }
7008 try {
7009 this.wait();
7010 } catch (InterruptedException e) {
7011 }
7012 }
7013 }
7014 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007015
7016 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007017 mUsageStatsService.shutdown();
7018 mBatteryStatsService.shutdown();
7019
7020 return timedout;
7021 }
7022
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007023 public final void activitySlept(IBinder token) {
7024 if (localLOGV) Slog.v(
7025 TAG, "Activity slept: token=" + token);
7026
7027 ActivityRecord r = null;
7028
7029 final long origId = Binder.clearCallingIdentity();
7030
7031 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007032 r = mMainStack.isInStackLocked(token);
7033 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007034 mMainStack.activitySleptLocked(r);
7035 }
7036 }
7037
7038 Binder.restoreCallingIdentity(origId);
7039 }
7040
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007041 private void comeOutOfSleepIfNeededLocked() {
7042 if (!mWentToSleep && !mLockScreenShown) {
7043 if (mSleeping) {
7044 mSleeping = false;
7045 mMainStack.awakeFromSleepingLocked();
7046 mMainStack.resumeTopActivityLocked(null);
7047 }
7048 }
7049 }
7050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007052 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7053 != PackageManager.PERMISSION_GRANTED) {
7054 throw new SecurityException("Requires permission "
7055 + android.Manifest.permission.DEVICE_POWER);
7056 }
7057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007059 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007060 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007061 comeOutOfSleepIfNeededLocked();
7062 }
7063 }
7064
Jeff Brownc042ee22012-05-08 13:03:42 -07007065 private void updateEventDispatchingLocked() {
7066 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7067 }
7068
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007069 public void setLockScreenShown(boolean shown) {
7070 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7071 != PackageManager.PERMISSION_GRANTED) {
7072 throw new SecurityException("Requires permission "
7073 + android.Manifest.permission.DEVICE_POWER);
7074 }
7075
7076 synchronized(this) {
7077 mLockScreenShown = shown;
7078 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007079 }
7080 }
7081
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007082 public void stopAppSwitches() {
7083 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7084 != PackageManager.PERMISSION_GRANTED) {
7085 throw new SecurityException("Requires permission "
7086 + android.Manifest.permission.STOP_APP_SWITCHES);
7087 }
7088
7089 synchronized(this) {
7090 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7091 + APP_SWITCH_DELAY_TIME;
7092 mDidAppSwitch = false;
7093 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7094 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7095 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7096 }
7097 }
7098
7099 public void resumeAppSwitches() {
7100 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7101 != PackageManager.PERMISSION_GRANTED) {
7102 throw new SecurityException("Requires permission "
7103 + android.Manifest.permission.STOP_APP_SWITCHES);
7104 }
7105
7106 synchronized(this) {
7107 // Note that we don't execute any pending app switches... we will
7108 // let those wait until either the timeout, or the next start
7109 // activity request.
7110 mAppSwitchesAllowedTime = 0;
7111 }
7112 }
7113
7114 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7115 String name) {
7116 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7117 return true;
7118 }
7119
7120 final int perm = checkComponentPermission(
7121 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007122 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007123 if (perm == PackageManager.PERMISSION_GRANTED) {
7124 return true;
7125 }
7126
Joe Onorato8a9b2202010-02-26 18:56:32 -08007127 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007128 return false;
7129 }
7130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 public void setDebugApp(String packageName, boolean waitForDebugger,
7132 boolean persistent) {
7133 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7134 "setDebugApp()");
7135
7136 // Note that this is not really thread safe if there are multiple
7137 // callers into it at the same time, but that's not a situation we
7138 // care about.
7139 if (persistent) {
7140 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007141 Settings.Global.putString(
7142 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007144 Settings.Global.putInt(
7145 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007146 waitForDebugger ? 1 : 0);
7147 }
7148
7149 synchronized (this) {
7150 if (!persistent) {
7151 mOrigDebugApp = mDebugApp;
7152 mOrigWaitForDebugger = mWaitForDebugger;
7153 }
7154 mDebugApp = packageName;
7155 mWaitForDebugger = waitForDebugger;
7156 mDebugTransient = !persistent;
7157 if (packageName != null) {
7158 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007159 forceStopPackageLocked(packageName, -1, false, false, true, true,
7160 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 Binder.restoreCallingIdentity(origId);
7162 }
7163 }
7164 }
7165
Siva Velusamy92a8b222012-03-09 16:24:04 -08007166 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7167 synchronized (this) {
7168 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7169 if (!isDebuggable) {
7170 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7171 throw new SecurityException("Process not debuggable: " + app.packageName);
7172 }
7173 }
7174
7175 mOpenGlTraceApp = processName;
7176 }
7177 }
7178
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007179 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7180 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7181 synchronized (this) {
7182 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7183 if (!isDebuggable) {
7184 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7185 throw new SecurityException("Process not debuggable: " + app.packageName);
7186 }
7187 }
7188 mProfileApp = processName;
7189 mProfileFile = profileFile;
7190 if (mProfileFd != null) {
7191 try {
7192 mProfileFd.close();
7193 } catch (IOException e) {
7194 }
7195 mProfileFd = null;
7196 }
7197 mProfileFd = profileFd;
7198 mProfileType = 0;
7199 mAutoStopProfiler = autoStopProfiler;
7200 }
7201 }
7202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 public void setAlwaysFinish(boolean enabled) {
7204 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7205 "setAlwaysFinish()");
7206
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007207 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007209 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210
7211 synchronized (this) {
7212 mAlwaysFinishActivities = enabled;
7213 }
7214 }
7215
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007216 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007217 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007218 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007220 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 }
7222 }
7223
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007224 public boolean isUserAMonkey() {
7225 // For now the fact that there is a controller implies
7226 // we have a monkey.
7227 synchronized (this) {
7228 return mController != null;
7229 }
7230 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007231
7232 public void requestBugReport() {
Jeff Sharkeyb9323192013-02-05 13:32:18 -08007233 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007234 SystemProperties.set("ctl.start", "bugreport");
7235 }
7236
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007237 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7238 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7239 != PackageManager.PERMISSION_GRANTED) {
7240 throw new SecurityException("Requires permission "
7241 + android.Manifest.permission.FILTER_EVENTS);
7242 }
7243
7244 ProcessRecord proc;
7245
7246 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7247 synchronized (this) {
7248 synchronized (mPidsSelfLocked) {
7249 proc = mPidsSelfLocked.get(pid);
7250 }
7251 if (proc != null) {
7252 if (proc.debugging) {
7253 return -1;
7254 }
7255
7256 if (mDidDexOpt) {
7257 // Give more time since we were dexopting.
7258 mDidDexOpt = false;
7259 return -1;
7260 }
7261
7262 if (proc.instrumentationClass != null) {
7263 Bundle info = new Bundle();
7264 info.putString("shortMsg", "keyDispatchingTimedOut");
7265 info.putString("longMsg", "Timed out while dispatching key event");
7266 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7267 proc = null;
7268 }
7269 }
7270 }
7271
7272 if (proc != null) {
7273 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7274 if (proc.instrumentationClass != null || proc.usingWrapper) {
7275 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7276 }
7277 }
7278
7279 return KEY_DISPATCHING_TIMEOUT;
7280 }
7281
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007282 public Bundle getTopActivityExtras(int requestType) {
7283 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7284 "getTopActivityExtras()");
7285 PendingActivityExtras pae;
7286 Bundle extras = new Bundle();
7287 synchronized (this) {
7288 ActivityRecord activity = mMainStack.mResumedActivity;
7289 if (activity == null) {
7290 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7291 return null;
7292 }
7293 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7294 if (activity.app == null || activity.app.thread == null) {
7295 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7296 return extras;
7297 }
7298 if (activity.app.pid == Binder.getCallingPid()) {
7299 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7300 return extras;
7301 }
7302 pae = new PendingActivityExtras(activity);
7303 try {
7304 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7305 mPendingActivityExtras.add(pae);
7306 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7307 } catch (RemoteException e) {
7308 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7309 return extras;
7310 }
7311 }
7312 synchronized (pae) {
7313 while (!pae.haveResult) {
7314 try {
7315 pae.wait();
7316 } catch (InterruptedException e) {
7317 }
7318 }
7319 if (pae.result != null) {
7320 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7321 }
7322 }
7323 synchronized (this) {
7324 mPendingActivityExtras.remove(pae);
7325 mHandler.removeCallbacks(pae);
7326 }
7327 return extras;
7328 }
7329
7330 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7331 PendingActivityExtras pae = (PendingActivityExtras)token;
7332 synchronized (pae) {
7333 pae.result = extras;
7334 pae.haveResult = true;
7335 pae.notifyAll();
7336 }
7337 }
7338
Jeff Sharkeya4620792011-05-20 15:29:23 -07007339 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007340 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7341 "registerProcessObserver()");
7342 synchronized (this) {
7343 mProcessObservers.register(observer);
7344 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007345 }
7346
7347 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007348 synchronized (this) {
7349 mProcessObservers.unregister(observer);
7350 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007351 }
7352
Daniel Sandler69a48172010-06-23 16:29:36 -04007353 public void setImmersive(IBinder token, boolean immersive) {
7354 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007355 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007356 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007357 throw new IllegalArgumentException();
7358 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007359 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007360
7361 // update associated state if we're frontmost
7362 if (r == mFocusedActivity) {
7363 if (DEBUG_IMMERSIVE) {
7364 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7365 }
7366 applyUpdateLockStateLocked(r);
7367 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007368 }
7369 }
7370
7371 public boolean isImmersive(IBinder token) {
7372 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007373 ActivityRecord r = mMainStack.isInStackLocked(token);
7374 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007375 throw new IllegalArgumentException();
7376 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007377 return r.immersive;
7378 }
7379 }
7380
7381 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007382 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007383 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007384 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007385 return (r != null) ? r.immersive : false;
7386 }
7387 }
7388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 public final void enterSafeMode() {
7390 synchronized(this) {
7391 // It only makes sense to do this before the system is ready
7392 // and started launching other packages.
7393 if (!mSystemReady) {
7394 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007395 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 } catch (RemoteException e) {
7397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 }
7399 }
7400 }
7401
Jeff Brownb09abc12011-01-13 21:08:27 -08007402 public final void showSafeModeOverlay() {
7403 View v = LayoutInflater.from(mContext).inflate(
7404 com.android.internal.R.layout.safe_mode, null);
7405 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7406 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7407 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7408 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007409 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007410 lp.format = v.getBackground().getOpacity();
7411 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7412 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007413 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007414 ((WindowManager)mContext.getSystemService(
7415 Context.WINDOW_SERVICE)).addView(v, lp);
7416 }
7417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007418 public void noteWakeupAlarm(IIntentSender sender) {
7419 if (!(sender instanceof PendingIntentRecord)) {
7420 return;
7421 }
7422 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7423 synchronized (stats) {
7424 if (mBatteryStatsService.isOnBattery()) {
7425 mBatteryStatsService.enforceCallingPermission();
7426 PendingIntentRecord rec = (PendingIntentRecord)sender;
7427 int MY_UID = Binder.getCallingUid();
7428 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7429 BatteryStatsImpl.Uid.Pkg pkg =
7430 stats.getPackageStatsLocked(uid, rec.key.packageName);
7431 pkg.incWakeupsLocked();
7432 }
7433 }
7434 }
7435
Dianne Hackborn64825172011-03-02 21:32:58 -08007436 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007438 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007439 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007440 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 // XXX Note: don't acquire main activity lock here, because the window
7442 // manager calls in with its locks held.
7443
7444 boolean killed = false;
7445 synchronized (mPidsSelfLocked) {
7446 int[] types = new int[pids.length];
7447 int worstType = 0;
7448 for (int i=0; i<pids.length; i++) {
7449 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7450 if (proc != null) {
7451 int type = proc.setAdj;
7452 types[i] = type;
7453 if (type > worstType) {
7454 worstType = type;
7455 }
7456 }
7457 }
7458
Dianne Hackborn64825172011-03-02 21:32:58 -08007459 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007461 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7462 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007463 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007464 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007465
7466 // If this is not a secure call, don't let it kill processes that
7467 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007468 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7469 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007470 }
7471
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007472 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007473 for (int i=0; i<pids.length; i++) {
7474 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7475 if (proc == null) {
7476 continue;
7477 }
7478 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007479 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007480 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007481 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007482 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007484 proc.killedBackground = true;
7485 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007486 }
7487 }
7488 }
7489 return killed;
7490 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007491
7492 @Override
7493 public boolean killProcessesBelowForeground(String reason) {
7494 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7495 throw new SecurityException("killProcessesBelowForeground() only available to system");
7496 }
7497
7498 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7499 }
7500
7501 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7502 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7503 throw new SecurityException("killProcessesBelowAdj() only available to system");
7504 }
7505
7506 boolean killed = false;
7507 synchronized (mPidsSelfLocked) {
7508 final int size = mPidsSelfLocked.size();
7509 for (int i = 0; i < size; i++) {
7510 final int pid = mPidsSelfLocked.keyAt(i);
7511 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7512 if (proc == null) continue;
7513
7514 final int adj = proc.setAdj;
7515 if (adj > belowAdj && !proc.killedBackground) {
7516 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007517 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7518 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007519 killed = true;
7520 proc.killedBackground = true;
7521 Process.killProcessQuiet(pid);
7522 }
7523 }
7524 }
7525 return killed;
7526 }
7527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007528 public final void startRunning(String pkg, String cls, String action,
7529 String data) {
7530 synchronized(this) {
7531 if (mStartRunning) {
7532 return;
7533 }
7534 mStartRunning = true;
7535 mTopComponent = pkg != null && cls != null
7536 ? new ComponentName(pkg, cls) : null;
7537 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7538 mTopData = data;
7539 if (!mSystemReady) {
7540 return;
7541 }
7542 }
7543
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007544 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 }
7546
7547 private void retrieveSettings() {
7548 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007549 String debugApp = Settings.Global.getString(
7550 resolver, Settings.Global.DEBUG_APP);
7551 boolean waitForDebugger = Settings.Global.getInt(
7552 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7553 boolean alwaysFinishActivities = Settings.Global.getInt(
7554 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555
7556 Configuration configuration = new Configuration();
7557 Settings.System.getConfiguration(resolver, configuration);
7558
7559 synchronized (this) {
7560 mDebugApp = mOrigDebugApp = debugApp;
7561 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7562 mAlwaysFinishActivities = alwaysFinishActivities;
7563 // This happens before any activities are started, so we can
7564 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007565 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007566 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 }
7568 }
7569
7570 public boolean testIsSystemReady() {
7571 // no need to synchronize(this) just to read & return the value
7572 return mSystemReady;
7573 }
7574
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007575 private static File getCalledPreBootReceiversFile() {
7576 File dataDir = Environment.getDataDirectory();
7577 File systemDir = new File(dataDir, "system");
7578 File fname = new File(systemDir, "called_pre_boots.dat");
7579 return fname;
7580 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007581
7582 static final int LAST_DONE_VERSION = 10000;
7583
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007584 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7585 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7586 File file = getCalledPreBootReceiversFile();
7587 FileInputStream fis = null;
7588 try {
7589 fis = new FileInputStream(file);
7590 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007591 int fvers = dis.readInt();
7592 if (fvers == LAST_DONE_VERSION) {
7593 String vers = dis.readUTF();
7594 String codename = dis.readUTF();
7595 String build = dis.readUTF();
7596 if (android.os.Build.VERSION.RELEASE.equals(vers)
7597 && android.os.Build.VERSION.CODENAME.equals(codename)
7598 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7599 int num = dis.readInt();
7600 while (num > 0) {
7601 num--;
7602 String pkg = dis.readUTF();
7603 String cls = dis.readUTF();
7604 lastDoneReceivers.add(new ComponentName(pkg, cls));
7605 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007606 }
7607 }
7608 } catch (FileNotFoundException e) {
7609 } catch (IOException e) {
7610 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7611 } finally {
7612 if (fis != null) {
7613 try {
7614 fis.close();
7615 } catch (IOException e) {
7616 }
7617 }
7618 }
7619 return lastDoneReceivers;
7620 }
7621
7622 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7623 File file = getCalledPreBootReceiversFile();
7624 FileOutputStream fos = null;
7625 DataOutputStream dos = null;
7626 try {
7627 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7628 fos = new FileOutputStream(file);
7629 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007630 dos.writeInt(LAST_DONE_VERSION);
7631 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007632 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007633 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007634 dos.writeInt(list.size());
7635 for (int i=0; i<list.size(); i++) {
7636 dos.writeUTF(list.get(i).getPackageName());
7637 dos.writeUTF(list.get(i).getClassName());
7638 }
7639 } catch (IOException e) {
7640 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7641 file.delete();
7642 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007643 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007644 if (dos != null) {
7645 try {
7646 dos.close();
7647 } catch (IOException e) {
7648 // TODO Auto-generated catch block
7649 e.printStackTrace();
7650 }
7651 }
7652 }
7653 }
7654
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007655 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 synchronized(this) {
7657 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007658 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 return;
7660 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007661
7662 // Check to see if there are any update receivers to run.
7663 if (!mDidUpdate) {
7664 if (mWaitingUpdate) {
7665 return;
7666 }
7667 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7668 List<ResolveInfo> ris = null;
7669 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007670 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007671 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007672 } catch (RemoteException e) {
7673 }
7674 if (ris != null) {
7675 for (int i=ris.size()-1; i>=0; i--) {
7676 if ((ris.get(i).activityInfo.applicationInfo.flags
7677 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7678 ris.remove(i);
7679 }
7680 }
7681 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007682
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007683 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007684
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007685 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007686 for (int i=0; i<ris.size(); i++) {
7687 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007688 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7689 if (lastDoneReceivers.contains(comp)) {
7690 ris.remove(i);
7691 i--;
7692 }
7693 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007694
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007695 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007696 for (int i=0; i<ris.size(); i++) {
7697 ActivityInfo ai = ris.get(i).activityInfo;
7698 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7699 doneReceivers.add(comp);
7700 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007701 for (int j=0; j<users.length; j++) {
7702 IIntentReceiver finisher = null;
7703 if (i == ris.size()-1 && j == users.length-1) {
7704 finisher = new IIntentReceiver.Stub() {
7705 public void performReceive(Intent intent, int resultCode,
7706 String data, Bundle extras, boolean ordered,
7707 boolean sticky, int sendingUser) {
7708 // The raw IIntentReceiver interface is called
7709 // with the AM lock held, so redispatch to
7710 // execute our code without the lock.
7711 mHandler.post(new Runnable() {
7712 public void run() {
7713 synchronized (ActivityManagerService.this) {
7714 mDidUpdate = true;
7715 }
7716 writeLastDonePreBootReceivers(doneReceivers);
7717 showBootMessage(mContext.getText(
7718 R.string.android_upgrading_complete),
7719 false);
7720 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007721 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007722 });
7723 }
7724 };
7725 }
7726 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7727 + " for user " + users[j]);
7728 broadcastIntentLocked(null, null, intent, null, finisher,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007729 0, null, null, null, AppOpsManager.OP_NONE,
7730 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007731 users[j]);
7732 if (finisher != null) {
7733 mWaitingUpdate = true;
7734 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007735 }
7736 }
7737 }
7738 if (mWaitingUpdate) {
7739 return;
7740 }
7741 mDidUpdate = true;
7742 }
7743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 mSystemReady = true;
7745 if (!mStartRunning) {
7746 return;
7747 }
7748 }
7749
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007750 ArrayList<ProcessRecord> procsToKill = null;
7751 synchronized(mPidsSelfLocked) {
7752 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7753 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7754 if (!isAllowedWhileBooting(proc.info)){
7755 if (procsToKill == null) {
7756 procsToKill = new ArrayList<ProcessRecord>();
7757 }
7758 procsToKill.add(proc);
7759 }
7760 }
7761 }
7762
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007763 synchronized(this) {
7764 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007765 for (int i=procsToKill.size()-1; i>=0; i--) {
7766 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007767 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007768 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007769 }
7770 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007771
7772 // Now that we have cleaned up any update processes, we
7773 // are ready to start launching real processes and know that
7774 // we won't trample on them any more.
7775 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007776 }
7777
Joe Onorato8a9b2202010-02-26 18:56:32 -08007778 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007779 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 SystemClock.uptimeMillis());
7781
7782 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007783 // Make sure we have no pre-ready processes sitting around.
7784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7786 ResolveInfo ri = mContext.getPackageManager()
7787 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007788 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 CharSequence errorMsg = null;
7790 if (ri != null) {
7791 ActivityInfo ai = ri.activityInfo;
7792 ApplicationInfo app = ai.applicationInfo;
7793 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7794 mTopAction = Intent.ACTION_FACTORY_TEST;
7795 mTopData = null;
7796 mTopComponent = new ComponentName(app.packageName,
7797 ai.name);
7798 } else {
7799 errorMsg = mContext.getResources().getText(
7800 com.android.internal.R.string.factorytest_not_system);
7801 }
7802 } else {
7803 errorMsg = mContext.getResources().getText(
7804 com.android.internal.R.string.factorytest_no_action);
7805 }
7806 if (errorMsg != null) {
7807 mTopAction = null;
7808 mTopData = null;
7809 mTopComponent = null;
7810 Message msg = Message.obtain();
7811 msg.what = SHOW_FACTORY_ERROR_MSG;
7812 msg.getData().putCharSequence("msg", errorMsg);
7813 mHandler.sendMessage(msg);
7814 }
7815 }
7816 }
7817
7818 retrieveSettings();
7819
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007820 if (goingCallback != null) goingCallback.run();
7821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 synchronized (this) {
7823 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7824 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007825 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007826 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 if (apps != null) {
7828 int N = apps.size();
7829 int i;
7830 for (i=0; i<N; i++) {
7831 ApplicationInfo info
7832 = (ApplicationInfo)apps.get(i);
7833 if (info != null &&
7834 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007835 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 }
7837 }
7838 }
7839 } catch (RemoteException ex) {
7840 // pm is in same process, this will never happen.
7841 }
7842 }
7843
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007844 // Start up initial activity.
7845 mBooting = true;
7846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007848 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 Message msg = Message.obtain();
7850 msg.what = SHOW_UID_ERROR_MSG;
7851 mHandler.sendMessage(msg);
7852 }
7853 } catch (RemoteException e) {
7854 }
7855
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007856 long ident = Binder.clearCallingIdentity();
7857 try {
7858 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007859 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7860 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007861 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7862 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007863 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007864 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007865 intent = new Intent(Intent.ACTION_USER_STARTING);
7866 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7867 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7868 broadcastIntentLocked(null, null, intent,
7869 null, new IIntentReceiver.Stub() {
7870 @Override
7871 public void performReceive(Intent intent, int resultCode, String data,
7872 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7873 throws RemoteException {
7874 }
7875 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007876 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007877 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007878 } finally {
7879 Binder.restoreCallingIdentity(ident);
7880 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007881 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007882 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 }
7884 }
7885
Dan Egnorb7f03672009-12-09 16:22:32 -08007886 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007887 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007888 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007889 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007890 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 startAppProblemLocked(app);
7892 app.stopFreezingAllLocked();
7893 return handleAppCrashLocked(app);
7894 }
7895
Dan Egnorb7f03672009-12-09 16:22:32 -08007896 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007897 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007899 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007900 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7901 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 startAppProblemLocked(app);
7903 app.stopFreezingAllLocked();
7904 }
7905
7906 /**
7907 * Generate a process error record, suitable for attachment to a ProcessRecord.
7908 *
7909 * @param app The ProcessRecord in which the error occurred.
7910 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7911 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007912 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007913 * @param shortMsg Short message describing the crash.
7914 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007915 * @param stackTrace Full crash stack trace, may be null.
7916 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 * @return Returns a fully-formed AppErrorStateInfo record.
7918 */
7919 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007920 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 report.condition = condition;
7924 report.processName = app.processName;
7925 report.pid = app.pid;
7926 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007927 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 report.shortMsg = shortMsg;
7929 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007930 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931
7932 return report;
7933 }
7934
Dan Egnor42471dd2010-01-07 17:25:22 -08007935 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 synchronized (this) {
7937 app.crashing = false;
7938 app.crashingReport = null;
7939 app.notResponding = false;
7940 app.notRespondingReport = null;
7941 if (app.anrDialog == fromDialog) {
7942 app.anrDialog = null;
7943 }
7944 if (app.waitDialog == fromDialog) {
7945 app.waitDialog = null;
7946 }
7947 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007948 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007949 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007950 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07007951 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007952 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 }
7955 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007956
Dan Egnorb7f03672009-12-09 16:22:32 -08007957 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007958 if (mHeadless) {
7959 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7960 return false;
7961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 long now = SystemClock.uptimeMillis();
7963
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007964 Long crashTime;
7965 if (!app.isolated) {
7966 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7967 } else {
7968 crashTime = null;
7969 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007970 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007972 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007973 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007974 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007975 app.userId, app.info.processName, app.uid);
Craig Mautnercae015f2013-02-08 14:31:27 -08007976 mMainStack.handleAppCrashLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 if (!app.persistent) {
7978 // We don't want to start this process again until the user
7979 // explicitly does so... but for persistent process, we really
7980 // need to keep it running. If a persistent process is actually
7981 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007982 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007984 if (!app.isolated) {
7985 // XXX We don't have a way to mark isolated processes
7986 // as bad, since they don't have a peristent identity.
7987 mBadProcesses.put(app.info.processName, app.uid, now);
7988 mProcessCrashTimes.remove(app.info.processName, app.uid);
7989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007992 // Don't let services in this process be restarted and potentially
7993 // annoy the user repeatedly. Unless it is persistent, since those
7994 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007995 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007996 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 return false;
7998 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007999 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008000 } else {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08008001 mMainStack.finishTopRunningActivityLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 }
8003
8004 // Bump up the crash count of any services currently running in the proc.
8005 if (app.services.size() != 0) {
8006 // Any services running in the application need to be placed
8007 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008008 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008010 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008011 sr.crashCount++;
8012 }
8013 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008014
8015 // If the crashing process is what we consider to be the "home process" and it has been
8016 // replaced by a third-party app, clear the package preferred activities from packages
8017 // with a home activity running in the process to prevent a repeatedly crashing app
8018 // from blocking the user to manually clear the list.
8019 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8020 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8021 Iterator it = mHomeProcess.activities.iterator();
8022 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008023 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008024 if (r.isHomeActivity) {
8025 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8026 try {
8027 ActivityThread.getPackageManager()
8028 .clearPackagePreferredActivities(r.packageName);
8029 } catch (RemoteException c) {
8030 // pm is in same process, this will never happen.
8031 }
8032 }
8033 }
8034 }
8035
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008036 if (!app.isolated) {
8037 // XXX Can't keep track of crash times for isolated processes,
8038 // because they don't have a perisistent identity.
8039 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8040 }
8041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 return true;
8043 }
8044
8045 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008046 if (app.userId == mCurrentUserId) {
8047 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8048 mContext, app.info.packageName, app.info.flags);
8049 } else {
8050 // If this app is not running under the current user, then we
8051 // can't give it a report button because that would require
8052 // launching the report UI under a different user.
8053 app.errorReportReceiver = null;
8054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 skipCurrentReceiverLocked(app);
8056 }
8057
8058 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008059 for (BroadcastQueue queue : mBroadcastQueues) {
8060 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008061 }
8062 }
8063
Dan Egnor60d87622009-12-16 16:32:58 -08008064 /**
8065 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8066 * The application process will exit immediately after this call returns.
8067 * @param app object of the crashing app, null for the system server
8068 * @param crashInfo describing the exception
8069 */
8070 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008071 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008072 final String processName = app == null ? "system_server"
8073 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008074
8075 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008076 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008077 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008078 crashInfo.exceptionClassName,
8079 crashInfo.exceptionMessage,
8080 crashInfo.throwFileName,
8081 crashInfo.throwLineNumber);
8082
Jeff Sharkeya353d262011-10-28 11:12:06 -07008083 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008084
8085 crashApplication(r, crashInfo);
8086 }
8087
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008088 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008089 IBinder app,
8090 int violationMask,
8091 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008092 ProcessRecord r = findAppProcess(app, "StrictMode");
8093 if (r == null) {
8094 return;
8095 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008096
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008097 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008098 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008099 boolean logIt = true;
8100 synchronized (mAlreadyLoggedViolatedStacks) {
8101 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8102 logIt = false;
8103 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008104 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008105 // the relative pain numbers, without logging all
8106 // the stack traces repeatedly. We'd want to do
8107 // likewise in the client code, which also does
8108 // dup suppression, before the Binder call.
8109 } else {
8110 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8111 mAlreadyLoggedViolatedStacks.clear();
8112 }
8113 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8114 }
8115 }
8116 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008117 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008118 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008119 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008120
8121 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8122 AppErrorResult result = new AppErrorResult();
8123 synchronized (this) {
8124 final long origId = Binder.clearCallingIdentity();
8125
8126 Message msg = Message.obtain();
8127 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8128 HashMap<String, Object> data = new HashMap<String, Object>();
8129 data.put("result", result);
8130 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008131 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008132 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008133 msg.obj = data;
8134 mHandler.sendMessage(msg);
8135
8136 Binder.restoreCallingIdentity(origId);
8137 }
8138 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008139 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008140 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008141 }
8142
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008143 // Depending on the policy in effect, there could be a bunch of
8144 // these in quick succession so we try to batch these together to
8145 // minimize disk writes, number of dropbox entries, and maximize
8146 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008147 private void logStrictModeViolationToDropBox(
8148 ProcessRecord process,
8149 StrictMode.ViolationInfo info) {
8150 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008151 return;
8152 }
8153 final boolean isSystemApp = process == null ||
8154 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8155 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008156 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008157 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8158 final DropBoxManager dbox = (DropBoxManager)
8159 mContext.getSystemService(Context.DROPBOX_SERVICE);
8160
8161 // Exit early if the dropbox isn't configured to accept this report type.
8162 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8163
8164 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008165 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008166 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8167 synchronized (sb) {
8168 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008169 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008170 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8171 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008172 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8173 if (info.violationNumThisLoop != 0) {
8174 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8175 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008176 if (info.numAnimationsRunning != 0) {
8177 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8178 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008179 if (info.broadcastIntentAction != null) {
8180 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8181 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008182 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008183 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008184 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008185 if (info.numInstances != -1) {
8186 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8187 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008188 if (info.tags != null) {
8189 for (String tag : info.tags) {
8190 sb.append("Span-Tag: ").append(tag).append("\n");
8191 }
8192 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008193 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008194 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8195 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008196 }
8197 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008198
8199 // Only buffer up to ~64k. Various logging bits truncate
8200 // things at 128k.
8201 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008202 }
8203
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008204 // Flush immediately if the buffer's grown too large, or this
8205 // is a non-system app. Non-system apps are isolated with a
8206 // different tag & policy and not batched.
8207 //
8208 // Batching is useful during internal testing with
8209 // StrictMode settings turned up high. Without batching,
8210 // thousands of separate files could be created on boot.
8211 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008212 new Thread("Error dump: " + dropboxTag) {
8213 @Override
8214 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008215 String report;
8216 synchronized (sb) {
8217 report = sb.toString();
8218 sb.delete(0, sb.length());
8219 sb.trimToSize();
8220 }
8221 if (report.length() != 0) {
8222 dbox.addText(dropboxTag, report);
8223 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008224 }
8225 }.start();
8226 return;
8227 }
8228
8229 // System app batching:
8230 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008231 // An existing dropbox-writing thread is outstanding, so
8232 // we don't need to start it up. The existing thread will
8233 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008234 return;
8235 }
8236
8237 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8238 // (After this point, we shouldn't access AMS internal data structures.)
8239 new Thread("Error dump: " + dropboxTag) {
8240 @Override
8241 public void run() {
8242 // 5 second sleep to let stacks arrive and be batched together
8243 try {
8244 Thread.sleep(5000); // 5 seconds
8245 } catch (InterruptedException e) {}
8246
8247 String errorReport;
8248 synchronized (mStrictModeBuffer) {
8249 errorReport = mStrictModeBuffer.toString();
8250 if (errorReport.length() == 0) {
8251 return;
8252 }
8253 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8254 mStrictModeBuffer.trimToSize();
8255 }
8256 dbox.addText(dropboxTag, errorReport);
8257 }
8258 }.start();
8259 }
8260
Dan Egnor60d87622009-12-16 16:32:58 -08008261 /**
8262 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8263 * @param app object of the crashing app, null for the system server
8264 * @param tag reported by the caller
8265 * @param crashInfo describing the context of the error
8266 * @return true if the process should exit immediately (WTF is fatal)
8267 */
8268 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008269 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008270 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008271 final String processName = app == null ? "system_server"
8272 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008273
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008274 EventLog.writeEvent(EventLogTags.AM_WTF,
8275 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008276 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008277 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008278 tag, crashInfo.exceptionMessage);
8279
Jeff Sharkeya353d262011-10-28 11:12:06 -07008280 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008281
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008282 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008283 Settings.Global.getInt(mContext.getContentResolver(),
8284 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008285 crashApplication(r, crashInfo);
8286 return true;
8287 } else {
8288 return false;
8289 }
8290 }
8291
8292 /**
8293 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8294 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8295 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008296 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008297 if (app == null) {
8298 return null;
8299 }
8300
8301 synchronized (this) {
8302 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8303 final int NA = apps.size();
8304 for (int ia=0; ia<NA; ia++) {
8305 ProcessRecord p = apps.valueAt(ia);
8306 if (p.thread != null && p.thread.asBinder() == app) {
8307 return p;
8308 }
8309 }
8310 }
8311
Dianne Hackborncb44d962011-03-10 17:02:27 -08008312 Slog.w(TAG, "Can't find mystery application for " + reason
8313 + " from pid=" + Binder.getCallingPid()
8314 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008315 return null;
8316 }
8317 }
8318
8319 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008320 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8321 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008322 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008323 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8324 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008325 // Watchdog thread ends up invoking this function (with
8326 // a null ProcessRecord) to add the stack file to dropbox.
8327 // Do not acquire a lock on this (am) in such cases, as it
8328 // could cause a potential deadlock, if and when watchdog
8329 // is invoked due to unavailability of lock on am and it
8330 // would prevent watchdog from killing system_server.
8331 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008332 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008333 return;
8334 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008335 // Note: ProcessRecord 'process' is guarded by the service
8336 // instance. (notably process.pkgList, which could otherwise change
8337 // concurrently during execution of this method)
8338 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008339 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008340 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008341 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008342 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8343 for (String pkg : process.pkgList) {
8344 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008345 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008346 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008347 if (pi != null) {
8348 sb.append(" v").append(pi.versionCode);
8349 if (pi.versionName != null) {
8350 sb.append(" (").append(pi.versionName).append(")");
8351 }
8352 }
8353 } catch (RemoteException e) {
8354 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008355 }
Dan Egnora455d192010-03-12 08:52:28 -08008356 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008357 }
Dan Egnora455d192010-03-12 08:52:28 -08008358 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008359 }
8360
8361 private static String processClass(ProcessRecord process) {
8362 if (process == null || process.pid == MY_PID) {
8363 return "system_server";
8364 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8365 return "system_app";
8366 } else {
8367 return "data_app";
8368 }
8369 }
8370
8371 /**
8372 * Write a description of an error (crash, WTF, ANR) to the drop box.
8373 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8374 * @param process which caused the error, null means the system server
8375 * @param activity which triggered the error, null if unknown
8376 * @param parent activity related to the error, null if unknown
8377 * @param subject line related to the error, null if absent
8378 * @param report in long form describing the error, null if absent
8379 * @param logFile to include in the report, null if none
8380 * @param crashInfo giving an application stack trace, null if absent
8381 */
8382 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008383 ProcessRecord process, String processName, ActivityRecord activity,
8384 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008385 final String report, final File logFile,
8386 final ApplicationErrorReport.CrashInfo crashInfo) {
8387 // NOTE -- this must never acquire the ActivityManagerService lock,
8388 // otherwise the watchdog may be prevented from resetting the system.
8389
8390 final String dropboxTag = processClass(process) + "_" + eventType;
8391 final DropBoxManager dbox = (DropBoxManager)
8392 mContext.getSystemService(Context.DROPBOX_SERVICE);
8393
8394 // Exit early if the dropbox isn't configured to accept this report type.
8395 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8396
8397 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008398 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008399 if (activity != null) {
8400 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8401 }
8402 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8403 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8404 }
8405 if (parent != null && parent != activity) {
8406 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8407 }
8408 if (subject != null) {
8409 sb.append("Subject: ").append(subject).append("\n");
8410 }
8411 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008412 if (Debug.isDebuggerConnected()) {
8413 sb.append("Debugger: Connected\n");
8414 }
Dan Egnora455d192010-03-12 08:52:28 -08008415 sb.append("\n");
8416
8417 // Do the rest in a worker thread to avoid blocking the caller on I/O
8418 // (After this point, we shouldn't access AMS internal data structures.)
8419 Thread worker = new Thread("Error dump: " + dropboxTag) {
8420 @Override
8421 public void run() {
8422 if (report != null) {
8423 sb.append(report);
8424 }
8425 if (logFile != null) {
8426 try {
8427 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8428 } catch (IOException e) {
8429 Slog.e(TAG, "Error reading " + logFile, e);
8430 }
8431 }
8432 if (crashInfo != null && crashInfo.stackTrace != null) {
8433 sb.append(crashInfo.stackTrace);
8434 }
8435
Jeff Sharkey625239a2012-09-26 22:03:49 -07008436 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8437 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008438 if (lines > 0) {
8439 sb.append("\n");
8440
8441 // Merge several logcat streams, and take the last N lines
8442 InputStreamReader input = null;
8443 try {
8444 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8445 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8446 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8447
8448 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8449 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8450 input = new InputStreamReader(logcat.getInputStream());
8451
8452 int num;
8453 char[] buf = new char[8192];
8454 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8455 } catch (IOException e) {
8456 Slog.e(TAG, "Error running logcat", e);
8457 } finally {
8458 if (input != null) try { input.close(); } catch (IOException e) {}
8459 }
8460 }
8461
8462 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008463 }
Dan Egnora455d192010-03-12 08:52:28 -08008464 };
8465
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008466 if (process == null) {
8467 // If process is null, we are being called from some internal code
8468 // and may be about to die -- run this synchronously.
8469 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008470 } else {
8471 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008472 }
8473 }
8474
8475 /**
8476 * Bring up the "unexpected error" dialog box for a crashing app.
8477 * Deal with edge cases (intercepts from instrumented applications,
8478 * ActivityController, error intent receivers, that sort of thing).
8479 * @param r the application crashing
8480 * @param crashInfo describing the failure
8481 */
8482 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008483 long timeMillis = System.currentTimeMillis();
8484 String shortMsg = crashInfo.exceptionClassName;
8485 String longMsg = crashInfo.exceptionMessage;
8486 String stackTrace = crashInfo.stackTrace;
8487 if (shortMsg != null && longMsg != null) {
8488 longMsg = shortMsg + ": " + longMsg;
8489 } else if (shortMsg != null) {
8490 longMsg = shortMsg;
8491 }
8492
Dan Egnor60d87622009-12-16 16:32:58 -08008493 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008495 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 try {
8497 String name = r != null ? r.processName : null;
8498 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008499 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008500 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008501 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 + " at watcher's request");
8503 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008504 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 }
8506 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008507 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 }
8509 }
8510
8511 final long origId = Binder.clearCallingIdentity();
8512
8513 // If this process is running instrumentation, finish it.
8514 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008515 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008517 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8518 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008519 Bundle info = new Bundle();
8520 info.putString("shortMsg", shortMsg);
8521 info.putString("longMsg", longMsg);
8522 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8523 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008524 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 }
8526
Dan Egnor60d87622009-12-16 16:32:58 -08008527 // If we can't identify the process or it's already exceeded its crash quota,
8528 // quit right away without showing a crash dialog.
8529 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008531 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008532 }
8533
8534 Message msg = Message.obtain();
8535 msg.what = SHOW_ERROR_MSG;
8536 HashMap data = new HashMap();
8537 data.put("result", result);
8538 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 msg.obj = data;
8540 mHandler.sendMessage(msg);
8541
8542 Binder.restoreCallingIdentity(origId);
8543 }
8544
8545 int res = result.get();
8546
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008547 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008549 if (r != null && !r.isolated) {
8550 // XXX Can't keep track of crash time for isolated processes,
8551 // since they don't have a persistent identity.
8552 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 SystemClock.uptimeMillis());
8554 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008555 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008556 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008557 }
8558 }
8559
8560 if (appErrorIntent != null) {
8561 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008562 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008563 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008564 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008568
8569 Intent createAppErrorIntentLocked(ProcessRecord r,
8570 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8571 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008572 if (report == null) {
8573 return null;
8574 }
8575 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8576 result.setComponent(r.errorReportReceiver);
8577 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8578 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8579 return result;
8580 }
8581
Dan Egnorb7f03672009-12-09 16:22:32 -08008582 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8583 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008584 if (r.errorReportReceiver == null) {
8585 return null;
8586 }
8587
8588 if (!r.crashing && !r.notResponding) {
8589 return null;
8590 }
8591
Dan Egnorb7f03672009-12-09 16:22:32 -08008592 ApplicationErrorReport report = new ApplicationErrorReport();
8593 report.packageName = r.info.packageName;
8594 report.installerPackageName = r.errorReportReceiver.getPackageName();
8595 report.processName = r.processName;
8596 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008597 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008598
Dan Egnorb7f03672009-12-09 16:22:32 -08008599 if (r.crashing) {
8600 report.type = ApplicationErrorReport.TYPE_CRASH;
8601 report.crashInfo = crashInfo;
8602 } else if (r.notResponding) {
8603 report.type = ApplicationErrorReport.TYPE_ANR;
8604 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008605
Dan Egnorb7f03672009-12-09 16:22:32 -08008606 report.anrInfo.activity = r.notRespondingReport.tag;
8607 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8608 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008609 }
8610
Dan Egnorb7f03672009-12-09 16:22:32 -08008611 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008612 }
8613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008615 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 // assume our apps are happy - lazy create the list
8617 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8618
Dianne Hackborn0c380492012-08-20 17:23:30 -07008619 final boolean allUsers = ActivityManager.checkUidPermission(
8620 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8621 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8622 int userId = UserHandle.getUserId(Binder.getCallingUid());
8623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 synchronized (this) {
8625
8626 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008627 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8628 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008629 if (!allUsers && app.userId != userId) {
8630 continue;
8631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8633 // This one's in trouble, so we'll generate a report for it
8634 // crashes are higher priority (in case there's a crash *and* an anr)
8635 ActivityManager.ProcessErrorStateInfo report = null;
8636 if (app.crashing) {
8637 report = app.crashingReport;
8638 } else if (app.notResponding) {
8639 report = app.notRespondingReport;
8640 }
8641
8642 if (report != null) {
8643 if (errList == null) {
8644 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8645 }
8646 errList.add(report);
8647 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008648 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 " crashing = " + app.crashing +
8650 " notResponding = " + app.notResponding);
8651 }
8652 }
8653 }
8654 }
8655
8656 return errList;
8657 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008658
8659 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008660 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008661 if (currApp != null) {
8662 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8663 }
8664 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008665 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8666 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008667 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8668 if (currApp != null) {
8669 currApp.lru = 0;
8670 }
8671 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008672 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008673 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8674 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8675 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8676 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8677 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8678 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8679 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8680 } else {
8681 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8682 }
8683 }
8684
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008685 private void fillInProcMemInfo(ProcessRecord app,
8686 ActivityManager.RunningAppProcessInfo outInfo) {
8687 outInfo.pid = app.pid;
8688 outInfo.uid = app.info.uid;
8689 if (mHeavyWeightProcess == app) {
8690 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8691 }
8692 if (app.persistent) {
8693 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8694 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008695 if (app.hasActivities) {
8696 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8697 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008698 outInfo.lastTrimLevel = app.trimMemoryLevel;
8699 int adj = app.curAdj;
8700 outInfo.importance = oomAdjToImportance(adj, outInfo);
8701 outInfo.importanceReasonCode = app.adjTypeCode;
8702 }
8703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008705 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 // Lazy instantiation of list
8707 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008708 final boolean allUsers = ActivityManager.checkUidPermission(
8709 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8710 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8711 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 synchronized (this) {
8713 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008714 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8715 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008716 if (!allUsers && app.userId != userId) {
8717 continue;
8718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8720 // Generate process state info for running application
8721 ActivityManager.RunningAppProcessInfo currApp =
8722 new ActivityManager.RunningAppProcessInfo(app.processName,
8723 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008724 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008725 if (app.adjSource instanceof ProcessRecord) {
8726 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008727 currApp.importanceReasonImportance = oomAdjToImportance(
8728 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008729 } else if (app.adjSource instanceof ActivityRecord) {
8730 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008731 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8732 }
8733 if (app.adjTarget instanceof ComponentName) {
8734 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8735 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008736 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 // + " lru=" + currApp.lru);
8738 if (runList == null) {
8739 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8740 }
8741 runList.add(currApp);
8742 }
8743 }
8744 }
8745 return runList;
8746 }
8747
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008748 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008749 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008750 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8751 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8752 if (runningApps != null && runningApps.size() > 0) {
8753 Set<String> extList = new HashSet<String>();
8754 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8755 if (app.pkgList != null) {
8756 for (String pkg : app.pkgList) {
8757 extList.add(pkg);
8758 }
8759 }
8760 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008761 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008762 for (String pkg : extList) {
8763 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008764 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008765 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8766 retList.add(info);
8767 }
8768 } catch (RemoteException e) {
8769 }
8770 }
8771 }
8772 return retList;
8773 }
8774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008776 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8777 enforceNotIsolatedCaller("getMyMemoryState");
8778 synchronized (this) {
8779 ProcessRecord proc;
8780 synchronized (mPidsSelfLocked) {
8781 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8782 }
8783 fillInProcMemInfo(proc, outInfo);
8784 }
8785 }
8786
8787 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008789 if (checkCallingPermission(android.Manifest.permission.DUMP)
8790 != PackageManager.PERMISSION_GRANTED) {
8791 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8792 + Binder.getCallingPid()
8793 + ", uid=" + Binder.getCallingUid()
8794 + " without permission "
8795 + android.Manifest.permission.DUMP);
8796 return;
8797 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008798
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008799 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008800 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008801 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008802
8803 int opti = 0;
8804 while (opti < args.length) {
8805 String opt = args[opti];
8806 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8807 break;
8808 }
8809 opti++;
8810 if ("-a".equals(opt)) {
8811 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008812 } else if ("-c".equals(opt)) {
8813 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008814 } else if ("-h".equals(opt)) {
8815 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008816 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008818 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008819 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8821 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008822 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008823 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008824 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008825 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008826 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008827 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008828 pw.println(" all: dump all activities");
8829 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008830 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008831 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8832 pw.println(" a partial substring in a component name, a");
8833 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008834 pw.println(" -a: include all available server state.");
8835 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008837 } else {
8838 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008839 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008841
8842 long origId = Binder.clearCallingIdentity();
8843 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008844 // Is the caller requesting to dump a particular piece of data?
8845 if (opti < args.length) {
8846 String cmd = args[opti];
8847 opti++;
8848 if ("activities".equals(cmd) || "a".equals(cmd)) {
8849 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008850 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008851 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 String[] newArgs;
8854 String name;
8855 if (opti >= args.length) {
8856 name = null;
8857 newArgs = EMPTY_STRING_ARRAY;
8858 } else {
8859 name = args[opti];
8860 opti++;
8861 newArgs = new String[args.length - opti];
8862 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8863 args.length - opti);
8864 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008865 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008867 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008868 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008869 String[] newArgs;
8870 String name;
8871 if (opti >= args.length) {
8872 name = null;
8873 newArgs = EMPTY_STRING_ARRAY;
8874 } else {
8875 name = args[opti];
8876 opti++;
8877 newArgs = new String[args.length - opti];
8878 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8879 args.length - opti);
8880 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008882 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008885 String[] newArgs;
8886 String name;
8887 if (opti >= args.length) {
8888 name = null;
8889 newArgs = EMPTY_STRING_ARRAY;
8890 } else {
8891 name = args[opti];
8892 opti++;
8893 newArgs = new String[args.length - opti];
8894 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8895 args.length - opti);
8896 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008898 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008900 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8901 synchronized (this) {
8902 dumpOomLocked(fd, pw, args, opti, true);
8903 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008904 } else if ("provider".equals(cmd)) {
8905 String[] newArgs;
8906 String name;
8907 if (opti >= args.length) {
8908 name = null;
8909 newArgs = EMPTY_STRING_ARRAY;
8910 } else {
8911 name = args[opti];
8912 opti++;
8913 newArgs = new String[args.length - opti];
8914 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8915 }
8916 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8917 pw.println("No providers match: " + name);
8918 pw.println("Use -h for help.");
8919 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8921 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008922 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008925 String[] newArgs;
8926 String name;
8927 if (opti >= args.length) {
8928 name = null;
8929 newArgs = EMPTY_STRING_ARRAY;
8930 } else {
8931 name = args[opti];
8932 opti++;
8933 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008934 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8935 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008936 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008937 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008938 pw.println("No services match: " + name);
8939 pw.println("Use -h for help.");
8940 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008941 } else if ("package".equals(cmd)) {
8942 String[] newArgs;
8943 if (opti >= args.length) {
8944 pw.println("package: no package name specified");
8945 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008946 } else {
8947 dumpPackage = args[opti];
8948 opti++;
8949 newArgs = new String[args.length - opti];
8950 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8951 args.length - opti);
8952 args = newArgs;
8953 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008954 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008956 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8957 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008958 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008959 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008960 } else {
8961 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008962 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8963 pw.println("Bad activity command, or no activities match: " + cmd);
8964 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008965 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008966 }
8967 if (!more) {
8968 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008969 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008971 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008972
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008973 // No piece of data specified, dump everything.
8974 synchronized (this) {
8975 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 if (needSep) {
8978 pw.println(" ");
8979 }
8980 if (dumpAll) {
8981 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008983 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008984 if (needSep) {
8985 pw.println(" ");
8986 }
8987 if (dumpAll) {
8988 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008989 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008990 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008991 if (needSep) {
8992 pw.println(" ");
8993 }
8994 if (dumpAll) {
8995 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008996 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008997 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008998 if (needSep) {
8999 pw.println(" ");
9000 }
9001 if (dumpAll) {
9002 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 if (needSep) {
9006 pw.println(" ");
9007 }
9008 if (dumpAll) {
9009 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009011 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009012 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009013 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009014 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009015
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009018 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9019 pw.println(" Main stack:");
Craig Mautnercae015f2013-02-08 14:31:27 -08009020 mMainStack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009021 pw.println(" ");
9022 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009023 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9024 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009025 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009029 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009031 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009033 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009034 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009037 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9038 pw.println(" ");
9039 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009040 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009041 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009042 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009043 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 pw.println(" ");
9045 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009050 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009051 if (mMainStack.mPausingActivity != null) {
9052 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009053 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009054 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009056 if (dumpAll) {
9057 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9058 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009059 pw.println(" mDismissKeyguardOnNextActivity: "
9060 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009062
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009063 if (mRecentTasks.size() > 0) {
9064 pw.println();
9065 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066
9067 final int N = mRecentTasks.size();
9068 for (int i=0; i<N; i++) {
9069 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 if (dumpPackage != null) {
9071 if (tr.realActivity == null ||
9072 !dumpPackage.equals(tr.realActivity)) {
9073 continue;
9074 }
9075 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009076 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9077 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009078 if (dumpAll) {
9079 mRecentTasks.get(i).dump(pw, " ");
9080 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081 }
9082 }
9083
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009084 if (dumpAll) {
9085 pw.println(" ");
9086 pw.println(" mCurTask: " + mCurTask);
9087 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088
9089 return true;
9090 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009091
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009093 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 boolean needSep = false;
9095 int numPers = 0;
9096
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009097 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9098
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9101 final int NA = procs.size();
9102 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009103 ProcessRecord r = procs.valueAt(ia);
9104 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9105 continue;
9106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 if (!needSep) {
9108 pw.println(" All known processes:");
9109 needSep = true;
9110 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009111 pw.print(r.persistent ? " *PERS*" : " *APP*");
9112 pw.print(" UID "); pw.print(procs.keyAt(ia));
9113 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009114 r.dump(pw, " ");
9115 if (r.persistent) {
9116 numPers++;
9117 }
9118 }
9119 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009121
9122 if (mIsolatedProcesses.size() > 0) {
9123 if (needSep) pw.println(" ");
9124 needSep = true;
9125 pw.println(" Isolated process list (sorted by uid):");
9126 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9127 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9128 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9129 continue;
9130 }
9131 pw.println(String.format("%sIsolated #%2d: %s",
9132 " ", i, r.toString()));
9133 }
9134 }
9135
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 if (mLruProcesses.size() > 0) {
9137 if (needSep) pw.println(" ");
9138 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009139 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009140 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009141 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009142 needSep = true;
9143 }
9144
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 if (dumpAll) {
9146 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009147 boolean printed = false;
9148 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9149 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9150 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9151 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009153 if (!printed) {
9154 if (needSep) pw.println(" ");
9155 needSep = true;
9156 pw.println(" PID mappings:");
9157 printed = true;
9158 }
9159 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9160 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 }
9162 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009163 }
9164
9165 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009166 synchronized (mPidsSelfLocked) {
9167 boolean printed = false;
9168 for (int i=0; i<mForegroundProcesses.size(); i++) {
9169 ProcessRecord r = mPidsSelfLocked.get(
9170 mForegroundProcesses.valueAt(i).pid);
9171 if (dumpPackage != null && (r == null
9172 || !dumpPackage.equals(r.info.packageName))) {
9173 continue;
9174 }
9175 if (!printed) {
9176 if (needSep) pw.println(" ");
9177 needSep = true;
9178 pw.println(" Foreground Processes:");
9179 printed = true;
9180 }
9181 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9182 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009184 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009185 }
9186
9187 if (mPersistentStartingProcesses.size() > 0) {
9188 if (needSep) pw.println(" ");
9189 needSep = true;
9190 pw.println(" Persisent processes that are starting:");
9191 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009192 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009195 if (mRemovedProcesses.size() > 0) {
9196 if (needSep) pw.println(" ");
9197 needSep = true;
9198 pw.println(" Processes that are being removed:");
9199 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009200 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009201 }
9202
9203 if (mProcessesOnHold.size() > 0) {
9204 if (needSep) pw.println(" ");
9205 needSep = true;
9206 pw.println(" Processes that are on old until the system is ready:");
9207 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009208 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009210
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009211 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212
9213 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009214 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009215 long now = SystemClock.uptimeMillis();
9216 for (Map.Entry<String, SparseArray<Long>> procs
9217 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009218 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009219 SparseArray<Long> uids = procs.getValue();
9220 final int N = uids.size();
9221 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009222 int puid = uids.keyAt(i);
9223 ProcessRecord r = mProcessNames.get(pname, puid);
9224 if (dumpPackage != null && (r == null
9225 || !dumpPackage.equals(r.info.packageName))) {
9226 continue;
9227 }
9228 if (!printed) {
9229 if (needSep) pw.println(" ");
9230 needSep = true;
9231 pw.println(" Time since processes crashed:");
9232 printed = true;
9233 }
9234 pw.print(" Process "); pw.print(pname);
9235 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009236 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009237 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9238 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009239 }
9240 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009244 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009245 for (Map.Entry<String, SparseArray<Long>> procs
9246 : mBadProcesses.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(" Bad processes:");
9261 }
9262 pw.print(" Bad process "); pw.print(pname);
9263 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 pw.print(": crashed at time ");
9265 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 }
9267 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009271 pw.println(" mStartedUsers:");
9272 for (int i=0; i<mStartedUsers.size(); i++) {
9273 UserStartedState uss = mStartedUsers.valueAt(i);
9274 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009275 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009276 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009277 pw.print(" mStartedUserArray: [");
9278 for (int i=0; i<mStartedUserArray.length; i++) {
9279 if (i > 0) pw.print(", ");
9280 pw.print(mStartedUserArray[i]);
9281 }
9282 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009283 pw.print(" mUserLru: [");
9284 for (int i=0; i<mUserLru.size(); i++) {
9285 if (i > 0) pw.print(", ");
9286 pw.print(mUserLru.get(i));
9287 }
9288 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009289 if (dumpAll) {
9290 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9291 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009293 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009294 if (dumpAll) {
9295 StringBuilder sb = new StringBuilder(128);
9296 sb.append(" mPreviousProcessVisibleTime: ");
9297 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9298 pw.println(sb);
9299 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009300 if (mHeavyWeightProcess != null) {
9301 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009304 if (dumpAll) {
9305 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009306 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009307 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009308 for (Map.Entry<String, Integer> entry
9309 : mCompatModePackages.getPackages().entrySet()) {
9310 String pkg = entry.getKey();
9311 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009312 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9313 continue;
9314 }
9315 if (!printed) {
9316 pw.println(" mScreenCompatPackages:");
9317 printed = true;
9318 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009319 pw.print(" "); pw.print(pkg); pw.print(": ");
9320 pw.print(mode); pw.println();
9321 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009322 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009323 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009324 if (mSleeping || mWentToSleep || mLockScreenShown) {
9325 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9326 + " mLockScreenShown " + mLockScreenShown);
9327 }
9328 if (mShuttingDown) {
9329 pw.println(" mShuttingDown=" + mShuttingDown);
9330 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9332 || mOrigWaitForDebugger) {
9333 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9334 + " mDebugTransient=" + mDebugTransient
9335 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9336 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009337 if (mOpenGlTraceApp != null) {
9338 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9339 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009340 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9341 || mProfileFd != null) {
9342 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9343 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9344 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9345 + mAutoStopProfiler);
9346 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009347 if (mAlwaysFinishActivities || mController != null) {
9348 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9349 + " mController=" + mController);
9350 }
9351 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009354 + " mProcessesReady=" + mProcessesReady
9355 + " mSystemReady=" + mSystemReady);
9356 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 + " mBooted=" + mBooted
9358 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009359 pw.print(" mLastPowerCheckRealtime=");
9360 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9361 pw.println("");
9362 pw.print(" mLastPowerCheckUptime=");
9363 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9364 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009365 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9366 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009367 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009368 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9369 + " mNumHiddenProcs=" + mNumHiddenProcs
9370 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009371 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009373
9374 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009375 }
9376
Dianne Hackborn287952c2010-09-22 22:34:31 -07009377 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009378 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009379 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009380 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009381 long now = SystemClock.uptimeMillis();
9382 for (int i=0; i<mProcessesToGc.size(); i++) {
9383 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009384 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9385 continue;
9386 }
9387 if (!printed) {
9388 if (needSep) pw.println(" ");
9389 needSep = true;
9390 pw.println(" Processes that are waiting to GC:");
9391 printed = true;
9392 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009393 pw.print(" Process "); pw.println(proc);
9394 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9395 pw.print(", last gced=");
9396 pw.print(now-proc.lastRequestedGc);
9397 pw.print(" ms ago, last lowMem=");
9398 pw.print(now-proc.lastLowMemory);
9399 pw.println(" ms ago");
9400
9401 }
9402 }
9403 return needSep;
9404 }
9405
9406 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9407 int opti, boolean dumpAll) {
9408 boolean needSep = false;
9409
9410 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009411 if (needSep) pw.println(" ");
9412 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009413 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009414 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009415 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009416 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9417 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9418 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9419 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9420 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009421 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009422 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009423 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009424 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009425 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009426 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009427
9428 if (needSep) pw.println(" ");
9429 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009430 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009431 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009432 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009433 needSep = true;
9434 }
9435
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009436 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009437
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009438 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009439 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009440 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009441 if (mHeavyWeightProcess != null) {
9442 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9443 }
9444
9445 return true;
9446 }
9447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009448 /**
9449 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009450 * - no provider specified: dump all the providers
9451 * - a flattened component name that matched an existing provider was specified as the
9452 * first arg: dump that one provider
9453 * - the first arg isn't the flattened component name of an existing provider:
9454 * dump all providers whose component contains the first arg as a substring
9455 */
9456 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9457 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009458 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009459 }
9460
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009461 static class ItemMatcher {
9462 ArrayList<ComponentName> components;
9463 ArrayList<String> strings;
9464 ArrayList<Integer> objects;
9465 boolean all;
9466
9467 ItemMatcher() {
9468 all = true;
9469 }
9470
9471 void build(String name) {
9472 ComponentName componentName = ComponentName.unflattenFromString(name);
9473 if (componentName != null) {
9474 if (components == null) {
9475 components = new ArrayList<ComponentName>();
9476 }
9477 components.add(componentName);
9478 all = false;
9479 } else {
9480 int objectId = 0;
9481 // Not a '/' separated full component name; maybe an object ID?
9482 try {
9483 objectId = Integer.parseInt(name, 16);
9484 if (objects == null) {
9485 objects = new ArrayList<Integer>();
9486 }
9487 objects.add(objectId);
9488 all = false;
9489 } catch (RuntimeException e) {
9490 // Not an integer; just do string match.
9491 if (strings == null) {
9492 strings = new ArrayList<String>();
9493 }
9494 strings.add(name);
9495 all = false;
9496 }
9497 }
9498 }
9499
9500 int build(String[] args, int opti) {
9501 for (; opti<args.length; opti++) {
9502 String name = args[opti];
9503 if ("--".equals(name)) {
9504 return opti+1;
9505 }
9506 build(name);
9507 }
9508 return opti;
9509 }
9510
9511 boolean match(Object object, ComponentName comp) {
9512 if (all) {
9513 return true;
9514 }
9515 if (components != null) {
9516 for (int i=0; i<components.size(); i++) {
9517 if (components.get(i).equals(comp)) {
9518 return true;
9519 }
9520 }
9521 }
9522 if (objects != null) {
9523 for (int i=0; i<objects.size(); i++) {
9524 if (System.identityHashCode(object) == objects.get(i)) {
9525 return true;
9526 }
9527 }
9528 }
9529 if (strings != null) {
9530 String flat = comp.flattenToString();
9531 for (int i=0; i<strings.size(); i++) {
9532 if (flat.contains(strings.get(i))) {
9533 return true;
9534 }
9535 }
9536 }
9537 return false;
9538 }
9539 }
9540
Dianne Hackborn625ac272010-09-17 18:29:22 -07009541 /**
9542 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009543 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009544 * - the cmd arg isn't the flattened component name of an existing activity:
9545 * dump all activity whose component contains the cmd as a substring
9546 * - A hex number of the ActivityRecord object instance.
9547 */
9548 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9549 int opti, boolean dumpAll) {
Craig Mautnercae015f2013-02-08 14:31:27 -08009550 ArrayList<ActivityRecord> activities;
9551
9552 synchronized (this) {
9553 activities = mMainStack.getDumpActivitiesLocked(name);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009554 }
9555
9556 if (activities.size() <= 0) {
9557 return false;
9558 }
9559
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009560 String[] newArgs = new String[args.length - opti];
9561 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9562
Dianne Hackborn30d71892010-12-11 10:37:55 -08009563 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009564 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009565 for (int i=activities.size()-1; i>=0; i--) {
9566 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009567 if (needSep) {
9568 pw.println();
9569 }
9570 needSep = true;
9571 synchronized (this) {
9572 if (lastTask != r.task) {
9573 lastTask = r.task;
9574 pw.print("TASK "); pw.print(lastTask.affinity);
9575 pw.print(" id="); pw.println(lastTask.taskId);
9576 if (dumpAll) {
9577 lastTask.dump(pw, " ");
9578 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009579 }
9580 }
9581 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009582 }
9583 return true;
9584 }
9585
9586 /**
9587 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9588 * there is a thread associated with the activity.
9589 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009590 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009591 final ActivityRecord r, String[] args, boolean dumpAll) {
9592 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009593 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9595 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9596 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009597 if (r.app != null) pw.println(r.app.pid);
9598 else pw.println("(not running)");
9599 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009600 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009601 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009602 }
9603 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009604 // flush anything that is already in the PrintWriter since the thread is going
9605 // to write to the file descriptor directly
9606 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009607 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009608 TransferPipe tp = new TransferPipe();
9609 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009610 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9611 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009612 tp.go(fd);
9613 } finally {
9614 tp.kill();
9615 }
9616 } catch (IOException e) {
9617 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009618 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009619 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009620 }
9621 }
9622 }
9623
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009624 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009625 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009626 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009627 boolean onlyHistory = false;
9628
9629 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009630 if (opti < args.length && "-s".equals(args[opti])) {
9631 dumpAll = false;
9632 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009633 onlyHistory = true;
9634 dumpPackage = null;
9635 }
9636
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009637 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009638 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009639 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009640 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009641 Iterator it = mRegisteredReceivers.values().iterator();
9642 while (it.hasNext()) {
9643 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009644 if (dumpPackage != null && (r.app == null ||
9645 !dumpPackage.equals(r.app.info.packageName))) {
9646 continue;
9647 }
9648 if (!printed) {
9649 pw.println(" Registered Receivers:");
9650 needSep = true;
9651 printed = true;
9652 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009653 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 r.dump(pw, " ");
9655 }
9656 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009657
9658 if (mReceiverResolver.dump(pw, needSep ?
9659 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9660 " ", dumpPackage, false)) {
9661 needSep = true;
9662 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009663 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009664
9665 for (BroadcastQueue q : mBroadcastQueues) {
9666 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009669 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009670
Dianne Hackborn786b4402012-08-27 15:14:02 -07009671 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009672 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9673 if (needSep) {
9674 pw.println();
9675 }
9676 needSep = true;
9677 pw.print(" Sticky broadcasts for user ");
9678 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9679 StringBuilder sb = new StringBuilder(128);
9680 for (Map.Entry<String, ArrayList<Intent>> ent
9681 : mStickyBroadcasts.valueAt(user).entrySet()) {
9682 pw.print(" * Sticky action "); pw.print(ent.getKey());
9683 if (dumpAll) {
9684 pw.println(":");
9685 ArrayList<Intent> intents = ent.getValue();
9686 final int N = intents.size();
9687 for (int i=0; i<N; i++) {
9688 sb.setLength(0);
9689 sb.append(" Intent: ");
9690 intents.get(i).toShortString(sb, false, true, false, false);
9691 pw.println(sb.toString());
9692 Bundle bundle = intents.get(i).getExtras();
9693 if (bundle != null) {
9694 pw.print(" ");
9695 pw.println(bundle.toString());
9696 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009697 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009698 } else {
9699 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 }
9701 }
9702 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009703 }
9704
Dianne Hackborn786b4402012-08-27 15:14:02 -07009705 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009706 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009707 for (BroadcastQueue queue : mBroadcastQueues) {
9708 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9709 + queue.mBroadcastsScheduled);
9710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009711 pw.println(" mHandler:");
9712 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009713 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009714 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009715
9716 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 }
9718
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009719 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009720 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009721 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009723 ItemMatcher matcher = new ItemMatcher();
9724 matcher.build(args, opti);
9725
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009727
9728 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009729
9730 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009731 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009732 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009733 ContentProviderRecord r = mLaunchingProviders.get(i);
9734 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9735 continue;
9736 }
9737 if (!printed) {
9738 if (needSep) pw.println(" ");
9739 needSep = true;
9740 pw.println(" Launching content providers:");
9741 printed = true;
9742 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009743 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009744 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009745 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009746 }
9747
9748 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009749 if (needSep) pw.println();
9750 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009751 pw.println("Granted Uri Permissions:");
9752 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9753 int uid = mGrantedUriPermissions.keyAt(i);
9754 HashMap<Uri, UriPermission> perms
9755 = mGrantedUriPermissions.valueAt(i);
9756 pw.print(" * UID "); pw.print(uid);
9757 pw.println(" holds:");
9758 for (UriPermission perm : perms.values()) {
9759 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009760 if (dumpAll) {
9761 perm.dump(pw, " ");
9762 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009763 }
9764 }
9765 needSep = true;
9766 }
9767
9768 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009769 }
9770
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009771 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009772 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009773 boolean needSep = false;
9774
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009775 if (mIntentSenderRecords.size() > 0) {
9776 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009777 Iterator<WeakReference<PendingIntentRecord>> it
9778 = mIntentSenderRecords.values().iterator();
9779 while (it.hasNext()) {
9780 WeakReference<PendingIntentRecord> ref = it.next();
9781 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009782 if (dumpPackage != null && (rec == null
9783 || !dumpPackage.equals(rec.key.packageName))) {
9784 continue;
9785 }
9786 if (!printed) {
9787 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9788 printed = true;
9789 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 needSep = true;
9791 if (rec != null) {
9792 pw.print(" * "); pw.println(rec);
9793 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009794 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009795 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009796 } else {
9797 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009798 }
9799 }
9800 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009801
9802 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009803 }
9804
Craig Mautnercae015f2013-02-08 14:31:27 -08009805 static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009806 String prefix, String label, boolean complete, boolean brief, boolean client,
9807 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009808 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009809 boolean needNL = false;
9810 final String innerPrefix = prefix + " ";
9811 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009813 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009814 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9815 continue;
9816 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009817 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009818 if (needNL) {
9819 pw.println(" ");
9820 needNL = false;
9821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009822 if (lastTask != r.task) {
9823 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009824 pw.print(prefix);
9825 pw.print(full ? "* " : " ");
9826 pw.println(lastTask);
9827 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009828 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009829 } else if (complete) {
9830 // Complete + brief == give a summary. Isn't that obvious?!?
9831 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009832 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009833 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009837 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9838 pw.print(" #"); pw.print(i); pw.print(": ");
9839 pw.println(r);
9840 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009841 r.dump(pw, innerPrefix);
9842 } else if (complete) {
9843 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009844 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009845 if (r.app != null) {
9846 pw.print(innerPrefix); pw.println(r.app);
9847 }
9848 }
9849 if (client && r.app != null && r.app.thread != null) {
9850 // flush anything that is already in the PrintWriter since the thread is going
9851 // to write to the file descriptor directly
9852 pw.flush();
9853 try {
9854 TransferPipe tp = new TransferPipe();
9855 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009856 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9857 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 // Short timeout, since blocking here can
9859 // deadlock with the application.
9860 tp.go(fd, 2000);
9861 } finally {
9862 tp.kill();
9863 }
9864 } catch (IOException e) {
9865 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9866 } catch (RemoteException e) {
9867 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9868 }
9869 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 }
9872 }
9873
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009874 private static String buildOomTag(String prefix, String space, int val, int base) {
9875 if (val == base) {
9876 if (space == null) return prefix;
9877 return prefix + " ";
9878 }
9879 return prefix + "+" + Integer.toString(val-base);
9880 }
9881
9882 private static final int dumpProcessList(PrintWriter pw,
9883 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009884 String prefix, String normalLabel, String persistentLabel,
9885 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009886 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009887 final int N = list.size()-1;
9888 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009889 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009890 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9891 continue;
9892 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009893 pw.println(String.format("%s%s #%2d: %s",
9894 prefix, (r.persistent ? persistentLabel : normalLabel),
9895 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009896 if (r.persistent) {
9897 numPers++;
9898 }
9899 }
9900 return numPers;
9901 }
9902
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009903 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009904 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009905 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009906 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009907
Dianne Hackborn905577f2011-09-07 18:31:28 -07009908 ArrayList<Pair<ProcessRecord, Integer>> list
9909 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9910 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009911 ProcessRecord r = origList.get(i);
9912 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9913 continue;
9914 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009915 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9916 }
9917
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009918 if (list.size() <= 0) {
9919 return false;
9920 }
9921
Dianne Hackborn905577f2011-09-07 18:31:28 -07009922 Comparator<Pair<ProcessRecord, Integer>> comparator
9923 = new Comparator<Pair<ProcessRecord, Integer>>() {
9924 @Override
9925 public int compare(Pair<ProcessRecord, Integer> object1,
9926 Pair<ProcessRecord, Integer> object2) {
9927 if (object1.first.setAdj != object2.first.setAdj) {
9928 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9929 }
9930 if (object1.second.intValue() != object2.second.intValue()) {
9931 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9932 }
9933 return 0;
9934 }
9935 };
9936
9937 Collections.sort(list, comparator);
9938
Dianne Hackborn287952c2010-09-22 22:34:31 -07009939 final long curRealtime = SystemClock.elapsedRealtime();
9940 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9941 final long curUptime = SystemClock.uptimeMillis();
9942 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9943
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009944 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009945 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009946 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009947 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009948 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009949 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9950 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009951 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9952 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009953 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9954 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009955 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9956 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009957 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009958 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009959 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9960 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9961 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9962 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9963 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9964 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9965 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9966 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009967 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9968 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009969 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9970 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009971 } else {
9972 oomAdj = Integer.toString(r.setAdj);
9973 }
9974 String schedGroup;
9975 switch (r.setSchedGroup) {
9976 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9977 schedGroup = "B";
9978 break;
9979 case Process.THREAD_GROUP_DEFAULT:
9980 schedGroup = "F";
9981 break;
9982 default:
9983 schedGroup = Integer.toString(r.setSchedGroup);
9984 break;
9985 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009986 String foreground;
9987 if (r.foregroundActivities) {
9988 foreground = "A";
9989 } else if (r.foregroundServices) {
9990 foreground = "S";
9991 } else {
9992 foreground = " ";
9993 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009994 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009995 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009996 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9997 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009998 if (r.adjSource != null || r.adjTarget != null) {
9999 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010000 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010001 if (r.adjTarget instanceof ComponentName) {
10002 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10003 } else if (r.adjTarget != null) {
10004 pw.print(r.adjTarget.toString());
10005 } else {
10006 pw.print("{null}");
10007 }
10008 pw.print("<=");
10009 if (r.adjSource instanceof ProcessRecord) {
10010 pw.print("Proc{");
10011 pw.print(((ProcessRecord)r.adjSource).toShortString());
10012 pw.println("}");
10013 } else if (r.adjSource != null) {
10014 pw.println(r.adjSource.toString());
10015 } else {
10016 pw.println("{null}");
10017 }
10018 }
10019 if (inclDetails) {
10020 pw.print(prefix);
10021 pw.print(" ");
10022 pw.print("oom: max="); pw.print(r.maxAdj);
10023 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010024 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010025 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010026 pw.print(" curRaw="); pw.print(r.curRawAdj);
10027 pw.print(" setRaw="); pw.print(r.setRawAdj);
10028 pw.print(" cur="); pw.print(r.curAdj);
10029 pw.print(" set="); pw.println(r.setAdj);
10030 pw.print(prefix);
10031 pw.print(" ");
10032 pw.print("keeping="); pw.print(r.keeping);
10033 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010034 pw.print(" empty="); pw.print(r.empty);
10035 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010036
10037 if (!r.keeping) {
10038 if (r.lastWakeTime != 0) {
10039 long wtime;
10040 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10041 synchronized (stats) {
10042 wtime = stats.getProcessWakeTime(r.info.uid,
10043 r.pid, curRealtime);
10044 }
10045 long timeUsed = wtime - r.lastWakeTime;
10046 pw.print(prefix);
10047 pw.print(" ");
10048 pw.print("keep awake over ");
10049 TimeUtils.formatDuration(realtimeSince, pw);
10050 pw.print(" used ");
10051 TimeUtils.formatDuration(timeUsed, pw);
10052 pw.print(" (");
10053 pw.print((timeUsed*100)/realtimeSince);
10054 pw.println("%)");
10055 }
10056 if (r.lastCpuTime != 0) {
10057 long timeUsed = r.curCpuTime - r.lastCpuTime;
10058 pw.print(prefix);
10059 pw.print(" ");
10060 pw.print("run cpu over ");
10061 TimeUtils.formatDuration(uptimeSince, pw);
10062 pw.print(" used ");
10063 TimeUtils.formatDuration(timeUsed, pw);
10064 pw.print(" (");
10065 pw.print((timeUsed*100)/uptimeSince);
10066 pw.println("%)");
10067 }
10068 }
10069 }
10070 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010071 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010072 }
10073
Dianne Hackbornb437e092011-08-05 17:50:29 -070010074 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010075 ArrayList<ProcessRecord> procs;
10076 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010077 if (args != null && args.length > start
10078 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010079 procs = new ArrayList<ProcessRecord>();
10080 int pid = -1;
10081 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010082 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010083 } catch (NumberFormatException e) {
10084
10085 }
10086 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10087 ProcessRecord proc = mLruProcesses.get(i);
10088 if (proc.pid == pid) {
10089 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010090 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010091 procs.add(proc);
10092 }
10093 }
10094 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010095 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010096 return null;
10097 }
10098 } else {
10099 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10100 }
10101 }
10102 return procs;
10103 }
10104
10105 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10106 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010107 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010108 if (procs == null) {
10109 return;
10110 }
10111
10112 long uptime = SystemClock.uptimeMillis();
10113 long realtime = SystemClock.elapsedRealtime();
10114 pw.println("Applications Graphics Acceleration Info:");
10115 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10116
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010117 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10118 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010119 if (r.thread != null) {
10120 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10121 pw.flush();
10122 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010123 TransferPipe tp = new TransferPipe();
10124 try {
10125 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10126 tp.go(fd);
10127 } finally {
10128 tp.kill();
10129 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010130 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010131 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010132 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010133 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010134 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010135 pw.flush();
10136 }
10137 }
10138 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010139 }
10140
Jeff Brown6754ba22011-12-14 20:20:01 -080010141 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10142 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10143 if (procs == null) {
10144 return;
10145 }
10146
10147 pw.println("Applications Database Info:");
10148
10149 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10150 ProcessRecord r = procs.get(i);
10151 if (r.thread != null) {
10152 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10153 pw.flush();
10154 try {
10155 TransferPipe tp = new TransferPipe();
10156 try {
10157 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10158 tp.go(fd);
10159 } finally {
10160 tp.kill();
10161 }
10162 } catch (IOException e) {
10163 pw.println("Failure while dumping the app: " + r);
10164 pw.flush();
10165 } catch (RemoteException e) {
10166 pw.println("Got a RemoteException while dumping the app " + r);
10167 pw.flush();
10168 }
10169 }
10170 }
10171 }
10172
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010173 final static class MemItem {
10174 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010175 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010176 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010177 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010178 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010179
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010180 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010181 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010182 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010183 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010184 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010185 }
10186 }
10187
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010188 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010189 boolean sort) {
10190 if (sort) {
10191 Collections.sort(items, new Comparator<MemItem>() {
10192 @Override
10193 public int compare(MemItem lhs, MemItem rhs) {
10194 if (lhs.pss < rhs.pss) {
10195 return 1;
10196 } else if (lhs.pss > rhs.pss) {
10197 return -1;
10198 }
10199 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010200 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010201 });
10202 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010203
10204 for (int i=0; i<items.size(); i++) {
10205 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010207 if (mi.subitems != null) {
10208 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10209 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 }
10211 }
10212
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010213 // These are in KB.
10214 static final long[] DUMP_MEM_BUCKETS = new long[] {
10215 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10216 120*1024, 160*1024, 200*1024,
10217 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10218 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10219 };
10220
Dianne Hackborn672342c2011-11-29 11:29:02 -080010221 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10222 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010223 int start = label.lastIndexOf('.');
10224 if (start >= 0) start++;
10225 else start = 0;
10226 int end = label.length();
10227 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10228 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10229 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10230 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010231 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010232 out.append(label, start, end);
10233 return;
10234 }
10235 }
10236 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010237 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010238 out.append(label, start, end);
10239 }
10240
10241 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10242 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10243 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10244 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10245 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10246 };
10247 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10248 "System", "Persistent", "Foreground",
10249 "Visible", "Perceptible", "Heavy Weight",
10250 "Backup", "A Services", "Home", "Previous",
10251 "B Services", "Background"
10252 };
10253
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010254 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010255 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010256 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010257 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010258 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010259
10260 int opti = 0;
10261 while (opti < args.length) {
10262 String opt = args[opti];
10263 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10264 break;
10265 }
10266 opti++;
10267 if ("-a".equals(opt)) {
10268 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010269 } else if ("--oom".equals(opt)) {
10270 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010271 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010272 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010273 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010274 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010275 pw.println("If [process] is specified it can be the name or ");
10276 pw.println("pid of a specific process to dump.");
10277 return;
10278 } else {
10279 pw.println("Unknown argument: " + opt + "; use -h for help");
10280 }
10281 }
10282
10283 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010284 if (procs == null) {
10285 return;
10286 }
10287
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010288 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 long uptime = SystemClock.uptimeMillis();
10290 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010291
10292 if (procs.size() == 1 || isCheckinRequest) {
10293 dumpAll = true;
10294 }
10295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 if (isCheckinRequest) {
10297 // short checkin version
10298 pw.println(uptime + "," + realtime);
10299 pw.flush();
10300 } else {
10301 pw.println("Applications Memory Usage (kB):");
10302 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10303 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010304
Dianne Hackbornb437e092011-08-05 17:50:29 -070010305 String[] innerArgs = new String[args.length-opti];
10306 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10307
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010308 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10309 long nativePss=0, dalvikPss=0, otherPss=0;
10310 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10311
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010312 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10313 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10314 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010315
10316 long totalPss = 0;
10317
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010318 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10319 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010321 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010322 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10323 pw.flush();
10324 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010325 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010326 if (dumpAll) {
10327 try {
10328 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10329 } catch (RemoteException e) {
10330 if (!isCheckinRequest) {
10331 pw.println("Got RemoteException!");
10332 pw.flush();
10333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010335 } else {
10336 mi = new Debug.MemoryInfo();
10337 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010338 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010339
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010340 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010341 long myTotalPss = mi.getTotalPss();
10342 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010343 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010344 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010345 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010346
10347 nativePss += mi.nativePss;
10348 dalvikPss += mi.dalvikPss;
10349 otherPss += mi.otherPss;
10350 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10351 long mem = mi.getOtherPss(j);
10352 miscPss[j] += mem;
10353 otherPss -= mem;
10354 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010355
10356 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010357 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10358 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010359 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010360 if (oomProcs[oomIndex] == null) {
10361 oomProcs[oomIndex] = new ArrayList<MemItem>();
10362 }
10363 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010364 break;
10365 }
10366 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010368 }
10369 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010370
10371 if (!isCheckinRequest && procs.size() > 1) {
10372 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10373
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010374 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10375 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10376 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010377 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010378 String label = Debug.MemoryInfo.getOtherLabel(j);
10379 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010380 }
10381
Dianne Hackbornb437e092011-08-05 17:50:29 -070010382 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10383 for (int j=0; j<oomPss.length; j++) {
10384 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010385 String label = DUMP_MEM_OOM_LABEL[j];
10386 MemItem item = new MemItem(label, label, oomPss[j],
10387 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010388 item.subitems = oomProcs[j];
10389 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010390 }
10391 }
10392
Dianne Hackborn672342c2011-11-29 11:29:02 -080010393 if (outTag != null || outStack != null) {
10394 if (outTag != null) {
10395 appendMemBucket(outTag, totalPss, "total", false);
10396 }
10397 if (outStack != null) {
10398 appendMemBucket(outStack, totalPss, "total", true);
10399 }
10400 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010401 for (int i=0; i<oomMems.size(); i++) {
10402 MemItem miCat = oomMems.get(i);
10403 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10404 continue;
10405 }
10406 if (miCat.id < ProcessList.SERVICE_ADJ
10407 || miCat.id == ProcessList.HOME_APP_ADJ
10408 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010409 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10410 outTag.append(" / ");
10411 }
10412 if (outStack != null) {
10413 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10414 if (firstLine) {
10415 outStack.append(":");
10416 firstLine = false;
10417 }
10418 outStack.append("\n\t at ");
10419 } else {
10420 outStack.append("$");
10421 }
10422 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010423 for (int j=0; j<miCat.subitems.size(); j++) {
10424 MemItem mi = miCat.subitems.get(j);
10425 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010426 if (outTag != null) {
10427 outTag.append(" ");
10428 }
10429 if (outStack != null) {
10430 outStack.append("$");
10431 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010432 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010433 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10434 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10435 }
10436 if (outStack != null) {
10437 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10438 }
10439 }
10440 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10441 outStack.append("(");
10442 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10443 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10444 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10445 outStack.append(":");
10446 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10447 }
10448 }
10449 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010450 }
10451 }
10452 }
10453 }
10454
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010455 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010456 pw.println();
10457 pw.println("Total PSS by process:");
10458 dumpMemItems(pw, " ", procMems, true);
10459 pw.println();
10460 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010461 pw.println("Total PSS by OOM adjustment:");
10462 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010463 if (!oomOnly) {
10464 PrintWriter out = categoryPw != null ? categoryPw : pw;
10465 out.println();
10466 out.println("Total PSS by category:");
10467 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010468 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010469 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010470 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010471 final int[] SINGLE_LONG_FORMAT = new int[] {
10472 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10473 };
10474 long[] longOut = new long[1];
10475 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10476 SINGLE_LONG_FORMAT, null, longOut, null);
10477 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10478 longOut[0] = 0;
10479 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10480 SINGLE_LONG_FORMAT, null, longOut, null);
10481 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10482 longOut[0] = 0;
10483 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10484 SINGLE_LONG_FORMAT, null, longOut, null);
10485 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10486 longOut[0] = 0;
10487 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10488 SINGLE_LONG_FORMAT, null, longOut, null);
10489 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10490 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10491 pw.print(shared); pw.println(" kB");
10492 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10493 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010495 }
10496
10497 /**
10498 * Searches array of arguments for the specified string
10499 * @param args array of argument strings
10500 * @param value value to search for
10501 * @return true if the value is contained in the array
10502 */
10503 private static boolean scanArgs(String[] args, String value) {
10504 if (args != null) {
10505 for (String arg : args) {
10506 if (value.equals(arg)) {
10507 return true;
10508 }
10509 }
10510 }
10511 return false;
10512 }
10513
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010514 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10515 ContentProviderRecord cpr, boolean always) {
10516 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10517
10518 if (!inLaunching || always) {
10519 synchronized (cpr) {
10520 cpr.launchingApp = null;
10521 cpr.notifyAll();
10522 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010523 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010524 String names[] = cpr.info.authority.split(";");
10525 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010526 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 }
10528 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010529
10530 for (int i=0; i<cpr.connections.size(); i++) {
10531 ContentProviderConnection conn = cpr.connections.get(i);
10532 if (conn.waiting) {
10533 // If this connection is waiting for the provider, then we don't
10534 // need to mess with its process unless we are always removing
10535 // or for some reason the provider is not currently launching.
10536 if (inLaunching && !always) {
10537 continue;
10538 }
10539 }
10540 ProcessRecord capp = conn.client;
10541 conn.dead = true;
10542 if (conn.stableCount > 0) {
10543 if (!capp.persistent && capp.thread != null
10544 && capp.pid != 0
10545 && capp.pid != MY_PID) {
10546 Slog.i(TAG, "Kill " + capp.processName
10547 + " (pid " + capp.pid + "): provider " + cpr.info.name
10548 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010549 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010550 capp.processName, capp.setAdj, "dying provider "
10551 + cpr.name.toShortString());
10552 Process.killProcessQuiet(capp.pid);
10553 }
10554 } else if (capp.thread != null && conn.provider.provider != null) {
10555 try {
10556 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10557 } catch (RemoteException e) {
10558 }
10559 // In the protocol here, we don't expect the client to correctly
10560 // clean up this connection, we'll just remove it.
10561 cpr.connections.remove(i);
10562 conn.client.conProviders.remove(conn);
10563 }
10564 }
10565
10566 if (inLaunching && always) {
10567 mLaunchingProviders.remove(cpr);
10568 }
10569 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 }
10571
10572 /**
10573 * Main code for cleaning up a process when it has gone away. This is
10574 * called both as a result of the process dying, or directly when stopping
10575 * a process when running in single process mode.
10576 */
10577 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010578 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010580 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 }
10582
Dianne Hackborn36124872009-10-08 16:22:03 -070010583 mProcessesToGc.remove(app);
10584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 // Dismiss any open dialogs.
10586 if (app.crashDialog != null) {
10587 app.crashDialog.dismiss();
10588 app.crashDialog = null;
10589 }
10590 if (app.anrDialog != null) {
10591 app.anrDialog.dismiss();
10592 app.anrDialog = null;
10593 }
10594 if (app.waitDialog != null) {
10595 app.waitDialog.dismiss();
10596 app.waitDialog = null;
10597 }
10598
10599 app.crashing = false;
10600 app.notResponding = false;
10601
10602 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010603 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 app.thread = null;
10605 app.forcingToForeground = null;
10606 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010607 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010608 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010609 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010610
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010611 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010612
10613 boolean restart = false;
10614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 // Remove published content providers.
10616 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010617 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010619 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010620
10621 final boolean always = app.bad || !allowRestart;
10622 if (removeDyingProviderLocked(app, cpr, always) || always) {
10623 // We left the provider in the launching list, need to
10624 // restart it.
10625 restart = true;
10626 }
10627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010629 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 }
10631 app.pubProviders.clear();
10632 }
10633
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010634 // Take care of any launching providers waiting for this process.
10635 if (checkAppInLaunchingProvidersLocked(app, false)) {
10636 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010637 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 // Unregister from connected content providers.
10640 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010641 for (int i=0; i<app.conProviders.size(); i++) {
10642 ContentProviderConnection conn = app.conProviders.get(i);
10643 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010644 }
10645 app.conProviders.clear();
10646 }
10647
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010648 // At this point there may be remaining entries in mLaunchingProviders
10649 // where we were the only one waiting, so they are no longer of use.
10650 // Look for these and clean up if found.
10651 // XXX Commented out for now. Trying to figure out a way to reproduce
10652 // the actual situation to identify what is actually going on.
10653 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010654 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010655 ContentProviderRecord cpr = (ContentProviderRecord)
10656 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010657 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010658 synchronized (cpr) {
10659 cpr.launchingApp = null;
10660 cpr.notifyAll();
10661 }
10662 }
10663 }
10664 }
10665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 skipCurrentReceiverLocked(app);
10667
10668 // Unregister any receivers.
10669 if (app.receivers.size() > 0) {
10670 Iterator<ReceiverList> it = app.receivers.iterator();
10671 while (it.hasNext()) {
10672 removeReceiverLocked(it.next());
10673 }
10674 app.receivers.clear();
10675 }
10676
Christopher Tate181fafa2009-05-14 11:12:14 -070010677 // If the app is undergoing backup, tell the backup manager about it
10678 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010679 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10680 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010681 try {
10682 IBackupManager bm = IBackupManager.Stub.asInterface(
10683 ServiceManager.getService(Context.BACKUP_SERVICE));
10684 bm.agentDisconnected(app.info.packageName);
10685 } catch (RemoteException e) {
10686 // can't happen; backup manager is local
10687 }
10688 }
10689
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010690 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10691 ProcessChangeItem item = mPendingProcessChanges.get(i);
10692 if (item.pid == app.pid) {
10693 mPendingProcessChanges.remove(i);
10694 mAvailProcessChanges.add(item);
10695 }
10696 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010697 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 // If the caller is restarting this app, then leave it in its
10700 // current lists and let the caller take care of it.
10701 if (restarting) {
10702 return;
10703 }
10704
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010705 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010706 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010708 mProcessNames.remove(app.processName, app.uid);
10709 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010710 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010711 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10712 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010713 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010715 } else if (!app.removed) {
10716 // This app is persistent, so we need to keep its record around.
10717 // If it is not already on the pending app list, add it there
10718 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10720 mPersistentStartingProcesses.add(app);
10721 restart = true;
10722 }
10723 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010724 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010725 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 mProcessesOnHold.remove(app);
10727
The Android Open Source Project4df24232009-03-05 14:34:35 -080010728 if (app == mHomeProcess) {
10729 mHomeProcess = null;
10730 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010731 if (app == mPreviousProcess) {
10732 mPreviousProcess = null;
10733 }
10734
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010735 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 // We have components that still need to be running in the
10737 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010738 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 startProcessLocked(app, "restart", app.processName);
10740 } else if (app.pid > 0 && app.pid != MY_PID) {
10741 // Goodbye!
10742 synchronized (mPidsSelfLocked) {
10743 mPidsSelfLocked.remove(app.pid);
10744 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10745 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010746 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010747 }
10748 }
10749
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010750 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10751 // Look through the content providers we are waiting to have launched,
10752 // and if any run in this process then either schedule a restart of
10753 // the process or kill the client waiting for it if this process has
10754 // gone bad.
10755 int NL = mLaunchingProviders.size();
10756 boolean restart = false;
10757 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010758 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010759 if (cpr.launchingApp == app) {
10760 if (!alwaysBad && !app.bad) {
10761 restart = true;
10762 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010763 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010764 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010765 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010766 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010767 }
10768 }
10769 }
10770 return restart;
10771 }
10772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773 // =========================================================
10774 // SERVICES
10775 // =========================================================
10776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10778 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010779 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010780 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010781 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 }
10783 }
10784
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010785 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010786 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010787 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010788 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010789 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010790 }
10791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010793 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010794 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 // Refuse possible leaked file descriptors
10796 if (service != null && service.hasFileDescriptors() == true) {
10797 throw new IllegalArgumentException("File descriptors passed in Intent");
10798 }
10799
Amith Yamasani742a6712011-05-04 14:49:28 -070010800 if (DEBUG_SERVICE)
10801 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010802 synchronized(this) {
10803 final int callingPid = Binder.getCallingPid();
10804 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010805 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010807 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010808 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 Binder.restoreCallingIdentity(origId);
10810 return res;
10811 }
10812 }
10813
10814 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010815 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010816 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010817 if (DEBUG_SERVICE)
10818 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010820 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010821 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 Binder.restoreCallingIdentity(origId);
10823 return res;
10824 }
10825 }
10826
10827 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010828 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010829 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 // Refuse possible leaked file descriptors
10831 if (service != null && service.hasFileDescriptors() == true) {
10832 throw new IllegalArgumentException("File descriptors passed in Intent");
10833 }
10834
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010835 checkValidCaller(Binder.getCallingUid(), userId);
10836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010838 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841
10842 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010843 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 // Refuse possible leaked file descriptors
10845 if (service != null && service.hasFileDescriptors() == true) {
10846 throw new IllegalArgumentException("File descriptors passed in Intent");
10847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010849 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 }
10852
10853 public boolean stopServiceToken(ComponentName className, IBinder token,
10854 int startId) {
10855 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010856 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
10859
10860 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010861 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010863 mServices.setServiceForegroundLocked(className, token, id, notification,
10864 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 }
10866 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010867
Dianne Hackborn41203752012-08-31 14:05:51 -070010868 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10869 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010870 final int callingUserId = UserHandle.getUserId(callingUid);
10871 if (callingUserId != userId) {
10872 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10873 if ((requireFull || checkComponentPermission(
10874 android.Manifest.permission.INTERACT_ACROSS_USERS,
10875 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10876 && checkComponentPermission(
10877 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10878 callingPid, callingUid, -1, true)
10879 != PackageManager.PERMISSION_GRANTED) {
10880 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10881 // In this case, they would like to just execute as their
10882 // owner user instead of failing.
10883 userId = callingUserId;
10884 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010885 StringBuilder builder = new StringBuilder(128);
10886 builder.append("Permission Denial: ");
10887 builder.append(name);
10888 if (callerPackage != null) {
10889 builder.append(" from ");
10890 builder.append(callerPackage);
10891 }
10892 builder.append(" asks to run as user ");
10893 builder.append(userId);
10894 builder.append(" but is calling from user ");
10895 builder.append(UserHandle.getUserId(callingUid));
10896 builder.append("; this requires ");
10897 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10898 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010899 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010900 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10901 }
10902 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010903 Slog.w(TAG, msg);
10904 throw new SecurityException(msg);
10905 }
10906 }
10907 }
10908 if (userId == UserHandle.USER_CURRENT
10909 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010910 // Note that we may be accessing this outside of a lock...
10911 // shouldn't be a big deal, if this is being called outside
10912 // of a locked context there is intrinsically a race with
10913 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010914 userId = mCurrentUserId;
10915 }
10916 if (!allowAll && userId < 0) {
10917 throw new IllegalArgumentException(
10918 "Call does not support special user #" + userId);
10919 }
10920 }
10921 return userId;
10922 }
10923
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010924 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10925 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010926 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010927 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010928 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10929 if (ActivityManager.checkUidPermission(
10930 android.Manifest.permission.INTERACT_ACROSS_USERS,
10931 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10932 ComponentName comp = new ComponentName(aInfo.packageName, className);
10933 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10934 + " requests FLAG_SINGLE_USER, but app does not hold "
10935 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10936 Slog.w(TAG, msg);
10937 throw new SecurityException(msg);
10938 }
10939 result = true;
10940 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010941 } else if (componentProcessName == aInfo.packageName) {
10942 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10943 } else if ("system".equals(componentProcessName)) {
10944 result = true;
10945 }
10946 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010947 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10948 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010949 }
10950 return result;
10951 }
10952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 public int bindService(IApplicationThread caller, IBinder token,
10954 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010955 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010956 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 // Refuse possible leaked file descriptors
10958 if (service != null && service.hasFileDescriptors() == true) {
10959 throw new IllegalArgumentException("File descriptors passed in Intent");
10960 }
10961
10962 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010963 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10964 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 }
10966 }
10967
10968 public boolean unbindService(IServiceConnection connection) {
10969 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010970 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 }
10973
10974 public void publishService(IBinder token, Intent intent, IBinder service) {
10975 // Refuse possible leaked file descriptors
10976 if (intent != null && intent.hasFileDescriptors() == true) {
10977 throw new IllegalArgumentException("File descriptors passed in Intent");
10978 }
10979
10980 synchronized(this) {
10981 if (!(token instanceof ServiceRecord)) {
10982 throw new IllegalArgumentException("Invalid service token");
10983 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010984 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 }
10986 }
10987
10988 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10989 // Refuse possible leaked file descriptors
10990 if (intent != null && intent.hasFileDescriptors() == true) {
10991 throw new IllegalArgumentException("File descriptors passed in Intent");
10992 }
10993
10994 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010995 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010996 }
10997 }
10998
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010999 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011000 synchronized(this) {
11001 if (!(token instanceof ServiceRecord)) {
11002 throw new IllegalArgumentException("Invalid service token");
11003 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011004 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011006 }
11007
11008 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011009 // BACKUP AND RESTORE
11010 // =========================================================
11011
11012 // Cause the target app to be launched if necessary and its backup agent
11013 // instantiated. The backup agent will invoke backupAgentCreated() on the
11014 // activity manager to announce its creation.
11015 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011016 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11017 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011018
11019 synchronized(this) {
11020 // !!! TODO: currently no check here that we're already bound
11021 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11022 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11023 synchronized (stats) {
11024 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11025 }
11026
Dianne Hackborne7f97212011-02-24 14:40:20 -080011027 // Backup agent is now in use, its package can't be stopped.
11028 try {
11029 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011030 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011031 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011032 } catch (IllegalArgumentException e) {
11033 Slog.w(TAG, "Failed trying to unstop package "
11034 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011035 }
11036
Christopher Tate181fafa2009-05-14 11:12:14 -070011037 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011038 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11039 ? new ComponentName(app.packageName, app.backupAgentName)
11040 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011041 // startProcessLocked() returns existing proc's record if it's already running
11042 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011043 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011044 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011045 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011046 return false;
11047 }
11048
11049 r.app = proc;
11050 mBackupTarget = r;
11051 mBackupAppName = app.packageName;
11052
Christopher Tate6fa95972009-06-05 18:43:55 -070011053 // Try not to kill the process during backup
11054 updateOomAdjLocked(proc);
11055
Christopher Tate181fafa2009-05-14 11:12:14 -070011056 // If the process is already attached, schedule the creation of the backup agent now.
11057 // If it is not yet live, this will be done when it attaches to the framework.
11058 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011059 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011060 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011061 proc.thread.scheduleCreateBackupAgent(app,
11062 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011063 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011064 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011065 }
11066 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011067 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011068 }
11069 // Invariants: at this point, the target app process exists and the application
11070 // is either already running or in the process of coming up. mBackupTarget and
11071 // mBackupAppName describe the app, so that when it binds back to the AM we
11072 // know that it's scheduled for a backup-agent operation.
11073 }
11074
11075 return true;
11076 }
11077
Christopher Tate346acb12012-10-15 19:20:25 -070011078 @Override
11079 public void clearPendingBackup() {
11080 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11081 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11082
11083 synchronized (this) {
11084 mBackupTarget = null;
11085 mBackupAppName = null;
11086 }
11087 }
11088
Christopher Tate181fafa2009-05-14 11:12:14 -070011089 // A backup agent has just come up
11090 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011091 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 + " = " + agent);
11093
11094 synchronized(this) {
11095 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011096 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011097 return;
11098 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011099 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011100
Dianne Hackborn06740692010-09-22 22:46:21 -070011101 long oldIdent = Binder.clearCallingIdentity();
11102 try {
11103 IBackupManager bm = IBackupManager.Stub.asInterface(
11104 ServiceManager.getService(Context.BACKUP_SERVICE));
11105 bm.agentConnected(agentPackageName, agent);
11106 } catch (RemoteException e) {
11107 // can't happen; the backup manager service is local
11108 } catch (Exception e) {
11109 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11110 e.printStackTrace();
11111 } finally {
11112 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011113 }
11114 }
11115
11116 // done with this agent
11117 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011118 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011119 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011121 return;
11122 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011123
11124 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011125 try {
11126 if (mBackupAppName == null) {
11127 Slog.w(TAG, "Unbinding backup agent with no active backup");
11128 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011129 }
Christopher Tate346acb12012-10-15 19:20:25 -070011130
11131 if (!mBackupAppName.equals(appInfo.packageName)) {
11132 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11133 return;
11134 }
11135
11136 // Not backing this app up any more; reset its OOM adjustment
11137 final ProcessRecord proc = mBackupTarget.app;
11138 updateOomAdjLocked(proc);
11139
11140 // If the app crashed during backup, 'thread' will be null here
11141 if (proc.thread != null) {
11142 try {
11143 proc.thread.scheduleDestroyBackupAgent(appInfo,
11144 compatibilityInfoForPackageLocked(appInfo));
11145 } catch (Exception e) {
11146 Slog.e(TAG, "Exception when unbinding backup agent:");
11147 e.printStackTrace();
11148 }
11149 }
11150 } finally {
11151 mBackupTarget = null;
11152 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011153 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011154 }
11155 }
11156 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011157 // BROADCASTS
11158 // =========================================================
11159
Josh Bartel7f208742010-02-25 11:01:44 -060011160 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011161 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011162 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011163 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11164 if (stickies == null) {
11165 return cur;
11166 }
11167 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 if (list == null) {
11169 return cur;
11170 }
11171 int N = list.size();
11172 for (int i=0; i<N; i++) {
11173 Intent intent = list.get(i);
11174 if (filter.match(resolver, intent, true, TAG) >= 0) {
11175 if (cur == null) {
11176 cur = new ArrayList<Intent>();
11177 }
11178 cur.add(intent);
11179 }
11180 }
11181 return cur;
11182 }
11183
Christopher Tatef46723b2012-01-26 14:19:24 -080011184 boolean isPendingBroadcastProcessLocked(int pid) {
11185 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11186 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011188
Christopher Tatef46723b2012-01-26 14:19:24 -080011189 void skipPendingBroadcastLocked(int pid) {
11190 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11191 for (BroadcastQueue queue : mBroadcastQueues) {
11192 queue.skipPendingBroadcastLocked(pid);
11193 }
11194 }
11195
11196 // The app just attached; send any pending broadcasts that it should receive
11197 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11198 boolean didSomething = false;
11199 for (BroadcastQueue queue : mBroadcastQueues) {
11200 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011202 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 }
11204
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011205 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011206 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011207 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011208 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011209 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011210 synchronized(this) {
11211 ProcessRecord callerApp = null;
11212 if (caller != null) {
11213 callerApp = getRecordForAppLocked(caller);
11214 if (callerApp == null) {
11215 throw new SecurityException(
11216 "Unable to find app for caller " + caller
11217 + " (pid=" + Binder.getCallingPid()
11218 + ") when registering receiver " + receiver);
11219 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011220 if (callerApp.info.uid != Process.SYSTEM_UID &&
11221 !callerApp.pkgList.contains(callerPackage)) {
11222 throw new SecurityException("Given caller package " + callerPackage
11223 + " is not running in process " + callerApp);
11224 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011225 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011226 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011227 } else {
11228 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011229 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011230 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231 }
11232
Dianne Hackborn139748f2012-09-24 11:36:57 -070011233 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011234 true, true, "registerReceiver", callerPackage);
11235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011236 List allSticky = null;
11237
11238 // Look for any matching sticky broadcasts...
11239 Iterator actions = filter.actionsIterator();
11240 if (actions != null) {
11241 while (actions.hasNext()) {
11242 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011243 allSticky = getStickiesLocked(action, filter, allSticky,
11244 UserHandle.USER_ALL);
11245 allSticky = getStickiesLocked(action, filter, allSticky,
11246 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011247 }
11248 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011249 allSticky = getStickiesLocked(null, filter, allSticky,
11250 UserHandle.USER_ALL);
11251 allSticky = getStickiesLocked(null, filter, allSticky,
11252 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 }
11254
11255 // The first sticky in the list is returned directly back to
11256 // the client.
11257 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11258
Joe Onorato8a9b2202010-02-26 18:56:32 -080011259 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 + ": " + sticky);
11261
11262 if (receiver == null) {
11263 return sticky;
11264 }
11265
11266 ReceiverList rl
11267 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11268 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011269 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11270 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011271 if (rl.app != null) {
11272 rl.app.receivers.add(rl);
11273 } else {
11274 try {
11275 receiver.asBinder().linkToDeath(rl, 0);
11276 } catch (RemoteException e) {
11277 return sticky;
11278 }
11279 rl.linkedToDeath = true;
11280 }
11281 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011282 } else if (rl.uid != callingUid) {
11283 throw new IllegalArgumentException(
11284 "Receiver requested to register for uid " + callingUid
11285 + " was previously registered for uid " + rl.uid);
11286 } else if (rl.pid != callingPid) {
11287 throw new IllegalArgumentException(
11288 "Receiver requested to register for pid " + callingPid
11289 + " was previously registered for pid " + rl.pid);
11290 } else if (rl.userId != userId) {
11291 throw new IllegalArgumentException(
11292 "Receiver requested to register for user " + userId
11293 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011294 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011295 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011296 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 rl.add(bf);
11298 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011299 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011300 }
11301 mReceiverResolver.addFilter(bf);
11302
11303 // Enqueue broadcasts for all existing stickies that match
11304 // this filter.
11305 if (allSticky != null) {
11306 ArrayList receivers = new ArrayList();
11307 receivers.add(bf);
11308
11309 int N = allSticky.size();
11310 for (int i=0; i<N; i++) {
11311 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011312 BroadcastQueue queue = broadcastQueueForIntent(intent);
11313 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011314 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11315 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011316 queue.enqueueParallelBroadcastLocked(r);
11317 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 }
11319 }
11320
11321 return sticky;
11322 }
11323 }
11324
11325 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011326 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011327
Christopher Tatef46723b2012-01-26 14:19:24 -080011328 final long origId = Binder.clearCallingIdentity();
11329 try {
11330 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331
Christopher Tatef46723b2012-01-26 14:19:24 -080011332 synchronized(this) {
11333 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011335 if (rl != null) {
11336 if (rl.curBroadcast != null) {
11337 BroadcastRecord r = rl.curBroadcast;
11338 final boolean doNext = finishReceiverLocked(
11339 receiver.asBinder(), r.resultCode, r.resultData,
11340 r.resultExtras, r.resultAbort, true);
11341 if (doNext) {
11342 doTrim = true;
11343 r.queue.processNextBroadcast(false);
11344 }
11345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011346
Christopher Tatef46723b2012-01-26 14:19:24 -080011347 if (rl.app != null) {
11348 rl.app.receivers.remove(rl);
11349 }
11350 removeReceiverLocked(rl);
11351 if (rl.linkedToDeath) {
11352 rl.linkedToDeath = false;
11353 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 }
11356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357
Christopher Tatef46723b2012-01-26 14:19:24 -080011358 // If we actually concluded any broadcasts, we might now be able
11359 // to trim the recipients' apps from our working set
11360 if (doTrim) {
11361 trimApplications();
11362 return;
11363 }
11364
11365 } finally {
11366 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 }
11369
11370 void removeReceiverLocked(ReceiverList rl) {
11371 mRegisteredReceivers.remove(rl.receiver.asBinder());
11372 int N = rl.size();
11373 for (int i=0; i<N; i++) {
11374 mReceiverResolver.removeFilter(rl.get(i));
11375 }
11376 }
11377
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011378 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011379 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11380 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011381 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011382 try {
11383 r.thread.dispatchPackageBroadcast(cmd, packages);
11384 } catch (RemoteException ex) {
11385 }
11386 }
11387 }
11388 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011389
11390 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11391 int[] users) {
11392 List<ResolveInfo> receivers = null;
11393 try {
11394 HashSet<ComponentName> singleUserReceivers = null;
11395 boolean scannedFirstReceivers = false;
11396 for (int user : users) {
11397 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11398 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011399 if (user != 0 && newReceivers != null) {
11400 // If this is not the primary user, we need to check for
11401 // any receivers that should be filtered out.
11402 for (int i=0; i<newReceivers.size(); i++) {
11403 ResolveInfo ri = newReceivers.get(i);
11404 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11405 newReceivers.remove(i);
11406 i--;
11407 }
11408 }
11409 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011410 if (newReceivers != null && newReceivers.size() == 0) {
11411 newReceivers = null;
11412 }
11413 if (receivers == null) {
11414 receivers = newReceivers;
11415 } else if (newReceivers != null) {
11416 // We need to concatenate the additional receivers
11417 // found with what we have do far. This would be easy,
11418 // but we also need to de-dup any receivers that are
11419 // singleUser.
11420 if (!scannedFirstReceivers) {
11421 // Collect any single user receivers we had already retrieved.
11422 scannedFirstReceivers = true;
11423 for (int i=0; i<receivers.size(); i++) {
11424 ResolveInfo ri = receivers.get(i);
11425 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11426 ComponentName cn = new ComponentName(
11427 ri.activityInfo.packageName, ri.activityInfo.name);
11428 if (singleUserReceivers == null) {
11429 singleUserReceivers = new HashSet<ComponentName>();
11430 }
11431 singleUserReceivers.add(cn);
11432 }
11433 }
11434 }
11435 // Add the new results to the existing results, tracking
11436 // and de-dupping single user receivers.
11437 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011438 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011439 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11440 ComponentName cn = new ComponentName(
11441 ri.activityInfo.packageName, ri.activityInfo.name);
11442 if (singleUserReceivers == null) {
11443 singleUserReceivers = new HashSet<ComponentName>();
11444 }
11445 if (!singleUserReceivers.contains(cn)) {
11446 singleUserReceivers.add(cn);
11447 receivers.add(ri);
11448 }
11449 } else {
11450 receivers.add(ri);
11451 }
11452 }
11453 }
11454 }
11455 } catch (RemoteException ex) {
11456 // pm is in same process, this will never happen.
11457 }
11458 return receivers;
11459 }
11460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 private final int broadcastIntentLocked(ProcessRecord callerApp,
11462 String callerPackage, Intent intent, String resolvedType,
11463 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011464 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011465 boolean ordered, boolean sticky, int callingPid, int callingUid,
11466 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 intent = new Intent(intent);
11468
Dianne Hackborne7f97212011-02-24 14:40:20 -080011469 // By default broadcasts do not go to stopped apps.
11470 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11471
Joe Onorato8a9b2202010-02-26 18:56:32 -080011472 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011473 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011474 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011476 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011477 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011478
Dianne Hackborn139748f2012-09-24 11:36:57 -070011479 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011480 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011481
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011482 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011483 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011484 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011485 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11486 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11487 Slog.w(TAG, "Skipping broadcast of " + intent
11488 + ": user " + userId + " is stopped");
11489 return ActivityManager.BROADCAST_SUCCESS;
11490 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011491 }
11492
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011493 /*
11494 * Prevent non-system code (defined here to be non-persistent
11495 * processes) from sending protected broadcasts.
11496 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011497 int callingAppId = UserHandle.getAppId(callingUid);
11498 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11499 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 callingUid == 0) {
11501 // Always okay.
11502 } else if (callerApp == null || !callerApp.persistent) {
11503 try {
11504 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11505 intent.getAction())) {
11506 String msg = "Permission Denial: not allowed to send broadcast "
11507 + intent.getAction() + " from pid="
11508 + callingPid + ", uid=" + callingUid;
11509 Slog.w(TAG, msg);
11510 throw new SecurityException(msg);
11511 }
11512 } catch (RemoteException e) {
11513 Slog.w(TAG, "Remote exception", e);
11514 return ActivityManager.BROADCAST_SUCCESS;
11515 }
11516 }
11517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 // Handle special intents: if this broadcast is from the package
11519 // manager about a package being removed, we need to remove all of
11520 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011521 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011523 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11524 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011525 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 || uidRemoved) {
11527 if (checkComponentPermission(
11528 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011529 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 == PackageManager.PERMISSION_GRANTED) {
11531 if (uidRemoved) {
11532 final Bundle intentExtras = intent.getExtras();
11533 final int uid = intentExtras != null
11534 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11535 if (uid >= 0) {
11536 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11537 synchronized (bs) {
11538 bs.removeUidStatsLocked(uid);
11539 }
11540 }
11541 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011542 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011543 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011544 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011545 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11546 if (list != null && (list.length > 0)) {
11547 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011548 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011549 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011550 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011551 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011552 }
11553 } else {
11554 Uri data = intent.getData();
11555 String ssp;
11556 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11557 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11558 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011559 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11560 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011561 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011562 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011563 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011564 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 }
11567 }
11568 }
11569 } else {
11570 String msg = "Permission Denial: " + intent.getAction()
11571 + " broadcast from " + callerPackage + " (pid=" + callingPid
11572 + ", uid=" + callingUid + ")"
11573 + " requires "
11574 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011575 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 throw new SecurityException(msg);
11577 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011578
11579 // Special case for adding a package: by default turn on compatibility
11580 // mode.
11581 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011582 Uri data = intent.getData();
11583 String ssp;
11584 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11585 mCompatModePackages.handlePackageAddedLocked(ssp,
11586 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011588 }
11589
11590 /*
11591 * If this is the time zone changed action, queue up a message that will reset the timezone
11592 * of all currently running processes. This message will get queued up before the broadcast
11593 * happens.
11594 */
11595 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11596 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11597 }
11598
Robert Greenwalt03595d02010-11-02 14:08:23 -070011599 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11600 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11601 }
11602
Robert Greenwalt434203a2010-10-11 16:00:27 -070011603 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11604 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11605 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11606 }
11607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 // Add to the sticky list if requested.
11609 if (sticky) {
11610 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11611 callingPid, callingUid)
11612 != PackageManager.PERMISSION_GRANTED) {
11613 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11614 + callingPid + ", uid=" + callingUid
11615 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011616 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011617 throw new SecurityException(msg);
11618 }
11619 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011620 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011622 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 }
11624 if (intent.getComponent() != null) {
11625 throw new SecurityException(
11626 "Sticky broadcasts can't target a specific component");
11627 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011628 // We use userId directly here, since the "all" target is maintained
11629 // as a separate set of sticky broadcasts.
11630 if (userId != UserHandle.USER_ALL) {
11631 // But first, if this is not a broadcast to all users, then
11632 // make sure it doesn't conflict with an existing broadcast to
11633 // all users.
11634 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11635 UserHandle.USER_ALL);
11636 if (stickies != null) {
11637 ArrayList<Intent> list = stickies.get(intent.getAction());
11638 if (list != null) {
11639 int N = list.size();
11640 int i;
11641 for (i=0; i<N; i++) {
11642 if (intent.filterEquals(list.get(i))) {
11643 throw new IllegalArgumentException(
11644 "Sticky broadcast " + intent + " for user "
11645 + userId + " conflicts with existing global broadcast");
11646 }
11647 }
11648 }
11649 }
11650 }
11651 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11652 if (stickies == null) {
11653 stickies = new HashMap<String, ArrayList<Intent>>();
11654 mStickyBroadcasts.put(userId, stickies);
11655 }
11656 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011657 if (list == null) {
11658 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011659 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 }
11661 int N = list.size();
11662 int i;
11663 for (i=0; i<N; i++) {
11664 if (intent.filterEquals(list.get(i))) {
11665 // This sticky already exists, replace it.
11666 list.set(i, new Intent(intent));
11667 break;
11668 }
11669 }
11670 if (i >= N) {
11671 list.add(new Intent(intent));
11672 }
11673 }
11674
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011675 int[] users;
11676 if (userId == UserHandle.USER_ALL) {
11677 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011678 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011679 } else {
11680 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011681 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011682 }
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 // Figure out who all will receive this broadcast.
11685 List receivers = null;
11686 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011687 // Need to resolve the intent to interested receivers...
11688 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11689 == 0) {
11690 receivers = collectReceiverComponents(intent, resolvedType, users);
11691 }
11692 if (intent.getComponent() == null) {
11693 registeredReceivers = mReceiverResolver.queryIntent(intent,
11694 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 }
11696
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011697 final boolean replacePending =
11698 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11699
Joe Onorato8a9b2202010-02-26 18:56:32 -080011700 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011701 + " replacePending=" + replacePending);
11702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11704 if (!ordered && NR > 0) {
11705 // If we are not serializing this broadcast, then send the
11706 // registered receivers separately so they don't wait for the
11707 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011708 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11709 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011710 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011712 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011713 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011714 TAG, "Enqueueing parallel broadcast " + r);
11715 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011716 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011717 queue.enqueueParallelBroadcastLocked(r);
11718 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 registeredReceivers = null;
11721 NR = 0;
11722 }
11723
11724 // Merge into one list.
11725 int ir = 0;
11726 if (receivers != null) {
11727 // A special case for PACKAGE_ADDED: do not allow the package
11728 // being added to see this broadcast. This prevents them from
11729 // using this as a back door to get run as soon as they are
11730 // installed. Maybe in the future we want to have a special install
11731 // broadcast or such for apps, but we'd like to deliberately make
11732 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011733 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011734 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11735 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11736 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011737 Uri data = intent.getData();
11738 if (data != null) {
11739 String pkgName = data.getSchemeSpecificPart();
11740 if (pkgName != null) {
11741 skipPackages = new String[] { pkgName };
11742 }
11743 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011744 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011745 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011746 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011747 if (skipPackages != null && (skipPackages.length > 0)) {
11748 for (String skipPackage : skipPackages) {
11749 if (skipPackage != null) {
11750 int NT = receivers.size();
11751 for (int it=0; it<NT; it++) {
11752 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11753 if (curt.activityInfo.packageName.equals(skipPackage)) {
11754 receivers.remove(it);
11755 it--;
11756 NT--;
11757 }
11758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759 }
11760 }
11761 }
11762
11763 int NT = receivers != null ? receivers.size() : 0;
11764 int it = 0;
11765 ResolveInfo curt = null;
11766 BroadcastFilter curr = null;
11767 while (it < NT && ir < NR) {
11768 if (curt == null) {
11769 curt = (ResolveInfo)receivers.get(it);
11770 }
11771 if (curr == null) {
11772 curr = registeredReceivers.get(ir);
11773 }
11774 if (curr.getPriority() >= curt.priority) {
11775 // Insert this broadcast record into the final list.
11776 receivers.add(it, curr);
11777 ir++;
11778 curr = null;
11779 it++;
11780 NT++;
11781 } else {
11782 // Skip to the next ResolveInfo in the final list.
11783 it++;
11784 curt = null;
11785 }
11786 }
11787 }
11788 while (ir < NR) {
11789 if (receivers == null) {
11790 receivers = new ArrayList();
11791 }
11792 receivers.add(registeredReceivers.get(ir));
11793 ir++;
11794 }
11795
11796 if ((receivers != null && receivers.size() > 0)
11797 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011798 BroadcastQueue queue = broadcastQueueForIntent(intent);
11799 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011800 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011801 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011802 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011803 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011805 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 if (DEBUG_BROADCAST) {
11807 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011808 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011810 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011811 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011812 queue.enqueueOrderedBroadcastLocked(r);
11813 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 }
11816
Dianne Hackborna4972e92012-03-14 10:38:05 -070011817 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 }
11819
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011820 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 // Refuse possible leaked file descriptors
11822 if (intent != null && intent.hasFileDescriptors() == true) {
11823 throw new IllegalArgumentException("File descriptors passed in Intent");
11824 }
11825
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011826 int flags = intent.getFlags();
11827
11828 if (!mProcessesReady) {
11829 // if the caller really truly claims to know what they're doing, go
11830 // ahead and allow the broadcast without launching any receivers
11831 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11832 intent = new Intent(intent);
11833 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11834 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11835 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11836 + " before boot completion");
11837 throw new IllegalStateException("Cannot broadcast before boot completed");
11838 }
11839 }
11840
11841 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11842 throw new IllegalArgumentException(
11843 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11844 }
11845
11846 return intent;
11847 }
11848
11849 public final int broadcastIntent(IApplicationThread caller,
11850 Intent intent, String resolvedType, IIntentReceiver resultTo,
11851 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011852 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011853 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011854 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011855 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011857 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11858 final int callingPid = Binder.getCallingPid();
11859 final int callingUid = Binder.getCallingUid();
11860 final long origId = Binder.clearCallingIdentity();
11861 int res = broadcastIntentLocked(callerApp,
11862 callerApp != null ? callerApp.info.packageName : null,
11863 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011864 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070011865 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011866 Binder.restoreCallingIdentity(origId);
11867 return res;
11868 }
11869 }
11870
11871 int broadcastIntentInPackage(String packageName, int uid,
11872 Intent intent, String resolvedType, IIntentReceiver resultTo,
11873 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011874 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011876 intent = verifyBroadcastLocked(intent);
11877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 final long origId = Binder.clearCallingIdentity();
11879 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11880 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011881 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 Binder.restoreCallingIdentity(origId);
11883 return res;
11884 }
11885 }
11886
Amith Yamasani742a6712011-05-04 14:49:28 -070011887 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 // Refuse possible leaked file descriptors
11889 if (intent != null && intent.hasFileDescriptors() == true) {
11890 throw new IllegalArgumentException("File descriptors passed in Intent");
11891 }
11892
Dianne Hackborn139748f2012-09-24 11:36:57 -070011893 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011894 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 synchronized(this) {
11897 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11898 != PackageManager.PERMISSION_GRANTED) {
11899 String msg = "Permission Denial: unbroadcastIntent() from pid="
11900 + Binder.getCallingPid()
11901 + ", uid=" + Binder.getCallingUid()
11902 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011903 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 throw new SecurityException(msg);
11905 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011906 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11907 if (stickies != null) {
11908 ArrayList<Intent> list = stickies.get(intent.getAction());
11909 if (list != null) {
11910 int N = list.size();
11911 int i;
11912 for (i=0; i<N; i++) {
11913 if (intent.filterEquals(list.get(i))) {
11914 list.remove(i);
11915 break;
11916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011917 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011918 if (list.size() <= 0) {
11919 stickies.remove(intent.getAction());
11920 }
11921 }
11922 if (stickies.size() <= 0) {
11923 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 }
11925 }
11926 }
11927 }
11928
11929 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11930 String resultData, Bundle resultExtras, boolean resultAbort,
11931 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011932 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11933 if (r == null) {
11934 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 return false;
11936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937
Christopher Tatef46723b2012-01-26 14:19:24 -080011938 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11939 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940 }
11941
11942 public void finishReceiver(IBinder who, int resultCode, String resultData,
11943 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011944 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011945
11946 // Refuse possible leaked file descriptors
11947 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11948 throw new IllegalArgumentException("File descriptors passed in Bundle");
11949 }
11950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011952 try {
11953 boolean doNext = false;
11954 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955
Christopher Tatef46723b2012-01-26 14:19:24 -080011956 synchronized(this) {
11957 r = broadcastRecordForReceiverLocked(who);
11958 if (r != null) {
11959 doNext = r.queue.finishReceiverLocked(r, resultCode,
11960 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011963
Christopher Tatef46723b2012-01-26 14:19:24 -080011964 if (doNext) {
11965 r.queue.processNextBroadcast(false);
11966 }
11967 trimApplications();
11968 } finally {
11969 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 // =========================================================
11974 // INSTRUMENTATION
11975 // =========================================================
11976
11977 public boolean startInstrumentation(ComponentName className,
11978 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080011979 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
11980 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011981 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070011982 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011983 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 // Refuse possible leaked file descriptors
11985 if (arguments != null && arguments.hasFileDescriptors()) {
11986 throw new IllegalArgumentException("File descriptors passed in Bundle");
11987 }
11988
11989 synchronized(this) {
11990 InstrumentationInfo ii = null;
11991 ApplicationInfo ai = null;
11992 try {
11993 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011994 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011995 ai = AppGlobals.getPackageManager().getApplicationInfo(
11996 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011998 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 }
12000 if (ii == null) {
12001 reportStartInstrumentationFailure(watcher, className,
12002 "Unable to find instrumentation info for: " + className);
12003 return false;
12004 }
12005 if (ai == null) {
12006 reportStartInstrumentationFailure(watcher, className,
12007 "Unable to find instrumentation target package: " + ii.targetPackage);
12008 return false;
12009 }
12010
12011 int match = mContext.getPackageManager().checkSignatures(
12012 ii.targetPackage, ii.packageName);
12013 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12014 String msg = "Permission Denial: starting instrumentation "
12015 + className + " from pid="
12016 + Binder.getCallingPid()
12017 + ", uid=" + Binder.getCallingPid()
12018 + " not allowed because package " + ii.packageName
12019 + " does not have a signature matching the target "
12020 + ii.targetPackage;
12021 reportStartInstrumentationFailure(watcher, className, msg);
12022 throw new SecurityException(msg);
12023 }
12024
12025 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012026 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012027 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012028 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012030 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012031 app.instrumentationProfileFile = profileFile;
12032 app.instrumentationArguments = arguments;
12033 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012034 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 app.instrumentationResultClass = className;
12036 Binder.restoreCallingIdentity(origId);
12037 }
12038
12039 return true;
12040 }
12041
12042 /**
12043 * Report errors that occur while attempting to start Instrumentation. Always writes the
12044 * error to the logs, but if somebody is watching, send the report there too. This enables
12045 * the "am" command to report errors with more information.
12046 *
12047 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12048 * @param cn The component name of the instrumentation.
12049 * @param report The error report.
12050 */
12051 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12052 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012053 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 try {
12055 if (watcher != null) {
12056 Bundle results = new Bundle();
12057 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12058 results.putString("Error", report);
12059 watcher.instrumentationStatus(cn, -1, results);
12060 }
12061 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012062 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 }
12064 }
12065
12066 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12067 if (app.instrumentationWatcher != null) {
12068 try {
12069 // NOTE: IInstrumentationWatcher *must* be oneway here
12070 app.instrumentationWatcher.instrumentationFinished(
12071 app.instrumentationClass,
12072 resultCode,
12073 results);
12074 } catch (RemoteException e) {
12075 }
12076 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012077 if (app.instrumentationUiAutomationConnection != null) {
12078 try {
12079 app.instrumentationUiAutomationConnection.shutdown();
12080 } catch (RemoteException re) {
12081 /* ignore */
12082 }
12083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012085 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012087 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 app.instrumentationProfileFile = null;
12089 app.instrumentationArguments = null;
12090
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012091 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 }
12093
12094 public void finishInstrumentation(IApplicationThread target,
12095 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012096 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 // Refuse possible leaked file descriptors
12098 if (results != null && results.hasFileDescriptors()) {
12099 throw new IllegalArgumentException("File descriptors passed in Intent");
12100 }
12101
12102 synchronized(this) {
12103 ProcessRecord app = getRecordForAppLocked(target);
12104 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012105 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 return;
12107 }
12108 final long origId = Binder.clearCallingIdentity();
12109 finishInstrumentationLocked(app, resultCode, results);
12110 Binder.restoreCallingIdentity(origId);
12111 }
12112 }
12113
12114 // =========================================================
12115 // CONFIGURATION
12116 // =========================================================
12117
12118 public ConfigurationInfo getDeviceConfigurationInfo() {
12119 ConfigurationInfo config = new ConfigurationInfo();
12120 synchronized (this) {
12121 config.reqTouchScreen = mConfiguration.touchscreen;
12122 config.reqKeyboardType = mConfiguration.keyboard;
12123 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012124 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12125 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12127 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012128 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12129 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12131 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012132 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 }
12134 return config;
12135 }
12136
12137 public Configuration getConfiguration() {
12138 Configuration ci;
12139 synchronized(this) {
12140 ci = new Configuration(mConfiguration);
12141 }
12142 return ci;
12143 }
12144
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012145 public void updatePersistentConfiguration(Configuration values) {
12146 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12147 "updateConfiguration()");
12148 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12149 "updateConfiguration()");
12150 if (values == null) {
12151 throw new NullPointerException("Configuration must not be null");
12152 }
12153
12154 synchronized(this) {
12155 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012156 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012157 Binder.restoreCallingIdentity(origId);
12158 }
12159 }
12160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012161 public void updateConfiguration(Configuration values) {
12162 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12163 "updateConfiguration()");
12164
12165 synchronized(this) {
12166 if (values == null && mWindowManager != null) {
12167 // sentinel: fetch the current configuration from the window manager
12168 values = mWindowManager.computeNewConfiguration();
12169 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012170
12171 if (mWindowManager != null) {
12172 mProcessList.applyDisplaySize(mWindowManager);
12173 }
12174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012175 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012176 if (values != null) {
12177 Settings.System.clearConfiguration(values);
12178 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012179 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012180 Binder.restoreCallingIdentity(origId);
12181 }
12182 }
12183
12184 /**
12185 * Do either or both things: (1) change the current configuration, and (2)
12186 * make sure the given activity is running with the (now) current
12187 * configuration. Returns true if the activity has been left running, or
12188 * false if <var>starting</var> is being destroyed to match the new
12189 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012190 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012192 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012193 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012194 // do nothing if we are headless
12195 if (mHeadless) return true;
12196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 int changes = 0;
12198
12199 boolean kept = true;
12200
12201 if (values != null) {
12202 Configuration newConfig = new Configuration(mConfiguration);
12203 changes = newConfig.updateFrom(values);
12204 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012205 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012206 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 }
12208
Doug Zongker2bec3d42009-12-04 12:52:44 -080012209 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210
Dianne Hackborn813075a62011-11-14 17:45:19 -080012211 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 saveLocaleLocked(values.locale,
12213 !values.locale.equals(mConfiguration.locale),
12214 values.userSetLocale);
12215 }
12216
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012217 mConfigurationSeq++;
12218 if (mConfigurationSeq <= 0) {
12219 mConfigurationSeq = 1;
12220 }
12221 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012223 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012224
12225 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012226
12227 // TODO: If our config changes, should we auto dismiss any currently
12228 // showing dialogs?
12229 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012230
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012231 AttributeCache ac = AttributeCache.instance();
12232 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012233 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012236 // Make sure all resources in our process are updated
12237 // right now, so that anyone who is going to retrieve
12238 // resource values after we return will be sure to get
12239 // the new ones. This is especially important during
12240 // boot, where the first config change needs to guarantee
12241 // all resources have that config before following boot
12242 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012243 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012244
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012245 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012246 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012247 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012248 mHandler.sendMessage(msg);
12249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012250
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012251 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12252 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 try {
12254 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012255 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012256 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012257 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258 }
12259 } catch (Exception e) {
12260 }
12261 }
12262 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012263 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012264 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12265 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012267 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12268 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012269 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012270 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12271 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12272 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012273 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12274 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 }
12277 }
12278
12279 if (changes != 0 && starting == null) {
12280 // If the configuration changed, and the caller is not already
12281 // in the process of starting an activity, then find the top
12282 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012283 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 }
12285
12286 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012287 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012288 // And we need to make sure at this point that all other activities
12289 // are made visible with the correct configuration.
12290 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012291 }
12292
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012293 if (values != null && mWindowManager != null) {
12294 mWindowManager.setNewConfiguration(mConfiguration);
12295 }
12296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012297 return kept;
12298 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012299
12300 /**
12301 * Decide based on the configuration whether we should shouw the ANR,
12302 * crash, etc dialogs. The idea is that if there is no affordnace to
12303 * press the on-screen buttons, we shouldn't show the dialog.
12304 *
12305 * A thought: SystemUI might also want to get told about this, the Power
12306 * dialog / global actions also might want different behaviors.
12307 */
12308 private static final boolean shouldShowDialogs(Configuration config) {
12309 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12310 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012312
12313 /**
12314 * Save the locale. You must be inside a synchronized (this) block.
12315 */
12316 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12317 if(isDiff) {
12318 SystemProperties.set("user.language", l.getLanguage());
12319 SystemProperties.set("user.region", l.getCountry());
12320 }
12321
12322 if(isPersist) {
12323 SystemProperties.set("persist.sys.language", l.getLanguage());
12324 SystemProperties.set("persist.sys.country", l.getCountry());
12325 SystemProperties.set("persist.sys.localevar", l.getVariant());
12326 }
12327 }
12328
Adam Powelldd8fab22012-03-22 17:47:27 -070012329 @Override
12330 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12331 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012332 return srec != null && srec.task.affinity != null &&
12333 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012334 }
12335
12336 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12337 Intent resultData) {
Adam Powelldd8fab22012-03-22 17:47:27 -070012338
12339 synchronized (this) {
12340 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012341 if (srec == null) {
12342 return false;
12343 }
Craig Mautnercae015f2013-02-08 14:31:27 -080012344 ActivityStack stack = srec.stack;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080012345 return stack.navigateUpToLocked(srec, destIntent, resultCode, resultData);
Adam Powelldd8fab22012-03-22 17:47:27 -070012346 }
12347 }
12348
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012349 public int getLaunchedFromUid(IBinder activityToken) {
12350 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12351 if (srec == null) {
12352 return -1;
12353 }
12354 return srec.launchedFromUid;
12355 }
12356
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012357 public String getLaunchedFromPackage(IBinder activityToken) {
12358 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12359 if (srec == null) {
12360 return null;
12361 }
12362 return srec.launchedFromPackage;
12363 }
12364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012365 // =========================================================
12366 // LIFETIME MANAGEMENT
12367 // =========================================================
12368
Christopher Tatef46723b2012-01-26 14:19:24 -080012369 // Returns which broadcast queue the app is the current [or imminent] receiver
12370 // on, or 'null' if the app is not an active broadcast recipient.
12371 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12372 BroadcastRecord r = app.curReceiver;
12373 if (r != null) {
12374 return r.queue;
12375 }
12376
12377 // It's not the current receiver, but it might be starting up to become one
12378 synchronized (this) {
12379 for (BroadcastQueue queue : mBroadcastQueues) {
12380 r = queue.mPendingBroadcast;
12381 if (r != null && r.curApp == app) {
12382 // found it; report which queue it's in
12383 return queue;
12384 }
12385 }
12386 }
12387
12388 return null;
12389 }
12390
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012391 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012392 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012393 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012394 // This adjustment has already been computed. If we are calling
12395 // from the top, we may have already computed our adjustment with
12396 // an earlier hidden adjustment that isn't really for us... if
12397 // so, use the new hidden adjustment.
12398 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012399 if (app.hasActivities) {
12400 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12401 } else if (app.hasClientActivities) {
12402 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12403 } else {
12404 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12405 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012406 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012407 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012408 }
12409
12410 if (app.thread == null) {
12411 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012412 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012413 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 }
12415
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012416 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12417 app.adjSource = null;
12418 app.adjTarget = null;
12419 app.empty = false;
12420 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012421 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012422
12423 final int activitiesSize = app.activities.size();
12424
Dianne Hackborn7d608422011-08-07 16:24:18 -070012425 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012426 // The max adjustment doesn't allow this app to be anything
12427 // below foreground, so it is not worth doing work for it.
12428 app.adjType = "fixed";
12429 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012430 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012431 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012432 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012433 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012434 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012435 // System process can do UI, and when they do we want to have
12436 // them trim their memory after the user leaves the UI. To
12437 // facilitate this, here we need to determine whether or not it
12438 // is currently showing UI.
12439 app.systemNoUi = true;
12440 if (app == TOP_APP) {
12441 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012442 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012443 } else if (activitiesSize > 0) {
12444 for (int j = 0; j < activitiesSize; j++) {
12445 final ActivityRecord r = app.activities.get(j);
12446 if (r.visible) {
12447 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012448 }
12449 if (r.app == app) {
12450 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012451 }
12452 }
12453 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012454 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012455 }
12456
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012457 app.keeping = false;
12458 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012459 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012460
The Android Open Source Project4df24232009-03-05 14:34:35 -080012461 // Determine the importance of the process, starting with most
12462 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012464 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012465 boolean foregroundActivities = false;
12466 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012467 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012468 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012470 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012471 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012472 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012473 foregroundActivities = true;
12474 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012475 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012476 } else if (app.instrumentationClass != null) {
12477 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012478 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012479 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012480 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012481 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012482 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012484 // counts as being in the foreground for OOM killer purposes.
12485 // It's placed in a sched group based on the nature of the
12486 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012487 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012488 schedGroup = (queue == mFgBroadcastQueue)
12489 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012490 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 } else if (app.executingServices.size() > 0) {
12492 // An app that is currently executing a service callback also
12493 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012494 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012495 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012496 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012497 } else {
12498 // Assume process is hidden (has activities); we will correct
12499 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012501 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012502 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012503 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012505
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012506 boolean hasStoppingActivities = false;
12507
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012508 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012509 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012510 for (int j = 0; j < activitiesSize; j++) {
12511 final ActivityRecord r = app.activities.get(j);
12512 if (r.visible) {
12513 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012514 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12515 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012516 app.adjType = "visible";
12517 }
12518 schedGroup = Process.THREAD_GROUP_DEFAULT;
12519 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012520 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012521 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012522 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012523 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012524 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12525 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012526 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012527 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012528 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012529 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012530 } else if (r.state == ActivityState.STOPPING) {
12531 // We will apply the actual adjustment later, because
12532 // we want to allow this process to immediately go through
12533 // any memory trimming that is in effect.
12534 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012535 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012536 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012537 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012538 if (r.app == app) {
12539 app.hasActivities = true;
12540 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012541 }
12542 }
12543
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012544 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012545 if (app.hasClientActivities) {
12546 adj = clientHiddenAdj;
12547 app.adjType = "bg-client-act";
12548 } else {
12549 // Whoops, this process is completely empty as far as we know
12550 // at this point.
12551 adj = emptyAdj;
12552 app.empty = true;
12553 app.adjType = "bg-empty";
12554 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012555 }
12556
Dianne Hackborn7d608422011-08-07 16:24:18 -070012557 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012558 if (app.foregroundServices) {
12559 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012560 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012561 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012562 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012563 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012564 } else if (app.forcingToForeground != null) {
12565 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012566 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012567 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012568 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012569 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012570 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012571 }
12572 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012573
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012574 if (app.foregroundServices) {
12575 interesting = true;
12576 }
12577
Dianne Hackborn7d608422011-08-07 16:24:18 -070012578 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012579 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012580 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012581 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012582 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012583 app.adjType = "heavy";
12584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585
Dianne Hackborn7d608422011-08-07 16:24:18 -070012586 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012587 // This process is hosting what we currently consider to be the
12588 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012589 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012590 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012591 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012592 app.adjType = "home";
12593 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012594
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012595 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12596 && app.activities.size() > 0) {
12597 // This was the previous process that showed UI to the user.
12598 // We want to try to keep it around more aggressively, to give
12599 // a good experience around switching between two apps.
12600 adj = ProcessList.PREVIOUS_APP_ADJ;
12601 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12602 app.hidden = false;
12603 app.adjType = "previous";
12604 }
12605
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012606 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12607 + " reason=" + app.adjType);
12608
The Android Open Source Project4df24232009-03-05 14:34:35 -080012609 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 // there are applications dependent on our services or providers, but
12611 // this gives us a baseline and makes sure we don't get into an
12612 // infinite recursion.
12613 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012614 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615
Christopher Tate6fa95972009-06-05 18:43:55 -070012616 if (mBackupTarget != null && app == mBackupTarget.app) {
12617 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012618 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012619 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012620 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012621 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012622 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012623 }
12624 }
12625
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012627 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 final long now = SystemClock.uptimeMillis();
12629 // This process is more important if the top activity is
12630 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012631 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012633 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012634 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012635 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012636 // If this process has shown some UI, let it immediately
12637 // go to the LRU list because it may be pretty heavy with
12638 // UI stuff. We'll tag it with a label just to help
12639 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012640 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012641 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012643 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012644 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012645 // This service has seen some activity within
12646 // recent memory, so we will keep its process ahead
12647 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012648 if (adj > ProcessList.SERVICE_ADJ) {
12649 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012650 app.adjType = "started-services";
12651 app.hidden = false;
12652 }
12653 }
12654 // If we have let the service slide into the background
12655 // state, still have some text describing what it is doing
12656 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012657 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012658 app.adjType = "started-bg-services";
12659 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012660 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012661 // Don't kill this process because it is doing work; it
12662 // has said it is doing work.
12663 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012665 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012666 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012667 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012668 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012669 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012670 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012671 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012672 // XXX should compute this based on the max of
12673 // all connected clients.
12674 ConnectionRecord cr = clist.get(i);
12675 if (cr.binding.client == app) {
12676 // Binding to ourself is not interesting.
12677 continue;
12678 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012679 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012680 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012681 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012682 int myHiddenAdj = hiddenAdj;
12683 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012684 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012685 myHiddenAdj = client.hiddenAdj;
12686 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012687 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012688 }
12689 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012690 int myClientHiddenAdj = clientHiddenAdj;
12691 if (myClientHiddenAdj > client.clientHiddenAdj) {
12692 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12693 myClientHiddenAdj = client.clientHiddenAdj;
12694 } else {
12695 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12696 }
12697 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012698 int myEmptyAdj = emptyAdj;
12699 if (myEmptyAdj > client.emptyAdj) {
12700 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12701 myEmptyAdj = client.emptyAdj;
12702 } else {
12703 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12704 }
12705 }
12706 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012707 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012708 String adjType = null;
12709 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12710 // Not doing bind OOM management, so treat
12711 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012712 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012713 // If this process has shown some UI, let it immediately
12714 // go to the LRU list because it may be pretty heavy with
12715 // UI stuff. We'll tag it with a label just to help
12716 // debug and understand what is going on.
12717 if (adj > clientAdj) {
12718 adjType = "bound-bg-ui-services";
12719 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012720 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012721 clientAdj = adj;
12722 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012723 if (now >= (s.lastActivity
12724 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012725 // This service has not seen activity within
12726 // recent memory, so allow it to drop to the
12727 // LRU list if there is no other reason to keep
12728 // it around. We'll also tag it with a label just
12729 // to help debug and undertand what is going on.
12730 if (adj > clientAdj) {
12731 adjType = "bound-bg-services";
12732 }
12733 clientAdj = adj;
12734 }
12735 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012736 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12737 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12738 // If this connection is keeping the service
12739 // created, then we want to try to better follow
12740 // its memory management semantics for activities.
12741 // That is, if it is sitting in the background
12742 // LRU list as a hidden process (with activities),
12743 // we don't want the service it is connected to
12744 // to go into the empty LRU and quickly get killed,
12745 // because I'll we'll do is just end up restarting
12746 // the service.
12747 app.hasClientActivities |= client.hasActivities;
12748 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012749 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012750 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012751 // If this process has recently shown UI, and
12752 // the process that is binding to it is less
12753 // important than being visible, then we don't
12754 // care about the binding as much as we care
12755 // about letting this process get into the LRU
12756 // list to be killed and restarted if needed for
12757 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012758 if (app.hasShownUi && app != mHomeProcess
12759 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012760 adjType = "bound-bg-ui-services";
12761 } else {
12762 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12763 |Context.BIND_IMPORTANT)) != 0) {
12764 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012765 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12766 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12767 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12768 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12769 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012770 adj = clientAdj;
12771 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012772 app.pendingUiClean = true;
12773 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12774 adj = ProcessList.VISIBLE_APP_ADJ;
12775 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012776 }
12777 if (!client.hidden) {
12778 app.hidden = false;
12779 }
12780 if (client.keeping) {
12781 app.keeping = true;
12782 }
12783 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012784 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012785 }
12786 if (adjType != null) {
12787 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012788 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12789 .REASON_SERVICE_IN_USE;
12790 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012791 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012792 app.adjTarget = s.name;
12793 }
12794 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12795 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12796 schedGroup = Process.THREAD_GROUP_DEFAULT;
12797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 }
12799 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012800 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012801 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012802 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012803 (a.visible || a.state == ActivityState.RESUMED
12804 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012805 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012806 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12807 schedGroup = Process.THREAD_GROUP_DEFAULT;
12808 }
12809 app.hidden = false;
12810 app.adjType = "service";
12811 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12812 .REASON_SERVICE_IN_USE;
12813 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012814 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012815 app.adjTarget = s.name;
12816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 }
12819 }
12820 }
12821 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012822
Dianne Hackborn287952c2010-09-22 22:34:31 -070012823 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012824 // would like to avoid killing it unless it would prevent the current
12825 // application from running. By default we put the process in
12826 // with the rest of the background processes; as we scan through
12827 // its services we may bump it up from there.
12828 if (adj > hiddenAdj) {
12829 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012830 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012831 app.adjType = "bg-services";
12832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
12834
Dianne Hackborn7d608422011-08-07 16:24:18 -070012835 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012836 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012837 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012838 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012839 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012840 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012841 for (int i = cpr.connections.size()-1;
12842 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12843 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12844 i--) {
12845 ContentProviderConnection conn = cpr.connections.get(i);
12846 ProcessRecord client = conn.client;
12847 if (client == app) {
12848 // Being our own client is not interesting.
12849 continue;
12850 }
12851 int myHiddenAdj = hiddenAdj;
12852 if (myHiddenAdj > client.hiddenAdj) {
12853 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12854 myHiddenAdj = client.hiddenAdj;
12855 } else {
12856 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012857 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012858 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012859 int myClientHiddenAdj = clientHiddenAdj;
12860 if (myClientHiddenAdj > client.clientHiddenAdj) {
12861 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
12862 myClientHiddenAdj = client.clientHiddenAdj;
12863 } else {
12864 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
12865 }
12866 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012867 int myEmptyAdj = emptyAdj;
12868 if (myEmptyAdj > client.emptyAdj) {
12869 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12870 myEmptyAdj = client.emptyAdj;
12871 } else {
12872 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12873 }
12874 }
12875 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012876 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012877 if (adj > clientAdj) {
12878 if (app.hasShownUi && app != mHomeProcess
12879 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12880 app.adjType = "bg-ui-provider";
12881 } else {
12882 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12883 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12884 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012886 if (!client.hidden) {
12887 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012888 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012889 if (client.keeping) {
12890 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012891 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012892 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12893 .REASON_PROVIDER_IN_USE;
12894 app.adjSource = client;
12895 app.adjSourceOom = clientAdj;
12896 app.adjTarget = cpr.name;
12897 }
12898 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12899 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 }
12901 }
12902 // If the provider has external (non-framework) process
12903 // dependencies, ensure that its adjustment is at least
12904 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012905 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012906 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12907 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012908 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012909 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012910 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012911 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012912 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012913 }
12914 }
12915 }
12916 }
12917
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012918 if (adj == ProcessList.SERVICE_ADJ) {
12919 if (doingAll) {
12920 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12921 mNewNumServiceProcs++;
12922 }
12923 if (app.serviceb) {
12924 adj = ProcessList.SERVICE_B_ADJ;
12925 }
12926 } else {
12927 app.serviceb = false;
12928 }
12929
12930 app.nonStoppingAdj = adj;
12931
12932 if (hasStoppingActivities) {
12933 // Only upgrade adjustment.
12934 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12935 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12936 app.adjType = "stopping";
12937 }
12938 }
12939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 app.curRawAdj = adj;
12941
Joe Onorato8a9b2202010-02-26 18:56:32 -080012942 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12944 if (adj > app.maxAdj) {
12945 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012946 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012947 schedGroup = Process.THREAD_GROUP_DEFAULT;
12948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012950 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012951 app.keeping = true;
12952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012954 if (app.hasAboveClient) {
12955 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12956 // then we need to drop its adjustment to be lower than the service's
12957 // in order to honor the request. We want to drop it by one adjustment
12958 // level... but there is special meaning applied to various levels so
12959 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012960 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012961 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012962 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12963 adj = ProcessList.VISIBLE_APP_ADJ;
12964 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12965 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12966 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12967 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012968 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012969 adj++;
12970 }
12971 }
12972
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012973 int importance = app.memImportance;
12974 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12975 app.curAdj = adj;
12976 app.curSchedGroup = schedGroup;
12977 if (!interesting) {
12978 // For this reporting, if there is not something explicitly
12979 // interesting in this process then we will push it to the
12980 // background importance.
12981 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12982 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12983 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12984 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12985 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12986 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12987 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12988 } else if (adj >= ProcessList.SERVICE_ADJ) {
12989 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12990 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12991 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12992 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12993 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12994 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12995 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12996 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12997 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12998 } else {
12999 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13000 }
13001 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013002
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013003 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13004 if (foregroundActivities != app.foregroundActivities) {
13005 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13006 }
13007 if (changes != 0) {
13008 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13009 app.memImportance = importance;
13010 app.foregroundActivities = foregroundActivities;
13011 int i = mPendingProcessChanges.size()-1;
13012 ProcessChangeItem item = null;
13013 while (i >= 0) {
13014 item = mPendingProcessChanges.get(i);
13015 if (item.pid == app.pid) {
13016 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13017 break;
13018 }
13019 i--;
13020 }
13021 if (i < 0) {
13022 // No existing item in pending changes; need a new one.
13023 final int NA = mAvailProcessChanges.size();
13024 if (NA > 0) {
13025 item = mAvailProcessChanges.remove(NA-1);
13026 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13027 } else {
13028 item = new ProcessChangeItem();
13029 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13030 }
13031 item.changes = 0;
13032 item.pid = app.pid;
13033 item.uid = app.info.uid;
13034 if (mPendingProcessChanges.size() == 0) {
13035 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13036 "*** Enqueueing dispatch processes changed!");
13037 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13038 }
13039 mPendingProcessChanges.add(item);
13040 }
13041 item.changes |= changes;
13042 item.importance = importance;
13043 item.foregroundActivities = foregroundActivities;
13044 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13045 + Integer.toHexString(System.identityHashCode(item))
13046 + " " + app.toShortString() + ": changes=" + item.changes
13047 + " importance=" + item.importance
13048 + " foreground=" + item.foregroundActivities
13049 + " type=" + app.adjType + " source=" + app.adjSource
13050 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013051 }
13052
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013053 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 }
13055
13056 /**
13057 * Ask a given process to GC right now.
13058 */
13059 final void performAppGcLocked(ProcessRecord app) {
13060 try {
13061 app.lastRequestedGc = SystemClock.uptimeMillis();
13062 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013063 if (app.reportLowMemory) {
13064 app.reportLowMemory = false;
13065 app.thread.scheduleLowMemory();
13066 } else {
13067 app.thread.processInBackground();
13068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013069 }
13070 } catch (Exception e) {
13071 // whatever.
13072 }
13073 }
13074
13075 /**
13076 * Returns true if things are idle enough to perform GCs.
13077 */
Josh Bartel7f208742010-02-25 11:01:44 -060013078 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013079 boolean processingBroadcasts = false;
13080 for (BroadcastQueue q : mBroadcastQueues) {
13081 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13082 processingBroadcasts = true;
13083 }
13084 }
13085 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013086 && (mSleeping || (mMainStack.mResumedActivity != null &&
13087 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 }
13089
13090 /**
13091 * Perform GCs on all processes that are waiting for it, but only
13092 * if things are idle.
13093 */
13094 final void performAppGcsLocked() {
13095 final int N = mProcessesToGc.size();
13096 if (N <= 0) {
13097 return;
13098 }
Josh Bartel7f208742010-02-25 11:01:44 -060013099 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013100 while (mProcessesToGc.size() > 0) {
13101 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013102 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013103 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13104 <= SystemClock.uptimeMillis()) {
13105 // To avoid spamming the system, we will GC processes one
13106 // at a time, waiting a few seconds between each.
13107 performAppGcLocked(proc);
13108 scheduleAppGcsLocked();
13109 return;
13110 } else {
13111 // It hasn't been long enough since we last GCed this
13112 // process... put it in the list to wait for its time.
13113 addProcessToGcListLocked(proc);
13114 break;
13115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 }
13117 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013118
13119 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013120 }
13121 }
13122
13123 /**
13124 * If all looks good, perform GCs on all processes waiting for them.
13125 */
13126 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013127 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 performAppGcsLocked();
13129 return;
13130 }
13131 // Still not idle, wait some more.
13132 scheduleAppGcsLocked();
13133 }
13134
13135 /**
13136 * Schedule the execution of all pending app GCs.
13137 */
13138 final void scheduleAppGcsLocked() {
13139 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013140
13141 if (mProcessesToGc.size() > 0) {
13142 // Schedule a GC for the time to the next process.
13143 ProcessRecord proc = mProcessesToGc.get(0);
13144 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13145
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013146 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013147 long now = SystemClock.uptimeMillis();
13148 if (when < (now+GC_TIMEOUT)) {
13149 when = now + GC_TIMEOUT;
13150 }
13151 mHandler.sendMessageAtTime(msg, when);
13152 }
13153 }
13154
13155 /**
13156 * Add a process to the array of processes waiting to be GCed. Keeps the
13157 * list in sorted order by the last GC time. The process can't already be
13158 * on the list.
13159 */
13160 final void addProcessToGcListLocked(ProcessRecord proc) {
13161 boolean added = false;
13162 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13163 if (mProcessesToGc.get(i).lastRequestedGc <
13164 proc.lastRequestedGc) {
13165 added = true;
13166 mProcessesToGc.add(i+1, proc);
13167 break;
13168 }
13169 }
13170 if (!added) {
13171 mProcessesToGc.add(0, proc);
13172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013173 }
13174
13175 /**
13176 * Set up to ask a process to GC itself. This will either do it
13177 * immediately, or put it on the list of processes to gc the next
13178 * time things are idle.
13179 */
13180 final void scheduleAppGcLocked(ProcessRecord app) {
13181 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013182 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013183 return;
13184 }
13185 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013186 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 scheduleAppGcsLocked();
13188 }
13189 }
13190
Dianne Hackborn287952c2010-09-22 22:34:31 -070013191 final void checkExcessivePowerUsageLocked(boolean doKills) {
13192 updateCpuStatsNow();
13193
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013194 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013195 boolean doWakeKills = doKills;
13196 boolean doCpuKills = doKills;
13197 if (mLastPowerCheckRealtime == 0) {
13198 doWakeKills = false;
13199 }
13200 if (mLastPowerCheckUptime == 0) {
13201 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013202 }
13203 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013204 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013205 }
13206 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013207 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13208 final long curUptime = SystemClock.uptimeMillis();
13209 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13210 mLastPowerCheckRealtime = curRealtime;
13211 mLastPowerCheckUptime = curUptime;
13212 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13213 doWakeKills = false;
13214 }
13215 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13216 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013217 }
13218 int i = mLruProcesses.size();
13219 while (i > 0) {
13220 i--;
13221 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013222 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013223 long wtime;
13224 synchronized (stats) {
13225 wtime = stats.getProcessWakeTime(app.info.uid,
13226 app.pid, curRealtime);
13227 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 long wtimeUsed = wtime - app.lastWakeTime;
13229 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13230 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013231 StringBuilder sb = new StringBuilder(128);
13232 sb.append("Wake for ");
13233 app.toShortString(sb);
13234 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013235 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013236 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013237 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013238 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013239 sb.append((wtimeUsed*100)/realtimeSince);
13240 sb.append("%)");
13241 Slog.i(TAG, sb.toString());
13242 sb.setLength(0);
13243 sb.append("CPU for ");
13244 app.toShortString(sb);
13245 sb.append(": over ");
13246 TimeUtils.formatDuration(uptimeSince, sb);
13247 sb.append(" used ");
13248 TimeUtils.formatDuration(cputimeUsed, sb);
13249 sb.append(" (");
13250 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013251 sb.append("%)");
13252 Slog.i(TAG, sb.toString());
13253 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013254 // If a process has held a wake lock for more
13255 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013256 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013257 if (doWakeKills && realtimeSince > 0
13258 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13259 synchronized (stats) {
13260 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13261 realtimeSince, wtimeUsed);
13262 }
13263 Slog.w(TAG, "Excessive wake lock in " + app.processName
13264 + " (pid " + app.pid + "): held " + wtimeUsed
13265 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013266 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013267 app.processName, app.setAdj, "excessive wake lock");
13268 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013269 } else if (doCpuKills && uptimeSince > 0
13270 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13271 synchronized (stats) {
13272 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13273 uptimeSince, cputimeUsed);
13274 }
13275 Slog.w(TAG, "Excessive CPU in " + app.processName
13276 + " (pid " + app.pid + "): used " + cputimeUsed
13277 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013278 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013279 app.processName, app.setAdj, "excessive cpu");
13280 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013281 } else {
13282 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013283 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013284 }
13285 }
13286 }
13287 }
13288
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013289 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013290 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013291 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013292 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013293 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294
13295 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013296 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 }
13298
Dianne Hackborn287952c2010-09-22 22:34:31 -070013299 final boolean wasKeeping = app.keeping;
13300
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013301 boolean success = true;
13302
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013303 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304
Jeff Brown10e89712011-07-08 18:52:57 -070013305 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013306 if (wasKeeping && !app.keeping) {
13307 // This app is no longer something we want to keep. Note
13308 // its current wake lock time to later know to kill it if
13309 // it is not behaving well.
13310 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13311 synchronized (stats) {
13312 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13313 app.pid, SystemClock.elapsedRealtime());
13314 }
13315 app.lastCpuTime = app.curCpuTime;
13316 }
13317
13318 app.setRawAdj = app.curRawAdj;
13319 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013320
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013321 if (app.curAdj != app.setAdj) {
13322 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013323 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013324 TAG, "Set " + app.pid + " " + app.processName +
13325 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013326 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013327 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013328 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013329 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013330 }
13331 }
13332 if (app.setSchedGroup != app.curSchedGroup) {
13333 app.setSchedGroup = app.curSchedGroup;
13334 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13335 "Setting process group of " + app.processName
13336 + " to " + app.curSchedGroup);
13337 if (app.waitingToKill != null &&
13338 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13339 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013340 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013341 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013342 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013343 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013344 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013345 } else {
13346 if (true) {
13347 long oldId = Binder.clearCallingIdentity();
13348 try {
13349 Process.setProcessGroup(app.pid, app.curSchedGroup);
13350 } catch (Exception e) {
13351 Slog.w(TAG, "Failed setting process group of " + app.pid
13352 + " to " + app.curSchedGroup);
13353 e.printStackTrace();
13354 } finally {
13355 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013356 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013357 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013358 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013359 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013360 app.thread.setSchedulingGroup(app.curSchedGroup);
13361 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013362 }
13363 }
13364 }
13365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013366 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013367 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 }
13369
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013370 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013371 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013372 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013373 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013375 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013376 }
13377 }
13378 return resumedActivity;
13379 }
13380
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013381 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013382 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013383 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13384 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013385 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13386 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013387
13388 mAdjSeq++;
13389
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013390 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13391 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013392 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13393 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013394 if (nowHidden != wasHidden) {
13395 // Changed to/from hidden state, so apps after it in the LRU
13396 // list may also be changed.
13397 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013398 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013399 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013400 }
13401
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013402 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013403 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013405 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406
13407 if (false) {
13408 RuntimeException e = new RuntimeException();
13409 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013410 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013411 }
13412
13413 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013414 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013416 final int emptyProcessLimit;
13417 final int hiddenProcessLimit;
13418 if (mProcessLimit <= 0) {
13419 emptyProcessLimit = hiddenProcessLimit = 0;
13420 } else if (mProcessLimit == 1) {
13421 emptyProcessLimit = 1;
13422 hiddenProcessLimit = 0;
13423 } else {
13424 emptyProcessLimit = (mProcessLimit*2)/3;
13425 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13426 }
13427
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013428 // Let's determine how many processes we have running vs.
13429 // how many slots we have for background processes; we may want
13430 // to put multiple processes in a slot of there are enough of
13431 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013432 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13433 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013434 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13435 if (numEmptyProcs > hiddenProcessLimit) {
13436 // If there are more empty processes than our limit on hidden
13437 // processes, then use the hidden process limit for the factor.
13438 // This ensures that the really old empty processes get pushed
13439 // down to the bottom, so if we are running low on memory we will
13440 // have a better chance at keeping around more hidden processes
13441 // instead of a gazillion empty processes.
13442 numEmptyProcs = hiddenProcessLimit;
13443 }
13444 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013445 if (emptyFactor < 1) emptyFactor = 1;
13446 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13447 if (hiddenFactor < 1) hiddenFactor = 1;
13448 int stepHidden = 0;
13449 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013450 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013451 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013452 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013453
13454 mNumNonHiddenProcs = 0;
13455 mNumHiddenProcs = 0;
13456
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013457 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013458 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013459 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013460 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013461 int nextHiddenAdj = curHiddenAdj+1;
13462 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13463 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013464 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013465 while (i > 0) {
13466 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013467 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013468 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013469 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013470 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013471 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13472 // This process was assigned as a hidden process... step the
13473 // hidden level.
13474 mNumHiddenProcs++;
13475 if (curHiddenAdj != nextHiddenAdj) {
13476 stepHidden++;
13477 if (stepHidden >= hiddenFactor) {
13478 stepHidden = 0;
13479 curHiddenAdj = nextHiddenAdj;
13480 nextHiddenAdj += 2;
13481 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13482 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13483 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013484 if (curClientHiddenAdj <= curHiddenAdj) {
13485 curClientHiddenAdj = curHiddenAdj + 1;
13486 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13487 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13488 }
13489 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013490 }
13491 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013492 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013493 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013494 Slog.i(TAG, "No longer want " + app.processName
13495 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013496 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013497 app.processName, app.setAdj, "too many background");
13498 app.killedBackground = true;
13499 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013500 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013501 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13502 // This process has a client that has activities. We will have
13503 // given it the current hidden adj; here we will just leave it
13504 // without stepping the hidden adj.
13505 curClientHiddenAdj++;
13506 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13507 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13508 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013509 } else {
13510 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13511 // This process was assigned as an empty process... step the
13512 // empty level.
13513 if (curEmptyAdj != nextEmptyAdj) {
13514 stepEmpty++;
13515 if (stepEmpty >= emptyFactor) {
13516 stepEmpty = 0;
13517 curEmptyAdj = nextEmptyAdj;
13518 nextEmptyAdj += 2;
13519 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13520 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13521 }
13522 }
13523 }
13524 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13525 mNumNonHiddenProcs++;
13526 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013527 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13528 && !app.hasClientActivities) {
13529 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13530 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013531 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013532 + " (pid " + app.pid + "): empty for "
13533 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13534 / 1000) + "s");
13535 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13536 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013537 app.killedBackground = true;
13538 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013539 } else {
13540 numEmpty++;
13541 if (numEmpty > emptyProcessLimit) {
13542 Slog.i(TAG, "No longer want " + app.processName
13543 + " (pid " + app.pid + "): empty #" + numEmpty);
13544 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13545 app.processName, app.setAdj, "too many background");
13546 app.killedBackground = true;
13547 Process.killProcessQuiet(app.pid);
13548 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013549 }
13550 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013551 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013552 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013553 // If this is an isolated process, and there are no
13554 // services running in it, then the process is no longer
13555 // needed. We agressively kill these because we can by
13556 // definition not re-use the same process again, and it is
13557 // good to avoid having whatever code was running in them
13558 // left sitting around after no longer needed.
13559 Slog.i(TAG, "Isolated process " + app.processName
13560 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013561 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013562 app.processName, app.setAdj, "isolated not needed");
13563 app.killedBackground = true;
13564 Process.killProcessQuiet(app.pid);
13565 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013566 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13567 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13568 && !app.killedBackground) {
13569 numTrimming++;
13570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013571 }
13572 }
13573
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013574 mNumServiceProcs = mNewNumServiceProcs;
13575
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013576 // Now determine the memory trimming level of background processes.
13577 // Unfortunately we need to start at the back of the list to do this
13578 // properly. We only do this if the number of background apps we
13579 // are managing to keep around is less than half the maximum we desire;
13580 // if we are keeping a good number around, we'll let them use whatever
13581 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013582 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13583 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013584 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013585 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013586 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013587 int minFactor = 2;
13588 if (mHomeProcess != null) minFactor++;
13589 if (mPreviousProcess != null) minFactor++;
13590 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013591 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013592 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013593 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013594 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013595 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013596 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13597 } else {
13598 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13599 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013600 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013601 for (i=0; i<N; i++) {
13602 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013603 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13604 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013605 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013606 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13607 try {
13608 app.thread.scheduleTrimMemory(curLevel);
13609 } catch (RemoteException e) {
13610 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013611 if (false) {
13612 // For now we won't do this; our memory trimming seems
13613 // to be good enough at this point that destroying
13614 // activities causes more harm than good.
13615 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13616 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013617 // Need to do this on its own message because the stack may not
13618 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013619 // For these apps we will also finish their activities
13620 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013621 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013622 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013623 }
13624 }
13625 app.trimMemoryLevel = curLevel;
13626 step++;
13627 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013628 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013629 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013630 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13631 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013632 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013633 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13634 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013635 break;
13636 }
13637 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013638 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013639 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013640 && app.thread != null) {
13641 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013642 app.thread.scheduleTrimMemory(
13643 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013644 } catch (RemoteException e) {
13645 }
13646 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013647 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013648 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013649 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013650 && app.pendingUiClean) {
13651 // If this application is now in the background and it
13652 // had done UI, then give it the special trim level to
13653 // have it free UI resources.
13654 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13655 if (app.trimMemoryLevel < level && app.thread != null) {
13656 try {
13657 app.thread.scheduleTrimMemory(level);
13658 } catch (RemoteException e) {
13659 }
13660 }
13661 app.pendingUiClean = false;
13662 }
13663 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013664 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013665 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013666 } catch (RemoteException e) {
13667 }
13668 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013669 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013670 }
13671 }
13672 } else {
13673 final int N = mLruProcesses.size();
13674 for (i=0; i<N; i++) {
13675 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013676 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013677 && app.pendingUiClean) {
13678 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13679 && app.thread != null) {
13680 try {
13681 app.thread.scheduleTrimMemory(
13682 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13683 } catch (RemoteException e) {
13684 }
13685 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013686 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013687 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013688 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013689 }
13690 }
13691
13692 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013693 // Need to do this on its own message because the stack may not
13694 // be in a consistent state at this point.
13695 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 }
13698
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013699 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013700 synchronized (this) {
13701 int i;
13702
13703 // First remove any unused application processes whose package
13704 // has been removed.
13705 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13706 final ProcessRecord app = mRemovedProcesses.get(i);
13707 if (app.activities.size() == 0
13708 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013709 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013710 TAG, "Exiting empty application process "
13711 + app.processName + " ("
13712 + (app.thread != null ? app.thread.asBinder() : null)
13713 + ")\n");
13714 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013715 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013716 app.processName, app.setAdj, "empty");
13717 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013718 } else {
13719 try {
13720 app.thread.scheduleExit();
13721 } catch (Exception e) {
13722 // Ignore exceptions.
13723 }
13724 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013725 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013726 mRemovedProcesses.remove(i);
13727
13728 if (app.persistent) {
13729 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013730 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731 }
13732 }
13733 }
13734 }
13735
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013736 // Now update the oom adj for all processes.
13737 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013738 }
13739 }
13740
13741 /** This method sends the specified signal to each of the persistent apps */
13742 public void signalPersistentProcesses(int sig) throws RemoteException {
13743 if (sig != Process.SIGNAL_USR1) {
13744 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13745 }
13746
13747 synchronized (this) {
13748 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13749 != PackageManager.PERMISSION_GRANTED) {
13750 throw new SecurityException("Requires permission "
13751 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13752 }
13753
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013754 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13755 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013756 if (r.thread != null && r.persistent) {
13757 Process.sendSignal(r.pid, sig);
13758 }
13759 }
13760 }
13761 }
13762
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013763 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13764 if (proc == null || proc == mProfileProc) {
13765 proc = mProfileProc;
13766 path = mProfileFile;
13767 profileType = mProfileType;
13768 clearProfilerLocked();
13769 }
13770 if (proc == null) {
13771 return;
13772 }
13773 try {
13774 proc.thread.profilerControl(false, path, null, profileType);
13775 } catch (RemoteException e) {
13776 throw new IllegalStateException("Process disappeared");
13777 }
13778 }
13779
13780 private void clearProfilerLocked() {
13781 if (mProfileFd != null) {
13782 try {
13783 mProfileFd.close();
13784 } catch (IOException e) {
13785 }
13786 }
13787 mProfileApp = null;
13788 mProfileProc = null;
13789 mProfileFile = null;
13790 mProfileType = 0;
13791 mAutoStopProfiler = false;
13792 }
13793
Dianne Hackborn1676c852012-09-10 14:52:30 -070013794 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013795 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013796
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013797 try {
13798 synchronized (this) {
13799 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13800 // its own permission.
13801 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13802 != PackageManager.PERMISSION_GRANTED) {
13803 throw new SecurityException("Requires permission "
13804 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013805 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013806
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013807 if (start && fd == null) {
13808 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013809 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013810
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013811 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013812 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013813 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013814 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013815
13816 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013817 throw new IllegalArgumentException("Unknown process: " + process);
13818 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013819
13820 if (start) {
13821 stopProfilerLocked(null, null, 0);
13822 setProfileApp(proc.info, proc.processName, path, fd, false);
13823 mProfileProc = proc;
13824 mProfileType = profileType;
13825 try {
13826 fd = fd.dup();
13827 } catch (IOException e) {
13828 fd = null;
13829 }
13830 proc.thread.profilerControl(start, path, fd, profileType);
13831 fd = null;
13832 mProfileFd = null;
13833 } else {
13834 stopProfilerLocked(proc, path, profileType);
13835 if (fd != null) {
13836 try {
13837 fd.close();
13838 } catch (IOException e) {
13839 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013840 }
13841 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013842
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013843 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013844 }
13845 } catch (RemoteException e) {
13846 throw new IllegalStateException("Process disappeared");
13847 } finally {
13848 if (fd != null) {
13849 try {
13850 fd.close();
13851 } catch (IOException e) {
13852 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013853 }
13854 }
13855 }
Andy McFadden824c5102010-07-09 16:26:57 -070013856
Dianne Hackborn1676c852012-09-10 14:52:30 -070013857 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013858 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013859 userId, true, true, callName, null);
13860 ProcessRecord proc = null;
13861 try {
13862 int pid = Integer.parseInt(process);
13863 synchronized (mPidsSelfLocked) {
13864 proc = mPidsSelfLocked.get(pid);
13865 }
13866 } catch (NumberFormatException e) {
13867 }
13868
13869 if (proc == null) {
13870 HashMap<String, SparseArray<ProcessRecord>> all
13871 = mProcessNames.getMap();
13872 SparseArray<ProcessRecord> procs = all.get(process);
13873 if (procs != null && procs.size() > 0) {
13874 proc = procs.valueAt(0);
13875 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13876 for (int i=1; i<procs.size(); i++) {
13877 ProcessRecord thisProc = procs.valueAt(i);
13878 if (thisProc.userId == userId) {
13879 proc = thisProc;
13880 break;
13881 }
13882 }
13883 }
13884 }
13885 }
13886
13887 return proc;
13888 }
13889
13890 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013891 String path, ParcelFileDescriptor fd) throws RemoteException {
13892
13893 try {
13894 synchronized (this) {
13895 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13896 // its own permission (same as profileControl).
13897 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13898 != PackageManager.PERMISSION_GRANTED) {
13899 throw new SecurityException("Requires permission "
13900 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13901 }
13902
13903 if (fd == null) {
13904 throw new IllegalArgumentException("null fd");
13905 }
13906
Dianne Hackborn1676c852012-09-10 14:52:30 -070013907 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013908 if (proc == null || proc.thread == null) {
13909 throw new IllegalArgumentException("Unknown process: " + process);
13910 }
13911
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013912 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13913 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013914 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13915 throw new SecurityException("Process not debuggable: " + proc);
13916 }
13917 }
13918
13919 proc.thread.dumpHeap(managed, path, fd);
13920 fd = null;
13921 return true;
13922 }
13923 } catch (RemoteException e) {
13924 throw new IllegalStateException("Process disappeared");
13925 } finally {
13926 if (fd != null) {
13927 try {
13928 fd.close();
13929 } catch (IOException e) {
13930 }
13931 }
13932 }
13933 }
13934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013935 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13936 public void monitor() {
13937 synchronized (this) { }
13938 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013939
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013940 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013941 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13942 ProcessRecord processRecord = mLruProcesses.get(i);
13943 try {
13944 if (processRecord.thread != null) {
13945 processRecord.thread.setCoreSettings(settings);
13946 }
13947 } catch (RemoteException re) {
13948 /* ignore */
13949 }
13950 }
13951 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013952
13953 // Multi-user methods
13954
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013955 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080013956 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013957 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13958 != PackageManager.PERMISSION_GRANTED) {
13959 String msg = "Permission Denial: switchUser() from pid="
13960 + Binder.getCallingPid()
13961 + ", uid=" + Binder.getCallingUid()
13962 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13963 Slog.w(TAG, msg);
13964 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013965 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013966
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013967 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013968 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013969 synchronized (this) {
13970 final int oldUserId = mCurrentUserId;
13971 if (oldUserId == userId) {
13972 return true;
13973 }
13974
13975 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13976 if (userInfo == null) {
13977 Slog.w(TAG, "No user info for user #" + userId);
13978 return false;
13979 }
13980
13981 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13982 R.anim.screen_user_enter);
13983
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070013984 boolean needStart = false;
13985
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013986 // If the user we are switching to is not currently started, then
13987 // we need to start it now.
13988 if (mStartedUsers.get(userId) == null) {
13989 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070013990 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070013991 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013992 }
13993
13994 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070013995 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013996 final Integer userIdInt = Integer.valueOf(userId);
13997 mUserLru.remove(userIdInt);
13998 mUserLru.add(userIdInt);
13999
Craig Mautnerf1b67412012-09-19 13:18:29 -070014000 mWindowManager.setCurrentUser(userId);
14001
Adam Cohenf7522022012-10-03 20:03:18 -070014002 // Once the internal notion of the active user has switched, we lock the device
14003 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014004 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014005
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014006 final UserStartedState uss = mStartedUsers.get(userId);
14007
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014008 // Make sure user is in the started state. If it is currently
14009 // stopping, we need to knock that off.
14010 if (uss.mState == UserStartedState.STATE_STOPPING) {
14011 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14012 // so we can just fairly silently bring the user back from
14013 // the almost-dead.
14014 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014015 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014016 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014017 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14018 // This means ACTION_SHUTDOWN has been sent, so we will
14019 // need to treat this as a new boot of the user.
14020 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014021 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014022 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014023 }
14024
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014025 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14026 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14027 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14028 oldUserId, userId, uss));
14029 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14030 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014031 if (needStart) {
14032 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14033 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14034 | Intent.FLAG_RECEIVER_FOREGROUND);
14035 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14036 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014037 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014038 false, false, MY_PID, Process.SYSTEM_UID, userId);
14039 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014040
14041 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14042 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014043 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014044 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014045 broadcastIntentLocked(null, null, intent, null,
14046 new IIntentReceiver.Stub() {
14047 public void performReceive(Intent intent, int resultCode,
14048 String data, Bundle extras, boolean ordered,
14049 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014050 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014051 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014052 }, 0, null, null, null, AppOpsManager.OP_NONE,
14053 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014054 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014055 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014056 } else {
14057 getUserManagerLocked().makeInitialized(userInfo.id);
14058 }
14059 }
14060
14061 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14062 if (!haveActivities) {
14063 startHomeActivityLocked(userId);
14064 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014065
Jeff Sharkey86597df2012-11-09 15:00:31 -080014066 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014067 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014068 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014069 if (needStart) {
14070 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14071 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14072 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14073 broadcastIntentLocked(null, null, intent,
14074 null, new IIntentReceiver.Stub() {
14075 @Override
14076 public void performReceive(Intent intent, int resultCode, String data,
14077 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14078 throws RemoteException {
14079 }
14080 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014081 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014082 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014083 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014084 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014085 } finally {
14086 Binder.restoreCallingIdentity(ident);
14087 }
Amith Yamasani13593602012-03-22 16:16:17 -070014088
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014089 return true;
14090 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014091
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014092 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14093 long ident = Binder.clearCallingIdentity();
14094 try {
14095 Intent intent;
14096 if (oldUserId >= 0) {
14097 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014098 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14099 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014100 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14101 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014102 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014103 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14104 }
14105 if (newUserId >= 0) {
14106 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014107 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14108 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014109 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14110 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014111 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014112 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14113 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014114 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14115 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014116 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14117 broadcastIntentLocked(null, null, intent,
14118 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014119 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014120 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14121 }
14122 } finally {
14123 Binder.restoreCallingIdentity(ident);
14124 }
14125 }
14126
14127 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14128 final int newUserId) {
14129 final int N = mUserSwitchObservers.beginBroadcast();
14130 if (N > 0) {
14131 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14132 int mCount = 0;
14133 @Override
14134 public void sendResult(Bundle data) throws RemoteException {
14135 synchronized (ActivityManagerService.this) {
14136 if (mCurUserSwitchCallback == this) {
14137 mCount++;
14138 if (mCount == N) {
14139 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14140 }
14141 }
14142 }
14143 }
14144 };
14145 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014146 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014147 mCurUserSwitchCallback = callback;
14148 }
14149 for (int i=0; i<N; i++) {
14150 try {
14151 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14152 newUserId, callback);
14153 } catch (RemoteException e) {
14154 }
14155 }
14156 } else {
14157 synchronized (this) {
14158 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14159 }
14160 }
14161 mUserSwitchObservers.finishBroadcast();
14162 }
14163
14164 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14165 synchronized (this) {
14166 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14167 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14168 }
14169 }
14170
14171 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14172 mCurUserSwitchCallback = null;
14173 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14174 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14175 oldUserId, newUserId, uss));
14176 }
14177
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014178 void userInitialized(UserStartedState uss, int newUserId) {
14179 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014180 }
14181
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014182 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014183 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014184 }
14185
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014186 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14187 boolean clearInitializing, boolean clearSwitching) {
14188 boolean unfrozen = false;
14189 synchronized (this) {
14190 if (clearInitializing) {
14191 uss.initializing = false;
14192 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14193 }
14194 if (clearSwitching) {
14195 uss.switching = false;
14196 }
14197 if (!uss.switching && !uss.initializing) {
14198 mWindowManager.stopFreezingScreen();
14199 unfrozen = true;
14200 }
14201 }
14202 if (unfrozen) {
14203 final int N = mUserSwitchObservers.beginBroadcast();
14204 for (int i=0; i<N; i++) {
14205 try {
14206 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14207 } catch (RemoteException e) {
14208 }
14209 }
14210 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014211 }
14212 }
14213
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014214 void finishUserSwitch(UserStartedState uss) {
14215 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014216 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014217 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14218 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014219 final int userId = uss.mHandle.getIdentifier();
14220 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14221 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14222 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014223 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014224 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014225 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014226 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014227 int num = mUserLru.size();
14228 int i = 0;
14229 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14230 Integer oldUserId = mUserLru.get(i);
14231 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14232 if (oldUss == null) {
14233 // Shouldn't happen, but be sane if it does.
14234 mUserLru.remove(i);
14235 num--;
14236 continue;
14237 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014238 if (oldUss.mState == UserStartedState.STATE_STOPPING
14239 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014240 // This user is already stopping, doesn't count.
14241 num--;
14242 i++;
14243 continue;
14244 }
14245 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14246 // Owner and current can't be stopped, but count as running.
14247 i++;
14248 continue;
14249 }
14250 // This is a user to be stopped.
14251 stopUserLocked(oldUserId, null);
14252 num--;
14253 i++;
14254 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014255 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014256 }
14257
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014258 @Override
14259 public int stopUser(final int userId, final IStopUserCallback callback) {
14260 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14261 != PackageManager.PERMISSION_GRANTED) {
14262 String msg = "Permission Denial: switchUser() from pid="
14263 + Binder.getCallingPid()
14264 + ", uid=" + Binder.getCallingUid()
14265 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14266 Slog.w(TAG, msg);
14267 throw new SecurityException(msg);
14268 }
14269 if (userId <= 0) {
14270 throw new IllegalArgumentException("Can't stop primary user " + userId);
14271 }
Amith Yamasani13593602012-03-22 16:16:17 -070014272 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014273 return stopUserLocked(userId, callback);
14274 }
14275 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014276
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014277 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14278 if (mCurrentUserId == userId) {
14279 return ActivityManager.USER_OP_IS_CURRENT;
14280 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014281
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014282 final UserStartedState uss = mStartedUsers.get(userId);
14283 if (uss == null) {
14284 // User is not started, nothing to do... but we do need to
14285 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014286 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014287 mHandler.post(new Runnable() {
14288 @Override
14289 public void run() {
14290 try {
14291 callback.userStopped(userId);
14292 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014293 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014294 }
14295 });
14296 }
14297 return ActivityManager.USER_OP_SUCCESS;
14298 }
14299
14300 if (callback != null) {
14301 uss.mStopCallbacks.add(callback);
14302 }
14303
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014304 if (uss.mState != UserStartedState.STATE_STOPPING
14305 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014306 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014307 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014308
14309 long ident = Binder.clearCallingIdentity();
14310 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014311 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014312 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014313 // stop the user.
14314 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14315 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14316 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14317 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14318 // This is the result receiver for the final shutdown broadcast.
14319 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014320 @Override
14321 public void performReceive(Intent intent, int resultCode, String data,
14322 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14323 finishUserStop(uss);
14324 }
14325 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014326 // This is the result receiver for the initial stopping broadcast.
14327 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14328 @Override
14329 public void performReceive(Intent intent, int resultCode, String data,
14330 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14331 // On to the next.
14332 synchronized (ActivityManagerService.this) {
14333 if (uss.mState != UserStartedState.STATE_STOPPING) {
14334 // Whoops, we are being started back up. Abort, abort!
14335 return;
14336 }
14337 uss.mState = UserStartedState.STATE_SHUTDOWN;
14338 }
14339 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014340 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014341 true, false, MY_PID, Process.SYSTEM_UID, userId);
14342 }
14343 };
14344 // Kick things off.
14345 broadcastIntentLocked(null, null, stoppingIntent,
14346 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014347 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014348 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014349 } finally {
14350 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014351 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014352 }
Amith Yamasani13593602012-03-22 16:16:17 -070014353
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014354 return ActivityManager.USER_OP_SUCCESS;
14355 }
14356
14357 void finishUserStop(UserStartedState uss) {
14358 final int userId = uss.mHandle.getIdentifier();
14359 boolean stopped;
14360 ArrayList<IStopUserCallback> callbacks;
14361 synchronized (this) {
14362 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014363 if (mStartedUsers.get(userId) != uss) {
14364 stopped = false;
14365 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014366 stopped = false;
14367 } else {
14368 stopped = true;
14369 // User can no longer run.
14370 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014371 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014372 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014373
14374 // Clean up all state and processes associated with the user.
14375 // Kill all the processes for the user.
14376 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014377 }
14378 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014379
14380 for (int i=0; i<callbacks.size(); i++) {
14381 try {
14382 if (stopped) callbacks.get(i).userStopped(userId);
14383 else callbacks.get(i).userStopAborted(userId);
14384 } catch (RemoteException e) {
14385 }
14386 }
14387 }
14388
14389 @Override
14390 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014391 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14392 != PackageManager.PERMISSION_GRANTED) && (
14393 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14394 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014395 String msg = "Permission Denial: getCurrentUser() from pid="
14396 + Binder.getCallingPid()
14397 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014398 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014399 Slog.w(TAG, msg);
14400 throw new SecurityException(msg);
14401 }
14402 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014403 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014404 }
Amith Yamasani13593602012-03-22 16:16:17 -070014405 }
14406
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014407 int getCurrentUserIdLocked() {
14408 return mCurrentUserId;
14409 }
14410
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014411 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014412 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014413 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14414 != PackageManager.PERMISSION_GRANTED) {
14415 String msg = "Permission Denial: isUserRunning() from pid="
14416 + Binder.getCallingPid()
14417 + ", uid=" + Binder.getCallingUid()
14418 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14419 Slog.w(TAG, msg);
14420 throw new SecurityException(msg);
14421 }
14422 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014423 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014424 }
14425 }
14426
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014427 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014428 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014429 if (state == null) {
14430 return false;
14431 }
14432 if (orStopped) {
14433 return true;
14434 }
14435 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014436 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014437 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014438
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014439 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014440 public int[] getRunningUserIds() {
14441 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14442 != PackageManager.PERMISSION_GRANTED) {
14443 String msg = "Permission Denial: isUserRunning() from pid="
14444 + Binder.getCallingPid()
14445 + ", uid=" + Binder.getCallingUid()
14446 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14447 Slog.w(TAG, msg);
14448 throw new SecurityException(msg);
14449 }
14450 synchronized (this) {
14451 return mStartedUserArray;
14452 }
14453 }
14454
14455 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014456 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014457 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014458 UserStartedState uss = mStartedUsers.valueAt(i);
14459 // This list does not include stopping users.
14460 if (uss.mState != UserStartedState.STATE_STOPPING
14461 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14462 num++;
14463 }
14464 }
14465 mStartedUserArray = new int[num];
14466 num = 0;
14467 for (int i=0; i<mStartedUsers.size(); i++) {
14468 UserStartedState uss = mStartedUsers.valueAt(i);
14469 if (uss.mState != UserStartedState.STATE_STOPPING
14470 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14471 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14472 num++;
14473 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014474 }
14475 }
14476
14477 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014478 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14479 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14480 != PackageManager.PERMISSION_GRANTED) {
14481 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14482 + Binder.getCallingPid()
14483 + ", uid=" + Binder.getCallingUid()
14484 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14485 Slog.w(TAG, msg);
14486 throw new SecurityException(msg);
14487 }
14488
14489 mUserSwitchObservers.register(observer);
14490 }
14491
14492 @Override
14493 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14494 mUserSwitchObservers.unregister(observer);
14495 }
14496
Dianne Hackborn1676c852012-09-10 14:52:30 -070014497 private boolean userExists(int userId) {
14498 if (userId == 0) {
14499 return true;
14500 }
14501 UserManagerService ums = getUserManagerLocked();
14502 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14503 }
14504
14505 int[] getUsersLocked() {
14506 UserManagerService ums = getUserManagerLocked();
14507 return ums != null ? ums.getUserIds() : new int[] { 0 };
14508 }
14509
14510 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014511 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014512 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14513 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014514 }
14515 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014516 }
14517
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014518 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014519 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014520
14521 throw new SecurityException("Caller uid=" + uid
14522 + " is not privileged to communicate with user=" + userId);
14523 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014524
14525 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014526 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014527 }
14528
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014529 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014530 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014531 ApplicationInfo newInfo = new ApplicationInfo(info);
14532 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014533 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14534 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014535 return newInfo;
14536 }
14537
14538 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014539 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014540 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014541 return aInfo;
14542 }
14543
14544 ActivityInfo info = new ActivityInfo(aInfo);
14545 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14546 return info;
14547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014548}