blob: 22af3d5b3357653fbe525ddd0c2e5fd0d618f41b [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 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08007743
7744 mAppOpsService.systemReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 mSystemReady = true;
7746 if (!mStartRunning) {
7747 return;
7748 }
7749 }
7750
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007751 ArrayList<ProcessRecord> procsToKill = null;
7752 synchronized(mPidsSelfLocked) {
7753 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7754 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7755 if (!isAllowedWhileBooting(proc.info)){
7756 if (procsToKill == null) {
7757 procsToKill = new ArrayList<ProcessRecord>();
7758 }
7759 procsToKill.add(proc);
7760 }
7761 }
7762 }
7763
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007764 synchronized(this) {
7765 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007766 for (int i=procsToKill.size()-1; i>=0; i--) {
7767 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007768 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007769 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007770 }
7771 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007772
7773 // Now that we have cleaned up any update processes, we
7774 // are ready to start launching real processes and know that
7775 // we won't trample on them any more.
7776 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007777 }
7778
Joe Onorato8a9b2202010-02-26 18:56:32 -08007779 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007780 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 SystemClock.uptimeMillis());
7782
7783 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007784 // Make sure we have no pre-ready processes sitting around.
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7787 ResolveInfo ri = mContext.getPackageManager()
7788 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007789 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 CharSequence errorMsg = null;
7791 if (ri != null) {
7792 ActivityInfo ai = ri.activityInfo;
7793 ApplicationInfo app = ai.applicationInfo;
7794 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7795 mTopAction = Intent.ACTION_FACTORY_TEST;
7796 mTopData = null;
7797 mTopComponent = new ComponentName(app.packageName,
7798 ai.name);
7799 } else {
7800 errorMsg = mContext.getResources().getText(
7801 com.android.internal.R.string.factorytest_not_system);
7802 }
7803 } else {
7804 errorMsg = mContext.getResources().getText(
7805 com.android.internal.R.string.factorytest_no_action);
7806 }
7807 if (errorMsg != null) {
7808 mTopAction = null;
7809 mTopData = null;
7810 mTopComponent = null;
7811 Message msg = Message.obtain();
7812 msg.what = SHOW_FACTORY_ERROR_MSG;
7813 msg.getData().putCharSequence("msg", errorMsg);
7814 mHandler.sendMessage(msg);
7815 }
7816 }
7817 }
7818
7819 retrieveSettings();
7820
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007821 if (goingCallback != null) goingCallback.run();
7822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 synchronized (this) {
7824 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7825 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007826 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007827 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 if (apps != null) {
7829 int N = apps.size();
7830 int i;
7831 for (i=0; i<N; i++) {
7832 ApplicationInfo info
7833 = (ApplicationInfo)apps.get(i);
7834 if (info != null &&
7835 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007836 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 }
7838 }
7839 }
7840 } catch (RemoteException ex) {
7841 // pm is in same process, this will never happen.
7842 }
7843 }
7844
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007845 // Start up initial activity.
7846 mBooting = true;
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007849 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 Message msg = Message.obtain();
7851 msg.what = SHOW_UID_ERROR_MSG;
7852 mHandler.sendMessage(msg);
7853 }
7854 } catch (RemoteException e) {
7855 }
7856
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007857 long ident = Binder.clearCallingIdentity();
7858 try {
7859 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007860 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7861 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007862 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7863 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007864 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007865 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007866 intent = new Intent(Intent.ACTION_USER_STARTING);
7867 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7868 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7869 broadcastIntentLocked(null, null, intent,
7870 null, new IIntentReceiver.Stub() {
7871 @Override
7872 public void performReceive(Intent intent, int resultCode, String data,
7873 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7874 throws RemoteException {
7875 }
7876 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007877 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007878 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007879 } finally {
7880 Binder.restoreCallingIdentity(ident);
7881 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007882 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007883 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 }
7885 }
7886
Dan Egnorb7f03672009-12-09 16:22:32 -08007887 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007888 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007890 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007891 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 startAppProblemLocked(app);
7893 app.stopFreezingAllLocked();
7894 return handleAppCrashLocked(app);
7895 }
7896
Dan Egnorb7f03672009-12-09 16:22:32 -08007897 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007898 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007900 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007901 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7902 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 startAppProblemLocked(app);
7904 app.stopFreezingAllLocked();
7905 }
7906
7907 /**
7908 * Generate a process error record, suitable for attachment to a ProcessRecord.
7909 *
7910 * @param app The ProcessRecord in which the error occurred.
7911 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7912 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007913 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 * @param shortMsg Short message describing the crash.
7915 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007916 * @param stackTrace Full crash stack trace, may be null.
7917 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 * @return Returns a fully-formed AppErrorStateInfo record.
7919 */
7920 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007921 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 report.condition = condition;
7925 report.processName = app.processName;
7926 report.pid = app.pid;
7927 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007928 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 report.shortMsg = shortMsg;
7930 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007931 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007932
7933 return report;
7934 }
7935
Dan Egnor42471dd2010-01-07 17:25:22 -08007936 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 synchronized (this) {
7938 app.crashing = false;
7939 app.crashingReport = null;
7940 app.notResponding = false;
7941 app.notRespondingReport = null;
7942 if (app.anrDialog == fromDialog) {
7943 app.anrDialog = null;
7944 }
7945 if (app.waitDialog == fromDialog) {
7946 app.waitDialog = null;
7947 }
7948 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007949 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007950 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007951 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07007952 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007953 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 }
7956 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007957
Dan Egnorb7f03672009-12-09 16:22:32 -08007958 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007959 if (mHeadless) {
7960 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7961 return false;
7962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 long now = SystemClock.uptimeMillis();
7964
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007965 Long crashTime;
7966 if (!app.isolated) {
7967 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7968 } else {
7969 crashTime = null;
7970 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007971 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007973 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007975 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007976 app.userId, app.info.processName, app.uid);
Craig Mautnercae015f2013-02-08 14:31:27 -08007977 mMainStack.handleAppCrashLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 if (!app.persistent) {
7979 // We don't want to start this process again until the user
7980 // explicitly does so... but for persistent process, we really
7981 // need to keep it running. If a persistent process is actually
7982 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007983 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007985 if (!app.isolated) {
7986 // XXX We don't have a way to mark isolated processes
7987 // as bad, since they don't have a peristent identity.
7988 mBadProcesses.put(app.info.processName, app.uid, now);
7989 mProcessCrashTimes.remove(app.info.processName, app.uid);
7990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007993 // Don't let services in this process be restarted and potentially
7994 // annoy the user repeatedly. Unless it is persistent, since those
7995 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007996 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007997 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 return false;
7999 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008000 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008001 } else {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08008002 mMainStack.finishTopRunningActivityLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 }
8004
8005 // Bump up the crash count of any services currently running in the proc.
8006 if (app.services.size() != 0) {
8007 // Any services running in the application need to be placed
8008 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008009 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008010 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008011 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 sr.crashCount++;
8013 }
8014 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008015
8016 // If the crashing process is what we consider to be the "home process" and it has been
8017 // replaced by a third-party app, clear the package preferred activities from packages
8018 // with a home activity running in the process to prevent a repeatedly crashing app
8019 // from blocking the user to manually clear the list.
8020 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8021 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8022 Iterator it = mHomeProcess.activities.iterator();
8023 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008024 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008025 if (r.isHomeActivity) {
8026 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8027 try {
8028 ActivityThread.getPackageManager()
8029 .clearPackagePreferredActivities(r.packageName);
8030 } catch (RemoteException c) {
8031 // pm is in same process, this will never happen.
8032 }
8033 }
8034 }
8035 }
8036
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008037 if (!app.isolated) {
8038 // XXX Can't keep track of crash times for isolated processes,
8039 // because they don't have a perisistent identity.
8040 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8041 }
8042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 return true;
8044 }
8045
8046 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008047 if (app.userId == mCurrentUserId) {
8048 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8049 mContext, app.info.packageName, app.info.flags);
8050 } else {
8051 // If this app is not running under the current user, then we
8052 // can't give it a report button because that would require
8053 // launching the report UI under a different user.
8054 app.errorReportReceiver = null;
8055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008056 skipCurrentReceiverLocked(app);
8057 }
8058
8059 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008060 for (BroadcastQueue queue : mBroadcastQueues) {
8061 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 }
8063 }
8064
Dan Egnor60d87622009-12-16 16:32:58 -08008065 /**
8066 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8067 * The application process will exit immediately after this call returns.
8068 * @param app object of the crashing app, null for the system server
8069 * @param crashInfo describing the exception
8070 */
8071 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008072 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008073 final String processName = app == null ? "system_server"
8074 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008075
8076 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008077 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008078 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008079 crashInfo.exceptionClassName,
8080 crashInfo.exceptionMessage,
8081 crashInfo.throwFileName,
8082 crashInfo.throwLineNumber);
8083
Jeff Sharkeya353d262011-10-28 11:12:06 -07008084 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008085
8086 crashApplication(r, crashInfo);
8087 }
8088
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008089 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008090 IBinder app,
8091 int violationMask,
8092 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008093 ProcessRecord r = findAppProcess(app, "StrictMode");
8094 if (r == null) {
8095 return;
8096 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008097
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008098 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008099 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008100 boolean logIt = true;
8101 synchronized (mAlreadyLoggedViolatedStacks) {
8102 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8103 logIt = false;
8104 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008105 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008106 // the relative pain numbers, without logging all
8107 // the stack traces repeatedly. We'd want to do
8108 // likewise in the client code, which also does
8109 // dup suppression, before the Binder call.
8110 } else {
8111 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8112 mAlreadyLoggedViolatedStacks.clear();
8113 }
8114 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8115 }
8116 }
8117 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008118 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008119 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008120 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008121
8122 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8123 AppErrorResult result = new AppErrorResult();
8124 synchronized (this) {
8125 final long origId = Binder.clearCallingIdentity();
8126
8127 Message msg = Message.obtain();
8128 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8129 HashMap<String, Object> data = new HashMap<String, Object>();
8130 data.put("result", result);
8131 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008132 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008133 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008134 msg.obj = data;
8135 mHandler.sendMessage(msg);
8136
8137 Binder.restoreCallingIdentity(origId);
8138 }
8139 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008140 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008141 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008142 }
8143
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008144 // Depending on the policy in effect, there could be a bunch of
8145 // these in quick succession so we try to batch these together to
8146 // minimize disk writes, number of dropbox entries, and maximize
8147 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008148 private void logStrictModeViolationToDropBox(
8149 ProcessRecord process,
8150 StrictMode.ViolationInfo info) {
8151 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008152 return;
8153 }
8154 final boolean isSystemApp = process == null ||
8155 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8156 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008157 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008158 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8159 final DropBoxManager dbox = (DropBoxManager)
8160 mContext.getSystemService(Context.DROPBOX_SERVICE);
8161
8162 // Exit early if the dropbox isn't configured to accept this report type.
8163 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8164
8165 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008166 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008167 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8168 synchronized (sb) {
8169 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008170 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008171 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8172 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008173 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8174 if (info.violationNumThisLoop != 0) {
8175 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8176 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008177 if (info.numAnimationsRunning != 0) {
8178 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8179 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008180 if (info.broadcastIntentAction != null) {
8181 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8182 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008183 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008184 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008185 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008186 if (info.numInstances != -1) {
8187 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8188 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008189 if (info.tags != null) {
8190 for (String tag : info.tags) {
8191 sb.append("Span-Tag: ").append(tag).append("\n");
8192 }
8193 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008194 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008195 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8196 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008197 }
8198 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008199
8200 // Only buffer up to ~64k. Various logging bits truncate
8201 // things at 128k.
8202 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008203 }
8204
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008205 // Flush immediately if the buffer's grown too large, or this
8206 // is a non-system app. Non-system apps are isolated with a
8207 // different tag & policy and not batched.
8208 //
8209 // Batching is useful during internal testing with
8210 // StrictMode settings turned up high. Without batching,
8211 // thousands of separate files could be created on boot.
8212 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008213 new Thread("Error dump: " + dropboxTag) {
8214 @Override
8215 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008216 String report;
8217 synchronized (sb) {
8218 report = sb.toString();
8219 sb.delete(0, sb.length());
8220 sb.trimToSize();
8221 }
8222 if (report.length() != 0) {
8223 dbox.addText(dropboxTag, report);
8224 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008225 }
8226 }.start();
8227 return;
8228 }
8229
8230 // System app batching:
8231 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008232 // An existing dropbox-writing thread is outstanding, so
8233 // we don't need to start it up. The existing thread will
8234 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008235 return;
8236 }
8237
8238 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8239 // (After this point, we shouldn't access AMS internal data structures.)
8240 new Thread("Error dump: " + dropboxTag) {
8241 @Override
8242 public void run() {
8243 // 5 second sleep to let stacks arrive and be batched together
8244 try {
8245 Thread.sleep(5000); // 5 seconds
8246 } catch (InterruptedException e) {}
8247
8248 String errorReport;
8249 synchronized (mStrictModeBuffer) {
8250 errorReport = mStrictModeBuffer.toString();
8251 if (errorReport.length() == 0) {
8252 return;
8253 }
8254 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8255 mStrictModeBuffer.trimToSize();
8256 }
8257 dbox.addText(dropboxTag, errorReport);
8258 }
8259 }.start();
8260 }
8261
Dan Egnor60d87622009-12-16 16:32:58 -08008262 /**
8263 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8264 * @param app object of the crashing app, null for the system server
8265 * @param tag reported by the caller
8266 * @param crashInfo describing the context of the error
8267 * @return true if the process should exit immediately (WTF is fatal)
8268 */
8269 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008270 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008271 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008272 final String processName = app == null ? "system_server"
8273 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008274
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008275 EventLog.writeEvent(EventLogTags.AM_WTF,
8276 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008277 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008278 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008279 tag, crashInfo.exceptionMessage);
8280
Jeff Sharkeya353d262011-10-28 11:12:06 -07008281 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008282
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008283 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008284 Settings.Global.getInt(mContext.getContentResolver(),
8285 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008286 crashApplication(r, crashInfo);
8287 return true;
8288 } else {
8289 return false;
8290 }
8291 }
8292
8293 /**
8294 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8295 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8296 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008297 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008298 if (app == null) {
8299 return null;
8300 }
8301
8302 synchronized (this) {
8303 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8304 final int NA = apps.size();
8305 for (int ia=0; ia<NA; ia++) {
8306 ProcessRecord p = apps.valueAt(ia);
8307 if (p.thread != null && p.thread.asBinder() == app) {
8308 return p;
8309 }
8310 }
8311 }
8312
Dianne Hackborncb44d962011-03-10 17:02:27 -08008313 Slog.w(TAG, "Can't find mystery application for " + reason
8314 + " from pid=" + Binder.getCallingPid()
8315 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008316 return null;
8317 }
8318 }
8319
8320 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008321 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8322 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008323 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008324 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8325 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008326 // Watchdog thread ends up invoking this function (with
8327 // a null ProcessRecord) to add the stack file to dropbox.
8328 // Do not acquire a lock on this (am) in such cases, as it
8329 // could cause a potential deadlock, if and when watchdog
8330 // is invoked due to unavailability of lock on am and it
8331 // would prevent watchdog from killing system_server.
8332 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008333 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008334 return;
8335 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008336 // Note: ProcessRecord 'process' is guarded by the service
8337 // instance. (notably process.pkgList, which could otherwise change
8338 // concurrently during execution of this method)
8339 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008340 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008341 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008342 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008343 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8344 for (String pkg : process.pkgList) {
8345 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008346 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008347 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008348 if (pi != null) {
8349 sb.append(" v").append(pi.versionCode);
8350 if (pi.versionName != null) {
8351 sb.append(" (").append(pi.versionName).append(")");
8352 }
8353 }
8354 } catch (RemoteException e) {
8355 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008356 }
Dan Egnora455d192010-03-12 08:52:28 -08008357 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008358 }
Dan Egnora455d192010-03-12 08:52:28 -08008359 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008360 }
8361
8362 private static String processClass(ProcessRecord process) {
8363 if (process == null || process.pid == MY_PID) {
8364 return "system_server";
8365 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8366 return "system_app";
8367 } else {
8368 return "data_app";
8369 }
8370 }
8371
8372 /**
8373 * Write a description of an error (crash, WTF, ANR) to the drop box.
8374 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8375 * @param process which caused the error, null means the system server
8376 * @param activity which triggered the error, null if unknown
8377 * @param parent activity related to the error, null if unknown
8378 * @param subject line related to the error, null if absent
8379 * @param report in long form describing the error, null if absent
8380 * @param logFile to include in the report, null if none
8381 * @param crashInfo giving an application stack trace, null if absent
8382 */
8383 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008384 ProcessRecord process, String processName, ActivityRecord activity,
8385 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008386 final String report, final File logFile,
8387 final ApplicationErrorReport.CrashInfo crashInfo) {
8388 // NOTE -- this must never acquire the ActivityManagerService lock,
8389 // otherwise the watchdog may be prevented from resetting the system.
8390
8391 final String dropboxTag = processClass(process) + "_" + eventType;
8392 final DropBoxManager dbox = (DropBoxManager)
8393 mContext.getSystemService(Context.DROPBOX_SERVICE);
8394
8395 // Exit early if the dropbox isn't configured to accept this report type.
8396 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8397
8398 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008399 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008400 if (activity != null) {
8401 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8402 }
8403 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8404 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8405 }
8406 if (parent != null && parent != activity) {
8407 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8408 }
8409 if (subject != null) {
8410 sb.append("Subject: ").append(subject).append("\n");
8411 }
8412 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008413 if (Debug.isDebuggerConnected()) {
8414 sb.append("Debugger: Connected\n");
8415 }
Dan Egnora455d192010-03-12 08:52:28 -08008416 sb.append("\n");
8417
8418 // Do the rest in a worker thread to avoid blocking the caller on I/O
8419 // (After this point, we shouldn't access AMS internal data structures.)
8420 Thread worker = new Thread("Error dump: " + dropboxTag) {
8421 @Override
8422 public void run() {
8423 if (report != null) {
8424 sb.append(report);
8425 }
8426 if (logFile != null) {
8427 try {
8428 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8429 } catch (IOException e) {
8430 Slog.e(TAG, "Error reading " + logFile, e);
8431 }
8432 }
8433 if (crashInfo != null && crashInfo.stackTrace != null) {
8434 sb.append(crashInfo.stackTrace);
8435 }
8436
Jeff Sharkey625239a2012-09-26 22:03:49 -07008437 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8438 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008439 if (lines > 0) {
8440 sb.append("\n");
8441
8442 // Merge several logcat streams, and take the last N lines
8443 InputStreamReader input = null;
8444 try {
8445 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8446 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8447 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8448
8449 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8450 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8451 input = new InputStreamReader(logcat.getInputStream());
8452
8453 int num;
8454 char[] buf = new char[8192];
8455 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8456 } catch (IOException e) {
8457 Slog.e(TAG, "Error running logcat", e);
8458 } finally {
8459 if (input != null) try { input.close(); } catch (IOException e) {}
8460 }
8461 }
8462
8463 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008464 }
Dan Egnora455d192010-03-12 08:52:28 -08008465 };
8466
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008467 if (process == null) {
8468 // If process is null, we are being called from some internal code
8469 // and may be about to die -- run this synchronously.
8470 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008471 } else {
8472 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008473 }
8474 }
8475
8476 /**
8477 * Bring up the "unexpected error" dialog box for a crashing app.
8478 * Deal with edge cases (intercepts from instrumented applications,
8479 * ActivityController, error intent receivers, that sort of thing).
8480 * @param r the application crashing
8481 * @param crashInfo describing the failure
8482 */
8483 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008484 long timeMillis = System.currentTimeMillis();
8485 String shortMsg = crashInfo.exceptionClassName;
8486 String longMsg = crashInfo.exceptionMessage;
8487 String stackTrace = crashInfo.stackTrace;
8488 if (shortMsg != null && longMsg != null) {
8489 longMsg = shortMsg + ": " + longMsg;
8490 } else if (shortMsg != null) {
8491 longMsg = shortMsg;
8492 }
8493
Dan Egnor60d87622009-12-16 16:32:58 -08008494 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008496 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 try {
8498 String name = r != null ? r.processName : null;
8499 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008500 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008501 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008502 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 + " at watcher's request");
8504 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008505 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008506 }
8507 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008508 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008509 }
8510 }
8511
8512 final long origId = Binder.clearCallingIdentity();
8513
8514 // If this process is running instrumentation, finish it.
8515 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008516 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008518 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8519 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 Bundle info = new Bundle();
8521 info.putString("shortMsg", shortMsg);
8522 info.putString("longMsg", longMsg);
8523 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8524 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008525 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008526 }
8527
Dan Egnor60d87622009-12-16 16:32:58 -08008528 // If we can't identify the process or it's already exceeded its crash quota,
8529 // quit right away without showing a crash dialog.
8530 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008532 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 }
8534
8535 Message msg = Message.obtain();
8536 msg.what = SHOW_ERROR_MSG;
8537 HashMap data = new HashMap();
8538 data.put("result", result);
8539 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008540 msg.obj = data;
8541 mHandler.sendMessage(msg);
8542
8543 Binder.restoreCallingIdentity(origId);
8544 }
8545
8546 int res = result.get();
8547
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008548 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008550 if (r != null && !r.isolated) {
8551 // XXX Can't keep track of crash time for isolated processes,
8552 // since they don't have a persistent identity.
8553 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 SystemClock.uptimeMillis());
8555 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008556 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008557 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008558 }
8559 }
8560
8561 if (appErrorIntent != null) {
8562 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008563 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008564 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008565 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008568 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008569
8570 Intent createAppErrorIntentLocked(ProcessRecord r,
8571 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8572 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008573 if (report == null) {
8574 return null;
8575 }
8576 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8577 result.setComponent(r.errorReportReceiver);
8578 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8579 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8580 return result;
8581 }
8582
Dan Egnorb7f03672009-12-09 16:22:32 -08008583 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8584 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008585 if (r.errorReportReceiver == null) {
8586 return null;
8587 }
8588
8589 if (!r.crashing && !r.notResponding) {
8590 return null;
8591 }
8592
Dan Egnorb7f03672009-12-09 16:22:32 -08008593 ApplicationErrorReport report = new ApplicationErrorReport();
8594 report.packageName = r.info.packageName;
8595 report.installerPackageName = r.errorReportReceiver.getPackageName();
8596 report.processName = r.processName;
8597 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008598 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008599
Dan Egnorb7f03672009-12-09 16:22:32 -08008600 if (r.crashing) {
8601 report.type = ApplicationErrorReport.TYPE_CRASH;
8602 report.crashInfo = crashInfo;
8603 } else if (r.notResponding) {
8604 report.type = ApplicationErrorReport.TYPE_ANR;
8605 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008606
Dan Egnorb7f03672009-12-09 16:22:32 -08008607 report.anrInfo.activity = r.notRespondingReport.tag;
8608 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8609 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008610 }
8611
Dan Egnorb7f03672009-12-09 16:22:32 -08008612 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008613 }
8614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008616 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 // assume our apps are happy - lazy create the list
8618 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8619
Dianne Hackborn0c380492012-08-20 17:23:30 -07008620 final boolean allUsers = ActivityManager.checkUidPermission(
8621 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8622 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8623 int userId = UserHandle.getUserId(Binder.getCallingUid());
8624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 synchronized (this) {
8626
8627 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008628 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8629 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008630 if (!allUsers && app.userId != userId) {
8631 continue;
8632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8634 // This one's in trouble, so we'll generate a report for it
8635 // crashes are higher priority (in case there's a crash *and* an anr)
8636 ActivityManager.ProcessErrorStateInfo report = null;
8637 if (app.crashing) {
8638 report = app.crashingReport;
8639 } else if (app.notResponding) {
8640 report = app.notRespondingReport;
8641 }
8642
8643 if (report != null) {
8644 if (errList == null) {
8645 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8646 }
8647 errList.add(report);
8648 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008649 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 " crashing = " + app.crashing +
8651 " notResponding = " + app.notResponding);
8652 }
8653 }
8654 }
8655 }
8656
8657 return errList;
8658 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008659
8660 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008661 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008662 if (currApp != null) {
8663 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8664 }
8665 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008666 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8667 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008668 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8669 if (currApp != null) {
8670 currApp.lru = 0;
8671 }
8672 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008673 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008674 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8675 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8676 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8677 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8678 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8679 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8680 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8681 } else {
8682 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8683 }
8684 }
8685
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008686 private void fillInProcMemInfo(ProcessRecord app,
8687 ActivityManager.RunningAppProcessInfo outInfo) {
8688 outInfo.pid = app.pid;
8689 outInfo.uid = app.info.uid;
8690 if (mHeavyWeightProcess == app) {
8691 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8692 }
8693 if (app.persistent) {
8694 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8695 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008696 if (app.hasActivities) {
8697 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8698 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008699 outInfo.lastTrimLevel = app.trimMemoryLevel;
8700 int adj = app.curAdj;
8701 outInfo.importance = oomAdjToImportance(adj, outInfo);
8702 outInfo.importanceReasonCode = app.adjTypeCode;
8703 }
8704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008706 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008707 // Lazy instantiation of list
8708 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008709 final boolean allUsers = ActivityManager.checkUidPermission(
8710 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8711 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8712 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 synchronized (this) {
8714 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008715 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8716 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008717 if (!allUsers && app.userId != userId) {
8718 continue;
8719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8721 // Generate process state info for running application
8722 ActivityManager.RunningAppProcessInfo currApp =
8723 new ActivityManager.RunningAppProcessInfo(app.processName,
8724 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008725 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008726 if (app.adjSource instanceof ProcessRecord) {
8727 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008728 currApp.importanceReasonImportance = oomAdjToImportance(
8729 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008730 } else if (app.adjSource instanceof ActivityRecord) {
8731 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008732 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8733 }
8734 if (app.adjTarget instanceof ComponentName) {
8735 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8736 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008737 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008738 // + " lru=" + currApp.lru);
8739 if (runList == null) {
8740 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8741 }
8742 runList.add(currApp);
8743 }
8744 }
8745 }
8746 return runList;
8747 }
8748
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008749 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008750 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008751 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8752 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8753 if (runningApps != null && runningApps.size() > 0) {
8754 Set<String> extList = new HashSet<String>();
8755 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8756 if (app.pkgList != null) {
8757 for (String pkg : app.pkgList) {
8758 extList.add(pkg);
8759 }
8760 }
8761 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008762 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008763 for (String pkg : extList) {
8764 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008765 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008766 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8767 retList.add(info);
8768 }
8769 } catch (RemoteException e) {
8770 }
8771 }
8772 }
8773 return retList;
8774 }
8775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008777 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8778 enforceNotIsolatedCaller("getMyMemoryState");
8779 synchronized (this) {
8780 ProcessRecord proc;
8781 synchronized (mPidsSelfLocked) {
8782 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8783 }
8784 fillInProcMemInfo(proc, outInfo);
8785 }
8786 }
8787
8788 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008790 if (checkCallingPermission(android.Manifest.permission.DUMP)
8791 != PackageManager.PERMISSION_GRANTED) {
8792 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8793 + Binder.getCallingPid()
8794 + ", uid=" + Binder.getCallingUid()
8795 + " without permission "
8796 + android.Manifest.permission.DUMP);
8797 return;
8798 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008799
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008800 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008801 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008802 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803
8804 int opti = 0;
8805 while (opti < args.length) {
8806 String opt = args[opti];
8807 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8808 break;
8809 }
8810 opti++;
8811 if ("-a".equals(opt)) {
8812 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008813 } else if ("-c".equals(opt)) {
8814 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008815 } else if ("-h".equals(opt)) {
8816 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008817 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008819 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008820 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008821 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8822 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008823 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008824 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008825 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008826 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008827 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008828 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008829 pw.println(" all: dump all activities");
8830 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008831 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008832 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8833 pw.println(" a partial substring in a component name, a");
8834 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008835 pw.println(" -a: include all available server state.");
8836 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008838 } else {
8839 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008842
8843 long origId = Binder.clearCallingIdentity();
8844 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 // Is the caller requesting to dump a particular piece of data?
8846 if (opti < args.length) {
8847 String cmd = args[opti];
8848 opti++;
8849 if ("activities".equals(cmd) || "a".equals(cmd)) {
8850 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008851 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008853 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 String[] newArgs;
8855 String name;
8856 if (opti >= args.length) {
8857 name = null;
8858 newArgs = EMPTY_STRING_ARRAY;
8859 } else {
8860 name = args[opti];
8861 opti++;
8862 newArgs = new String[args.length - opti];
8863 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8864 args.length - opti);
8865 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008868 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008869 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008870 String[] newArgs;
8871 String name;
8872 if (opti >= args.length) {
8873 name = null;
8874 newArgs = EMPTY_STRING_ARRAY;
8875 } else {
8876 name = args[opti];
8877 opti++;
8878 newArgs = new String[args.length - opti];
8879 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8880 args.length - opti);
8881 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008882 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008883 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008885 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008886 String[] newArgs;
8887 String name;
8888 if (opti >= args.length) {
8889 name = null;
8890 newArgs = EMPTY_STRING_ARRAY;
8891 } else {
8892 name = args[opti];
8893 opti++;
8894 newArgs = new String[args.length - opti];
8895 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8896 args.length - opti);
8897 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008899 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008900 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008901 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8902 synchronized (this) {
8903 dumpOomLocked(fd, pw, args, opti, true);
8904 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008905 } else if ("provider".equals(cmd)) {
8906 String[] newArgs;
8907 String name;
8908 if (opti >= args.length) {
8909 name = null;
8910 newArgs = EMPTY_STRING_ARRAY;
8911 } else {
8912 name = args[opti];
8913 opti++;
8914 newArgs = new String[args.length - opti];
8915 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8916 }
8917 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8918 pw.println("No providers match: " + name);
8919 pw.println("Use -h for help.");
8920 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008921 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8922 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008923 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008925 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008926 String[] newArgs;
8927 String name;
8928 if (opti >= args.length) {
8929 name = null;
8930 newArgs = EMPTY_STRING_ARRAY;
8931 } else {
8932 name = args[opti];
8933 opti++;
8934 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008935 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8936 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008937 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008938 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008939 pw.println("No services match: " + name);
8940 pw.println("Use -h for help.");
8941 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 } else if ("package".equals(cmd)) {
8943 String[] newArgs;
8944 if (opti >= args.length) {
8945 pw.println("package: no package name specified");
8946 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008947 } else {
8948 dumpPackage = args[opti];
8949 opti++;
8950 newArgs = new String[args.length - opti];
8951 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8952 args.length - opti);
8953 args = newArgs;
8954 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008955 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008956 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008957 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8958 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008959 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008961 } else {
8962 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008963 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8964 pw.println("Bad activity command, or no activities match: " + cmd);
8965 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008966 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008967 }
8968 if (!more) {
8969 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008970 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008972 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008973
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008974 // No piece of data specified, dump everything.
8975 synchronized (this) {
8976 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008977 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 if (needSep) {
8979 pw.println(" ");
8980 }
8981 if (dumpAll) {
8982 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 if (needSep) {
8986 pw.println(" ");
8987 }
8988 if (dumpAll) {
8989 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 if (needSep) {
8993 pw.println(" ");
8994 }
8995 if (dumpAll) {
8996 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008998 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 if (needSep) {
9000 pw.println(" ");
9001 }
9002 if (dumpAll) {
9003 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009004 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009005 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 if (needSep) {
9007 pw.println(" ");
9008 }
9009 if (dumpAll) {
9010 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009012 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009014 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009016
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009017 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009018 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009019 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9020 pw.println(" Main stack:");
Craig Mautnercae015f2013-02-08 14:31:27 -08009021 mMainStack.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022 pw.println(" ");
9023 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009024 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9025 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009026 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009029 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009030 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009032 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009034 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009035 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009036 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009038 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9039 pw.println(" ");
9040 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009041 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009042 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009043 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009044 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 pw.println(" ");
9046 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009048 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009052 if (mMainStack.mPausingActivity != null) {
9053 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009055 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009057 if (dumpAll) {
9058 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9059 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009060 pw.println(" mDismissKeyguardOnNextActivity: "
9061 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009064 if (mRecentTasks.size() > 0) {
9065 pw.println();
9066 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067
9068 final int N = mRecentTasks.size();
9069 for (int i=0; i<N; i++) {
9070 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009071 if (dumpPackage != null) {
9072 if (tr.realActivity == null ||
9073 !dumpPackage.equals(tr.realActivity)) {
9074 continue;
9075 }
9076 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009077 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9078 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009079 if (dumpAll) {
9080 mRecentTasks.get(i).dump(pw, " ");
9081 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009082 }
9083 }
9084
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009085 if (dumpAll) {
9086 pw.println(" ");
9087 pw.println(" mCurTask: " + mCurTask);
9088 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089
9090 return true;
9091 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009092
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009093 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009095 boolean needSep = false;
9096 int numPers = 0;
9097
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009098 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9099
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9102 final int NA = procs.size();
9103 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009104 ProcessRecord r = procs.valueAt(ia);
9105 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9106 continue;
9107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 if (!needSep) {
9109 pw.println(" All known processes:");
9110 needSep = true;
9111 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009112 pw.print(r.persistent ? " *PERS*" : " *APP*");
9113 pw.print(" UID "); pw.print(procs.keyAt(ia));
9114 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 r.dump(pw, " ");
9116 if (r.persistent) {
9117 numPers++;
9118 }
9119 }
9120 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009122
9123 if (mIsolatedProcesses.size() > 0) {
9124 if (needSep) pw.println(" ");
9125 needSep = true;
9126 pw.println(" Isolated process list (sorted by uid):");
9127 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9128 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9129 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9130 continue;
9131 }
9132 pw.println(String.format("%sIsolated #%2d: %s",
9133 " ", i, r.toString()));
9134 }
9135 }
9136
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009137 if (mLruProcesses.size() > 0) {
9138 if (needSep) pw.println(" ");
9139 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009140 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009141 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009142 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009143 needSep = true;
9144 }
9145
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009146 if (dumpAll) {
9147 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009148 boolean printed = false;
9149 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9150 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9151 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9152 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009153 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009154 if (!printed) {
9155 if (needSep) pw.println(" ");
9156 needSep = true;
9157 pw.println(" PID mappings:");
9158 printed = true;
9159 }
9160 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9161 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162 }
9163 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164 }
9165
9166 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009167 synchronized (mPidsSelfLocked) {
9168 boolean printed = false;
9169 for (int i=0; i<mForegroundProcesses.size(); i++) {
9170 ProcessRecord r = mPidsSelfLocked.get(
9171 mForegroundProcesses.valueAt(i).pid);
9172 if (dumpPackage != null && (r == null
9173 || !dumpPackage.equals(r.info.packageName))) {
9174 continue;
9175 }
9176 if (!printed) {
9177 if (needSep) pw.println(" ");
9178 needSep = true;
9179 pw.println(" Foreground Processes:");
9180 printed = true;
9181 }
9182 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9183 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009185 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009186 }
9187
9188 if (mPersistentStartingProcesses.size() > 0) {
9189 if (needSep) pw.println(" ");
9190 needSep = true;
9191 pw.println(" Persisent processes that are starting:");
9192 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009193 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009195
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009196 if (mRemovedProcesses.size() > 0) {
9197 if (needSep) pw.println(" ");
9198 needSep = true;
9199 pw.println(" Processes that are being removed:");
9200 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009201 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 }
9203
9204 if (mProcessesOnHold.size() > 0) {
9205 if (needSep) pw.println(" ");
9206 needSep = true;
9207 pw.println(" Processes that are on old until the system is ready:");
9208 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009212 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213
9214 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009215 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 long now = SystemClock.uptimeMillis();
9217 for (Map.Entry<String, SparseArray<Long>> procs
9218 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009219 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 SparseArray<Long> uids = procs.getValue();
9221 final int N = uids.size();
9222 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009223 int puid = uids.keyAt(i);
9224 ProcessRecord r = mProcessNames.get(pname, puid);
9225 if (dumpPackage != null && (r == null
9226 || !dumpPackage.equals(r.info.packageName))) {
9227 continue;
9228 }
9229 if (!printed) {
9230 if (needSep) pw.println(" ");
9231 needSep = true;
9232 pw.println(" Time since processes crashed:");
9233 printed = true;
9234 }
9235 pw.print(" Process "); pw.print(pname);
9236 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009238 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9239 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009240 }
9241 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009244 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009245 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 for (Map.Entry<String, SparseArray<Long>> procs
9247 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009248 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009249 SparseArray<Long> uids = procs.getValue();
9250 final int N = uids.size();
9251 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009252 int puid = uids.keyAt(i);
9253 ProcessRecord r = mProcessNames.get(pname, puid);
9254 if (dumpPackage != null && (r == null
9255 || !dumpPackage.equals(r.info.packageName))) {
9256 continue;
9257 }
9258 if (!printed) {
9259 if (needSep) pw.println(" ");
9260 needSep = true;
9261 pw.println(" Bad processes:");
9262 }
9263 pw.print(" Bad process "); pw.print(pname);
9264 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 pw.print(": crashed at time ");
9266 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 }
9268 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009271 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009272 pw.println(" mStartedUsers:");
9273 for (int i=0; i<mStartedUsers.size(); i++) {
9274 UserStartedState uss = mStartedUsers.valueAt(i);
9275 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009276 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009277 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009278 pw.print(" mStartedUserArray: [");
9279 for (int i=0; i<mStartedUserArray.length; i++) {
9280 if (i > 0) pw.print(", ");
9281 pw.print(mStartedUserArray[i]);
9282 }
9283 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009284 pw.print(" mUserLru: [");
9285 for (int i=0; i<mUserLru.size(); i++) {
9286 if (i > 0) pw.print(", ");
9287 pw.print(mUserLru.get(i));
9288 }
9289 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009290 if (dumpAll) {
9291 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9292 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009293 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009294 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009295 if (dumpAll) {
9296 StringBuilder sb = new StringBuilder(128);
9297 sb.append(" mPreviousProcessVisibleTime: ");
9298 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9299 pw.println(sb);
9300 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009301 if (mHeavyWeightProcess != null) {
9302 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9303 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009304 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 if (dumpAll) {
9306 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009307 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009308 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009309 for (Map.Entry<String, Integer> entry
9310 : mCompatModePackages.getPackages().entrySet()) {
9311 String pkg = entry.getKey();
9312 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9314 continue;
9315 }
9316 if (!printed) {
9317 pw.println(" mScreenCompatPackages:");
9318 printed = true;
9319 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009320 pw.print(" "); pw.print(pkg); pw.print(": ");
9321 pw.print(mode); pw.println();
9322 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009323 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009324 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009325 if (mSleeping || mWentToSleep || mLockScreenShown) {
9326 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9327 + " mLockScreenShown " + mLockScreenShown);
9328 }
9329 if (mShuttingDown) {
9330 pw.println(" mShuttingDown=" + mShuttingDown);
9331 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009332 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9333 || mOrigWaitForDebugger) {
9334 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9335 + " mDebugTransient=" + mDebugTransient
9336 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9337 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009338 if (mOpenGlTraceApp != null) {
9339 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9340 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009341 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9342 || mProfileFd != null) {
9343 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9344 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9345 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9346 + mAutoStopProfiler);
9347 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009348 if (mAlwaysFinishActivities || mController != null) {
9349 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9350 + " mController=" + mController);
9351 }
9352 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009353 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009354 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009355 + " mProcessesReady=" + mProcessesReady
9356 + " mSystemReady=" + mSystemReady);
9357 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009358 + " mBooted=" + mBooted
9359 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009360 pw.print(" mLastPowerCheckRealtime=");
9361 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9362 pw.println("");
9363 pw.print(" mLastPowerCheckUptime=");
9364 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9365 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009366 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9367 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009368 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009369 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9370 + " mNumHiddenProcs=" + mNumHiddenProcs
9371 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009372 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009373 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374
9375 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009376 }
9377
Dianne Hackborn287952c2010-09-22 22:34:31 -07009378 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009379 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009380 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009381 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009382 long now = SystemClock.uptimeMillis();
9383 for (int i=0; i<mProcessesToGc.size(); i++) {
9384 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009385 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9386 continue;
9387 }
9388 if (!printed) {
9389 if (needSep) pw.println(" ");
9390 needSep = true;
9391 pw.println(" Processes that are waiting to GC:");
9392 printed = true;
9393 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009394 pw.print(" Process "); pw.println(proc);
9395 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9396 pw.print(", last gced=");
9397 pw.print(now-proc.lastRequestedGc);
9398 pw.print(" ms ago, last lowMem=");
9399 pw.print(now-proc.lastLowMemory);
9400 pw.println(" ms ago");
9401
9402 }
9403 }
9404 return needSep;
9405 }
9406
9407 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9408 int opti, boolean dumpAll) {
9409 boolean needSep = false;
9410
9411 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009412 if (needSep) pw.println(" ");
9413 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009414 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009415 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009416 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009417 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9418 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9419 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9420 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9421 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009422 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009423 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009424 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009425 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009426 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009427 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009428
9429 if (needSep) pw.println(" ");
9430 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009431 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009432 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009433 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009434 needSep = true;
9435 }
9436
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009437 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009438
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009439 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009440 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009441 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009442 if (mHeavyWeightProcess != null) {
9443 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9444 }
9445
9446 return true;
9447 }
9448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009449 /**
9450 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009451 * - no provider specified: dump all the providers
9452 * - a flattened component name that matched an existing provider was specified as the
9453 * first arg: dump that one provider
9454 * - the first arg isn't the flattened component name of an existing provider:
9455 * dump all providers whose component contains the first arg as a substring
9456 */
9457 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9458 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009459 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009460 }
9461
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009462 static class ItemMatcher {
9463 ArrayList<ComponentName> components;
9464 ArrayList<String> strings;
9465 ArrayList<Integer> objects;
9466 boolean all;
9467
9468 ItemMatcher() {
9469 all = true;
9470 }
9471
9472 void build(String name) {
9473 ComponentName componentName = ComponentName.unflattenFromString(name);
9474 if (componentName != null) {
9475 if (components == null) {
9476 components = new ArrayList<ComponentName>();
9477 }
9478 components.add(componentName);
9479 all = false;
9480 } else {
9481 int objectId = 0;
9482 // Not a '/' separated full component name; maybe an object ID?
9483 try {
9484 objectId = Integer.parseInt(name, 16);
9485 if (objects == null) {
9486 objects = new ArrayList<Integer>();
9487 }
9488 objects.add(objectId);
9489 all = false;
9490 } catch (RuntimeException e) {
9491 // Not an integer; just do string match.
9492 if (strings == null) {
9493 strings = new ArrayList<String>();
9494 }
9495 strings.add(name);
9496 all = false;
9497 }
9498 }
9499 }
9500
9501 int build(String[] args, int opti) {
9502 for (; opti<args.length; opti++) {
9503 String name = args[opti];
9504 if ("--".equals(name)) {
9505 return opti+1;
9506 }
9507 build(name);
9508 }
9509 return opti;
9510 }
9511
9512 boolean match(Object object, ComponentName comp) {
9513 if (all) {
9514 return true;
9515 }
9516 if (components != null) {
9517 for (int i=0; i<components.size(); i++) {
9518 if (components.get(i).equals(comp)) {
9519 return true;
9520 }
9521 }
9522 }
9523 if (objects != null) {
9524 for (int i=0; i<objects.size(); i++) {
9525 if (System.identityHashCode(object) == objects.get(i)) {
9526 return true;
9527 }
9528 }
9529 }
9530 if (strings != null) {
9531 String flat = comp.flattenToString();
9532 for (int i=0; i<strings.size(); i++) {
9533 if (flat.contains(strings.get(i))) {
9534 return true;
9535 }
9536 }
9537 }
9538 return false;
9539 }
9540 }
9541
Dianne Hackborn625ac272010-09-17 18:29:22 -07009542 /**
9543 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009544 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009545 * - the cmd arg isn't the flattened component name of an existing activity:
9546 * dump all activity whose component contains the cmd as a substring
9547 * - A hex number of the ActivityRecord object instance.
9548 */
9549 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9550 int opti, boolean dumpAll) {
Craig Mautnercae015f2013-02-08 14:31:27 -08009551 ArrayList<ActivityRecord> activities;
9552
9553 synchronized (this) {
9554 activities = mMainStack.getDumpActivitiesLocked(name);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009555 }
9556
9557 if (activities.size() <= 0) {
9558 return false;
9559 }
9560
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009561 String[] newArgs = new String[args.length - opti];
9562 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9563
Dianne Hackborn30d71892010-12-11 10:37:55 -08009564 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009565 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009566 for (int i=activities.size()-1; i>=0; i--) {
9567 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009568 if (needSep) {
9569 pw.println();
9570 }
9571 needSep = true;
9572 synchronized (this) {
9573 if (lastTask != r.task) {
9574 lastTask = r.task;
9575 pw.print("TASK "); pw.print(lastTask.affinity);
9576 pw.print(" id="); pw.println(lastTask.taskId);
9577 if (dumpAll) {
9578 lastTask.dump(pw, " ");
9579 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009580 }
9581 }
9582 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009583 }
9584 return true;
9585 }
9586
9587 /**
9588 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9589 * there is a thread associated with the activity.
9590 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009591 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 final ActivityRecord r, String[] args, boolean dumpAll) {
9593 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009594 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009595 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9596 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9597 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009598 if (r.app != null) pw.println(r.app.pid);
9599 else pw.println("(not running)");
9600 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009601 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009602 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009603 }
9604 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 // flush anything that is already in the PrintWriter since the thread is going
9606 // to write to the file descriptor directly
9607 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009608 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009609 TransferPipe tp = new TransferPipe();
9610 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009611 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9612 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009613 tp.go(fd);
9614 } finally {
9615 tp.kill();
9616 }
9617 } catch (IOException e) {
9618 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009619 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009620 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009621 }
9622 }
9623 }
9624
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009625 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009626 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009627 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009628 boolean onlyHistory = false;
9629
9630 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009631 if (opti < args.length && "-s".equals(args[opti])) {
9632 dumpAll = false;
9633 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009634 onlyHistory = true;
9635 dumpPackage = null;
9636 }
9637
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009638 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009639 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009640 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009641 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642 Iterator it = mRegisteredReceivers.values().iterator();
9643 while (it.hasNext()) {
9644 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009645 if (dumpPackage != null && (r.app == null ||
9646 !dumpPackage.equals(r.app.info.packageName))) {
9647 continue;
9648 }
9649 if (!printed) {
9650 pw.println(" Registered Receivers:");
9651 needSep = true;
9652 printed = true;
9653 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009654 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 r.dump(pw, " ");
9656 }
9657 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009658
9659 if (mReceiverResolver.dump(pw, needSep ?
9660 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9661 " ", dumpPackage, false)) {
9662 needSep = true;
9663 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009664 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009665
9666 for (BroadcastQueue q : mBroadcastQueues) {
9667 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009670 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009671
Dianne Hackborn786b4402012-08-27 15:14:02 -07009672 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009673 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9674 if (needSep) {
9675 pw.println();
9676 }
9677 needSep = true;
9678 pw.print(" Sticky broadcasts for user ");
9679 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9680 StringBuilder sb = new StringBuilder(128);
9681 for (Map.Entry<String, ArrayList<Intent>> ent
9682 : mStickyBroadcasts.valueAt(user).entrySet()) {
9683 pw.print(" * Sticky action "); pw.print(ent.getKey());
9684 if (dumpAll) {
9685 pw.println(":");
9686 ArrayList<Intent> intents = ent.getValue();
9687 final int N = intents.size();
9688 for (int i=0; i<N; i++) {
9689 sb.setLength(0);
9690 sb.append(" Intent: ");
9691 intents.get(i).toShortString(sb, false, true, false, false);
9692 pw.println(sb.toString());
9693 Bundle bundle = intents.get(i).getExtras();
9694 if (bundle != null) {
9695 pw.print(" ");
9696 pw.println(bundle.toString());
9697 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009698 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009699 } else {
9700 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009701 }
9702 }
9703 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009704 }
9705
Dianne Hackborn786b4402012-08-27 15:14:02 -07009706 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009707 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009708 for (BroadcastQueue queue : mBroadcastQueues) {
9709 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9710 + queue.mBroadcastsScheduled);
9711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009712 pw.println(" mHandler:");
9713 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009714 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009715 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009716
9717 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 }
9719
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009720 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009721 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009722 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009723
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009724 ItemMatcher matcher = new ItemMatcher();
9725 matcher.build(args, opti);
9726
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009727 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009728
9729 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009730
9731 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009732 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009733 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009734 ContentProviderRecord r = mLaunchingProviders.get(i);
9735 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9736 continue;
9737 }
9738 if (!printed) {
9739 if (needSep) pw.println(" ");
9740 needSep = true;
9741 pw.println(" Launching content providers:");
9742 printed = true;
9743 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009744 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009745 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009747 }
9748
9749 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 if (needSep) pw.println();
9751 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009752 pw.println("Granted Uri Permissions:");
9753 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9754 int uid = mGrantedUriPermissions.keyAt(i);
9755 HashMap<Uri, UriPermission> perms
9756 = mGrantedUriPermissions.valueAt(i);
9757 pw.print(" * UID "); pw.print(uid);
9758 pw.println(" holds:");
9759 for (UriPermission perm : perms.values()) {
9760 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009761 if (dumpAll) {
9762 perm.dump(pw, " ");
9763 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009764 }
9765 }
9766 needSep = true;
9767 }
9768
9769 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770 }
9771
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009772 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009773 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774 boolean needSep = false;
9775
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009776 if (mIntentSenderRecords.size() > 0) {
9777 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009778 Iterator<WeakReference<PendingIntentRecord>> it
9779 = mIntentSenderRecords.values().iterator();
9780 while (it.hasNext()) {
9781 WeakReference<PendingIntentRecord> ref = it.next();
9782 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009783 if (dumpPackage != null && (rec == null
9784 || !dumpPackage.equals(rec.key.packageName))) {
9785 continue;
9786 }
9787 if (!printed) {
9788 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9789 printed = true;
9790 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009791 needSep = true;
9792 if (rec != null) {
9793 pw.print(" * "); pw.println(rec);
9794 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009795 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009797 } else {
9798 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009799 }
9800 }
9801 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009802
9803 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009804 }
9805
Craig Mautnercae015f2013-02-08 14:31:27 -08009806 static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009807 String prefix, String label, boolean complete, boolean brief, boolean client,
9808 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009809 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009810 boolean needNL = false;
9811 final String innerPrefix = prefix + " ";
9812 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009813 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009815 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9816 continue;
9817 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009818 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009819 if (needNL) {
9820 pw.println(" ");
9821 needNL = false;
9822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009823 if (lastTask != r.task) {
9824 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009825 pw.print(prefix);
9826 pw.print(full ? "* " : " ");
9827 pw.println(lastTask);
9828 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009829 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009830 } else if (complete) {
9831 // Complete + brief == give a summary. Isn't that obvious?!?
9832 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009833 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009834 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009835 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009838 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9839 pw.print(" #"); pw.print(i); pw.print(": ");
9840 pw.println(r);
9841 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009842 r.dump(pw, innerPrefix);
9843 } else if (complete) {
9844 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009845 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009846 if (r.app != null) {
9847 pw.print(innerPrefix); pw.println(r.app);
9848 }
9849 }
9850 if (client && r.app != null && r.app.thread != null) {
9851 // flush anything that is already in the PrintWriter since the thread is going
9852 // to write to the file descriptor directly
9853 pw.flush();
9854 try {
9855 TransferPipe tp = new TransferPipe();
9856 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009857 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9858 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009859 // Short timeout, since blocking here can
9860 // deadlock with the application.
9861 tp.go(fd, 2000);
9862 } finally {
9863 tp.kill();
9864 }
9865 } catch (IOException e) {
9866 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9867 } catch (RemoteException e) {
9868 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9869 }
9870 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009872 }
9873 }
9874
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009875 private static String buildOomTag(String prefix, String space, int val, int base) {
9876 if (val == base) {
9877 if (space == null) return prefix;
9878 return prefix + " ";
9879 }
9880 return prefix + "+" + Integer.toString(val-base);
9881 }
9882
9883 private static final int dumpProcessList(PrintWriter pw,
9884 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009885 String prefix, String normalLabel, String persistentLabel,
9886 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009888 final int N = list.size()-1;
9889 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009890 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009891 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9892 continue;
9893 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009894 pw.println(String.format("%s%s #%2d: %s",
9895 prefix, (r.persistent ? persistentLabel : normalLabel),
9896 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009897 if (r.persistent) {
9898 numPers++;
9899 }
9900 }
9901 return numPers;
9902 }
9903
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009904 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009905 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009906 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009907 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009908
Dianne Hackborn905577f2011-09-07 18:31:28 -07009909 ArrayList<Pair<ProcessRecord, Integer>> list
9910 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9911 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009912 ProcessRecord r = origList.get(i);
9913 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9914 continue;
9915 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009916 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9917 }
9918
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009919 if (list.size() <= 0) {
9920 return false;
9921 }
9922
Dianne Hackborn905577f2011-09-07 18:31:28 -07009923 Comparator<Pair<ProcessRecord, Integer>> comparator
9924 = new Comparator<Pair<ProcessRecord, Integer>>() {
9925 @Override
9926 public int compare(Pair<ProcessRecord, Integer> object1,
9927 Pair<ProcessRecord, Integer> object2) {
9928 if (object1.first.setAdj != object2.first.setAdj) {
9929 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9930 }
9931 if (object1.second.intValue() != object2.second.intValue()) {
9932 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9933 }
9934 return 0;
9935 }
9936 };
9937
9938 Collections.sort(list, comparator);
9939
Dianne Hackborn287952c2010-09-22 22:34:31 -07009940 final long curRealtime = SystemClock.elapsedRealtime();
9941 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9942 final long curUptime = SystemClock.uptimeMillis();
9943 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9944
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009945 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009946 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009947 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009948 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009949 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009950 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9951 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009952 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9953 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009954 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9955 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009956 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9957 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009958 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009959 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009960 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9961 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9962 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9963 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9964 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9965 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9966 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9967 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009968 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9969 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009970 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9971 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009972 } else {
9973 oomAdj = Integer.toString(r.setAdj);
9974 }
9975 String schedGroup;
9976 switch (r.setSchedGroup) {
9977 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9978 schedGroup = "B";
9979 break;
9980 case Process.THREAD_GROUP_DEFAULT:
9981 schedGroup = "F";
9982 break;
9983 default:
9984 schedGroup = Integer.toString(r.setSchedGroup);
9985 break;
9986 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009987 String foreground;
9988 if (r.foregroundActivities) {
9989 foreground = "A";
9990 } else if (r.foregroundServices) {
9991 foreground = "S";
9992 } else {
9993 foreground = " ";
9994 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009995 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009996 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009997 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9998 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009999 if (r.adjSource != null || r.adjTarget != null) {
10000 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010001 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010002 if (r.adjTarget instanceof ComponentName) {
10003 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10004 } else if (r.adjTarget != null) {
10005 pw.print(r.adjTarget.toString());
10006 } else {
10007 pw.print("{null}");
10008 }
10009 pw.print("<=");
10010 if (r.adjSource instanceof ProcessRecord) {
10011 pw.print("Proc{");
10012 pw.print(((ProcessRecord)r.adjSource).toShortString());
10013 pw.println("}");
10014 } else if (r.adjSource != null) {
10015 pw.println(r.adjSource.toString());
10016 } else {
10017 pw.println("{null}");
10018 }
10019 }
10020 if (inclDetails) {
10021 pw.print(prefix);
10022 pw.print(" ");
10023 pw.print("oom: max="); pw.print(r.maxAdj);
10024 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010025 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010026 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010027 pw.print(" curRaw="); pw.print(r.curRawAdj);
10028 pw.print(" setRaw="); pw.print(r.setRawAdj);
10029 pw.print(" cur="); pw.print(r.curAdj);
10030 pw.print(" set="); pw.println(r.setAdj);
10031 pw.print(prefix);
10032 pw.print(" ");
10033 pw.print("keeping="); pw.print(r.keeping);
10034 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010035 pw.print(" empty="); pw.print(r.empty);
10036 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010037
10038 if (!r.keeping) {
10039 if (r.lastWakeTime != 0) {
10040 long wtime;
10041 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10042 synchronized (stats) {
10043 wtime = stats.getProcessWakeTime(r.info.uid,
10044 r.pid, curRealtime);
10045 }
10046 long timeUsed = wtime - r.lastWakeTime;
10047 pw.print(prefix);
10048 pw.print(" ");
10049 pw.print("keep awake over ");
10050 TimeUtils.formatDuration(realtimeSince, pw);
10051 pw.print(" used ");
10052 TimeUtils.formatDuration(timeUsed, pw);
10053 pw.print(" (");
10054 pw.print((timeUsed*100)/realtimeSince);
10055 pw.println("%)");
10056 }
10057 if (r.lastCpuTime != 0) {
10058 long timeUsed = r.curCpuTime - r.lastCpuTime;
10059 pw.print(prefix);
10060 pw.print(" ");
10061 pw.print("run cpu over ");
10062 TimeUtils.formatDuration(uptimeSince, pw);
10063 pw.print(" used ");
10064 TimeUtils.formatDuration(timeUsed, pw);
10065 pw.print(" (");
10066 pw.print((timeUsed*100)/uptimeSince);
10067 pw.println("%)");
10068 }
10069 }
10070 }
10071 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010072 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010073 }
10074
Dianne Hackbornb437e092011-08-05 17:50:29 -070010075 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010076 ArrayList<ProcessRecord> procs;
10077 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010078 if (args != null && args.length > start
10079 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010080 procs = new ArrayList<ProcessRecord>();
10081 int pid = -1;
10082 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010083 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010084 } catch (NumberFormatException e) {
10085
10086 }
10087 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10088 ProcessRecord proc = mLruProcesses.get(i);
10089 if (proc.pid == pid) {
10090 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010091 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010092 procs.add(proc);
10093 }
10094 }
10095 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010096 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010097 return null;
10098 }
10099 } else {
10100 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10101 }
10102 }
10103 return procs;
10104 }
10105
10106 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10107 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010108 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010109 if (procs == null) {
10110 return;
10111 }
10112
10113 long uptime = SystemClock.uptimeMillis();
10114 long realtime = SystemClock.elapsedRealtime();
10115 pw.println("Applications Graphics Acceleration Info:");
10116 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10117
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010118 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10119 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010120 if (r.thread != null) {
10121 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10122 pw.flush();
10123 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010124 TransferPipe tp = new TransferPipe();
10125 try {
10126 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10127 tp.go(fd);
10128 } finally {
10129 tp.kill();
10130 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010131 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010132 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010133 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010134 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010135 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010136 pw.flush();
10137 }
10138 }
10139 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010140 }
10141
Jeff Brown6754ba22011-12-14 20:20:01 -080010142 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10143 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10144 if (procs == null) {
10145 return;
10146 }
10147
10148 pw.println("Applications Database Info:");
10149
10150 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10151 ProcessRecord r = procs.get(i);
10152 if (r.thread != null) {
10153 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10154 pw.flush();
10155 try {
10156 TransferPipe tp = new TransferPipe();
10157 try {
10158 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10159 tp.go(fd);
10160 } finally {
10161 tp.kill();
10162 }
10163 } catch (IOException e) {
10164 pw.println("Failure while dumping the app: " + r);
10165 pw.flush();
10166 } catch (RemoteException e) {
10167 pw.println("Got a RemoteException while dumping the app " + r);
10168 pw.flush();
10169 }
10170 }
10171 }
10172 }
10173
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010174 final static class MemItem {
10175 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010176 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010177 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010178 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010179 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010180
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010181 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010182 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010183 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010184 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010185 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010186 }
10187 }
10188
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010189 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010190 boolean sort) {
10191 if (sort) {
10192 Collections.sort(items, new Comparator<MemItem>() {
10193 @Override
10194 public int compare(MemItem lhs, MemItem rhs) {
10195 if (lhs.pss < rhs.pss) {
10196 return 1;
10197 } else if (lhs.pss > rhs.pss) {
10198 return -1;
10199 }
10200 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010201 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010202 });
10203 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010204
10205 for (int i=0; i<items.size(); i++) {
10206 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010207 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010208 if (mi.subitems != null) {
10209 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10210 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010211 }
10212 }
10213
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010214 // These are in KB.
10215 static final long[] DUMP_MEM_BUCKETS = new long[] {
10216 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10217 120*1024, 160*1024, 200*1024,
10218 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10219 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10220 };
10221
Dianne Hackborn672342c2011-11-29 11:29:02 -080010222 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10223 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010224 int start = label.lastIndexOf('.');
10225 if (start >= 0) start++;
10226 else start = 0;
10227 int end = label.length();
10228 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10229 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10230 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10231 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010232 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 out.append(label, start, end);
10234 return;
10235 }
10236 }
10237 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010238 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010239 out.append(label, start, end);
10240 }
10241
10242 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10243 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10244 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10245 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10246 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10247 };
10248 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10249 "System", "Persistent", "Foreground",
10250 "Visible", "Perceptible", "Heavy Weight",
10251 "Backup", "A Services", "Home", "Previous",
10252 "B Services", "Background"
10253 };
10254
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010255 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010256 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010257 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010258 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010259 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010260
10261 int opti = 0;
10262 while (opti < args.length) {
10263 String opt = args[opti];
10264 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10265 break;
10266 }
10267 opti++;
10268 if ("-a".equals(opt)) {
10269 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010270 } else if ("--oom".equals(opt)) {
10271 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010272 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010273 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010274 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010275 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010276 pw.println("If [process] is specified it can be the name or ");
10277 pw.println("pid of a specific process to dump.");
10278 return;
10279 } else {
10280 pw.println("Unknown argument: " + opt + "; use -h for help");
10281 }
10282 }
10283
10284 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010285 if (procs == null) {
10286 return;
10287 }
10288
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010289 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010290 long uptime = SystemClock.uptimeMillis();
10291 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010292
10293 if (procs.size() == 1 || isCheckinRequest) {
10294 dumpAll = true;
10295 }
10296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 if (isCheckinRequest) {
10298 // short checkin version
10299 pw.println(uptime + "," + realtime);
10300 pw.flush();
10301 } else {
10302 pw.println("Applications Memory Usage (kB):");
10303 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10304 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010305
Dianne Hackbornb437e092011-08-05 17:50:29 -070010306 String[] innerArgs = new String[args.length-opti];
10307 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10308
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010309 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10310 long nativePss=0, dalvikPss=0, otherPss=0;
10311 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10312
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010313 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10314 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10315 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316
10317 long totalPss = 0;
10318
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010319 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10320 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010321 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010322 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10324 pw.flush();
10325 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010326 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010327 if (dumpAll) {
10328 try {
10329 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10330 } catch (RemoteException e) {
10331 if (!isCheckinRequest) {
10332 pw.println("Got RemoteException!");
10333 pw.flush();
10334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010335 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010336 } else {
10337 mi = new Debug.MemoryInfo();
10338 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010339 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010340
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010341 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010342 long myTotalPss = mi.getTotalPss();
10343 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010344 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010345 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010346 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010347
10348 nativePss += mi.nativePss;
10349 dalvikPss += mi.dalvikPss;
10350 otherPss += mi.otherPss;
10351 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10352 long mem = mi.getOtherPss(j);
10353 miscPss[j] += mem;
10354 otherPss -= mem;
10355 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010356
10357 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010358 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10359 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010360 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010361 if (oomProcs[oomIndex] == null) {
10362 oomProcs[oomIndex] = new ArrayList<MemItem>();
10363 }
10364 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010365 break;
10366 }
10367 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010369 }
10370 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010371
10372 if (!isCheckinRequest && procs.size() > 1) {
10373 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10374
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010375 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10376 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10377 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010378 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010379 String label = Debug.MemoryInfo.getOtherLabel(j);
10380 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010381 }
10382
Dianne Hackbornb437e092011-08-05 17:50:29 -070010383 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10384 for (int j=0; j<oomPss.length; j++) {
10385 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010386 String label = DUMP_MEM_OOM_LABEL[j];
10387 MemItem item = new MemItem(label, label, oomPss[j],
10388 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010389 item.subitems = oomProcs[j];
10390 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010391 }
10392 }
10393
Dianne Hackborn672342c2011-11-29 11:29:02 -080010394 if (outTag != null || outStack != null) {
10395 if (outTag != null) {
10396 appendMemBucket(outTag, totalPss, "total", false);
10397 }
10398 if (outStack != null) {
10399 appendMemBucket(outStack, totalPss, "total", true);
10400 }
10401 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010402 for (int i=0; i<oomMems.size(); i++) {
10403 MemItem miCat = oomMems.get(i);
10404 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10405 continue;
10406 }
10407 if (miCat.id < ProcessList.SERVICE_ADJ
10408 || miCat.id == ProcessList.HOME_APP_ADJ
10409 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010410 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10411 outTag.append(" / ");
10412 }
10413 if (outStack != null) {
10414 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10415 if (firstLine) {
10416 outStack.append(":");
10417 firstLine = false;
10418 }
10419 outStack.append("\n\t at ");
10420 } else {
10421 outStack.append("$");
10422 }
10423 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010424 for (int j=0; j<miCat.subitems.size(); j++) {
10425 MemItem mi = miCat.subitems.get(j);
10426 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010427 if (outTag != null) {
10428 outTag.append(" ");
10429 }
10430 if (outStack != null) {
10431 outStack.append("$");
10432 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010433 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010434 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10435 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10436 }
10437 if (outStack != null) {
10438 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10439 }
10440 }
10441 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10442 outStack.append("(");
10443 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10444 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10445 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10446 outStack.append(":");
10447 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10448 }
10449 }
10450 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010451 }
10452 }
10453 }
10454 }
10455
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010456 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010457 pw.println();
10458 pw.println("Total PSS by process:");
10459 dumpMemItems(pw, " ", procMems, true);
10460 pw.println();
10461 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010462 pw.println("Total PSS by OOM adjustment:");
10463 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010464 if (!oomOnly) {
10465 PrintWriter out = categoryPw != null ? categoryPw : pw;
10466 out.println();
10467 out.println("Total PSS by category:");
10468 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010469 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010470 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010471 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010472 final int[] SINGLE_LONG_FORMAT = new int[] {
10473 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10474 };
10475 long[] longOut = new long[1];
10476 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10477 SINGLE_LONG_FORMAT, null, longOut, null);
10478 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10479 longOut[0] = 0;
10480 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10481 SINGLE_LONG_FORMAT, null, longOut, null);
10482 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10483 longOut[0] = 0;
10484 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10485 SINGLE_LONG_FORMAT, null, longOut, null);
10486 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10487 longOut[0] = 0;
10488 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10489 SINGLE_LONG_FORMAT, null, longOut, null);
10490 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10491 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10492 pw.print(shared); pw.println(" kB");
10493 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10494 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010495 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010496 }
10497
10498 /**
10499 * Searches array of arguments for the specified string
10500 * @param args array of argument strings
10501 * @param value value to search for
10502 * @return true if the value is contained in the array
10503 */
10504 private static boolean scanArgs(String[] args, String value) {
10505 if (args != null) {
10506 for (String arg : args) {
10507 if (value.equals(arg)) {
10508 return true;
10509 }
10510 }
10511 }
10512 return false;
10513 }
10514
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010515 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10516 ContentProviderRecord cpr, boolean always) {
10517 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10518
10519 if (!inLaunching || always) {
10520 synchronized (cpr) {
10521 cpr.launchingApp = null;
10522 cpr.notifyAll();
10523 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010524 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010525 String names[] = cpr.info.authority.split(";");
10526 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010527 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 }
10529 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010530
10531 for (int i=0; i<cpr.connections.size(); i++) {
10532 ContentProviderConnection conn = cpr.connections.get(i);
10533 if (conn.waiting) {
10534 // If this connection is waiting for the provider, then we don't
10535 // need to mess with its process unless we are always removing
10536 // or for some reason the provider is not currently launching.
10537 if (inLaunching && !always) {
10538 continue;
10539 }
10540 }
10541 ProcessRecord capp = conn.client;
10542 conn.dead = true;
10543 if (conn.stableCount > 0) {
10544 if (!capp.persistent && capp.thread != null
10545 && capp.pid != 0
10546 && capp.pid != MY_PID) {
10547 Slog.i(TAG, "Kill " + capp.processName
10548 + " (pid " + capp.pid + "): provider " + cpr.info.name
10549 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010550 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010551 capp.processName, capp.setAdj, "dying provider "
10552 + cpr.name.toShortString());
10553 Process.killProcessQuiet(capp.pid);
10554 }
10555 } else if (capp.thread != null && conn.provider.provider != null) {
10556 try {
10557 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10558 } catch (RemoteException e) {
10559 }
10560 // In the protocol here, we don't expect the client to correctly
10561 // clean up this connection, we'll just remove it.
10562 cpr.connections.remove(i);
10563 conn.client.conProviders.remove(conn);
10564 }
10565 }
10566
10567 if (inLaunching && always) {
10568 mLaunchingProviders.remove(cpr);
10569 }
10570 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 }
10572
10573 /**
10574 * Main code for cleaning up a process when it has gone away. This is
10575 * called both as a result of the process dying, or directly when stopping
10576 * a process when running in single process mode.
10577 */
10578 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010579 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010581 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 }
10583
Dianne Hackborn36124872009-10-08 16:22:03 -070010584 mProcessesToGc.remove(app);
10585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586 // Dismiss any open dialogs.
10587 if (app.crashDialog != null) {
10588 app.crashDialog.dismiss();
10589 app.crashDialog = null;
10590 }
10591 if (app.anrDialog != null) {
10592 app.anrDialog.dismiss();
10593 app.anrDialog = null;
10594 }
10595 if (app.waitDialog != null) {
10596 app.waitDialog.dismiss();
10597 app.waitDialog = null;
10598 }
10599
10600 app.crashing = false;
10601 app.notResponding = false;
10602
10603 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010604 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 app.thread = null;
10606 app.forcingToForeground = null;
10607 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010608 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010609 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010610 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010612 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613
10614 boolean restart = false;
10615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 // Remove published content providers.
10617 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010618 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010620 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010621
10622 final boolean always = app.bad || !allowRestart;
10623 if (removeDyingProviderLocked(app, cpr, always) || always) {
10624 // We left the provider in the launching list, need to
10625 // restart it.
10626 restart = true;
10627 }
10628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010629 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010630 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010631 }
10632 app.pubProviders.clear();
10633 }
10634
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010635 // Take care of any launching providers waiting for this process.
10636 if (checkAppInLaunchingProvidersLocked(app, false)) {
10637 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010640 // Unregister from connected content providers.
10641 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010642 for (int i=0; i<app.conProviders.size(); i++) {
10643 ContentProviderConnection conn = app.conProviders.get(i);
10644 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010645 }
10646 app.conProviders.clear();
10647 }
10648
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010649 // At this point there may be remaining entries in mLaunchingProviders
10650 // where we were the only one waiting, so they are no longer of use.
10651 // Look for these and clean up if found.
10652 // XXX Commented out for now. Trying to figure out a way to reproduce
10653 // the actual situation to identify what is actually going on.
10654 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010655 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010656 ContentProviderRecord cpr = (ContentProviderRecord)
10657 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010658 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010659 synchronized (cpr) {
10660 cpr.launchingApp = null;
10661 cpr.notifyAll();
10662 }
10663 }
10664 }
10665 }
10666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 skipCurrentReceiverLocked(app);
10668
10669 // Unregister any receivers.
10670 if (app.receivers.size() > 0) {
10671 Iterator<ReceiverList> it = app.receivers.iterator();
10672 while (it.hasNext()) {
10673 removeReceiverLocked(it.next());
10674 }
10675 app.receivers.clear();
10676 }
10677
Christopher Tate181fafa2009-05-14 11:12:14 -070010678 // If the app is undergoing backup, tell the backup manager about it
10679 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010680 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10681 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010682 try {
10683 IBackupManager bm = IBackupManager.Stub.asInterface(
10684 ServiceManager.getService(Context.BACKUP_SERVICE));
10685 bm.agentDisconnected(app.info.packageName);
10686 } catch (RemoteException e) {
10687 // can't happen; backup manager is local
10688 }
10689 }
10690
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010691 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10692 ProcessChangeItem item = mPendingProcessChanges.get(i);
10693 if (item.pid == app.pid) {
10694 mPendingProcessChanges.remove(i);
10695 mAvailProcessChanges.add(item);
10696 }
10697 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010698 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 // If the caller is restarting this app, then leave it in its
10701 // current lists and let the caller take care of it.
10702 if (restarting) {
10703 return;
10704 }
10705
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010706 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010707 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010709 mProcessNames.remove(app.processName, app.uid);
10710 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010711 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010712 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10713 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010714 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 } else if (!app.removed) {
10717 // This app is persistent, so we need to keep its record around.
10718 // If it is not already on the pending app list, add it there
10719 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010720 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10721 mPersistentStartingProcesses.add(app);
10722 restart = true;
10723 }
10724 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010725 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010726 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 mProcessesOnHold.remove(app);
10728
The Android Open Source Project4df24232009-03-05 14:34:35 -080010729 if (app == mHomeProcess) {
10730 mHomeProcess = null;
10731 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010732 if (app == mPreviousProcess) {
10733 mPreviousProcess = null;
10734 }
10735
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010736 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737 // We have components that still need to be running in the
10738 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010739 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 startProcessLocked(app, "restart", app.processName);
10741 } else if (app.pid > 0 && app.pid != MY_PID) {
10742 // Goodbye!
10743 synchronized (mPidsSelfLocked) {
10744 mPidsSelfLocked.remove(app.pid);
10745 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10746 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010747 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010748 }
10749 }
10750
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010751 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10752 // Look through the content providers we are waiting to have launched,
10753 // and if any run in this process then either schedule a restart of
10754 // the process or kill the client waiting for it if this process has
10755 // gone bad.
10756 int NL = mLaunchingProviders.size();
10757 boolean restart = false;
10758 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010759 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010760 if (cpr.launchingApp == app) {
10761 if (!alwaysBad && !app.bad) {
10762 restart = true;
10763 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010764 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010765 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010766 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010767 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010768 }
10769 }
10770 }
10771 return restart;
10772 }
10773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 // =========================================================
10775 // SERVICES
10776 // =========================================================
10777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010778 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10779 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010780 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010782 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 }
10784 }
10785
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010786 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010787 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010788 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010789 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010790 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010791 }
10792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010794 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010795 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 // Refuse possible leaked file descriptors
10797 if (service != null && service.hasFileDescriptors() == true) {
10798 throw new IllegalArgumentException("File descriptors passed in Intent");
10799 }
10800
Amith Yamasani742a6712011-05-04 14:49:28 -070010801 if (DEBUG_SERVICE)
10802 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 synchronized(this) {
10804 final int callingPid = Binder.getCallingPid();
10805 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010806 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010807 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010808 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010809 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 Binder.restoreCallingIdentity(origId);
10811 return res;
10812 }
10813 }
10814
10815 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010816 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010818 if (DEBUG_SERVICE)
10819 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010821 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010822 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 Binder.restoreCallingIdentity(origId);
10824 return res;
10825 }
10826 }
10827
10828 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010829 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010830 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 // Refuse possible leaked file descriptors
10832 if (service != null && service.hasFileDescriptors() == true) {
10833 throw new IllegalArgumentException("File descriptors passed in Intent");
10834 }
10835
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010836 checkValidCaller(Binder.getCallingUid(), userId);
10837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010839 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010841 }
10842
10843 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010844 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 // Refuse possible leaked file descriptors
10846 if (service != null && service.hasFileDescriptors() == true) {
10847 throw new IllegalArgumentException("File descriptors passed in Intent");
10848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010849 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010850 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 }
10853
10854 public boolean stopServiceToken(ComponentName className, IBinder token,
10855 int startId) {
10856 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010857 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 }
10860
10861 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010862 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010864 mServices.setServiceForegroundLocked(className, token, id, notification,
10865 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 }
10867 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010868
Dianne Hackborn41203752012-08-31 14:05:51 -070010869 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10870 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010871 final int callingUserId = UserHandle.getUserId(callingUid);
10872 if (callingUserId != userId) {
10873 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10874 if ((requireFull || checkComponentPermission(
10875 android.Manifest.permission.INTERACT_ACROSS_USERS,
10876 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10877 && checkComponentPermission(
10878 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10879 callingPid, callingUid, -1, true)
10880 != PackageManager.PERMISSION_GRANTED) {
10881 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10882 // In this case, they would like to just execute as their
10883 // owner user instead of failing.
10884 userId = callingUserId;
10885 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010886 StringBuilder builder = new StringBuilder(128);
10887 builder.append("Permission Denial: ");
10888 builder.append(name);
10889 if (callerPackage != null) {
10890 builder.append(" from ");
10891 builder.append(callerPackage);
10892 }
10893 builder.append(" asks to run as user ");
10894 builder.append(userId);
10895 builder.append(" but is calling from user ");
10896 builder.append(UserHandle.getUserId(callingUid));
10897 builder.append("; this requires ");
10898 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10899 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010900 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010901 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10902 }
10903 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010904 Slog.w(TAG, msg);
10905 throw new SecurityException(msg);
10906 }
10907 }
10908 }
10909 if (userId == UserHandle.USER_CURRENT
10910 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070010911 // Note that we may be accessing this outside of a lock...
10912 // shouldn't be a big deal, if this is being called outside
10913 // of a locked context there is intrinsically a race with
10914 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010915 userId = mCurrentUserId;
10916 }
10917 if (!allowAll && userId < 0) {
10918 throw new IllegalArgumentException(
10919 "Call does not support special user #" + userId);
10920 }
10921 }
10922 return userId;
10923 }
10924
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010925 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10926 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010927 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010928 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010929 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10930 if (ActivityManager.checkUidPermission(
10931 android.Manifest.permission.INTERACT_ACROSS_USERS,
10932 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10933 ComponentName comp = new ComponentName(aInfo.packageName, className);
10934 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10935 + " requests FLAG_SINGLE_USER, but app does not hold "
10936 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10937 Slog.w(TAG, msg);
10938 throw new SecurityException(msg);
10939 }
10940 result = true;
10941 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010942 } else if (componentProcessName == aInfo.packageName) {
10943 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10944 } else if ("system".equals(componentProcessName)) {
10945 result = true;
10946 }
10947 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010948 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10949 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010950 }
10951 return result;
10952 }
10953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 public int bindService(IApplicationThread caller, IBinder token,
10955 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010956 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010957 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 // Refuse possible leaked file descriptors
10959 if (service != null && service.hasFileDescriptors() == true) {
10960 throw new IllegalArgumentException("File descriptors passed in Intent");
10961 }
10962
10963 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010964 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10965 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 }
10967 }
10968
10969 public boolean unbindService(IServiceConnection connection) {
10970 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010971 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010973 }
10974
10975 public void publishService(IBinder token, Intent intent, IBinder service) {
10976 // Refuse possible leaked file descriptors
10977 if (intent != null && intent.hasFileDescriptors() == true) {
10978 throw new IllegalArgumentException("File descriptors passed in Intent");
10979 }
10980
10981 synchronized(this) {
10982 if (!(token instanceof ServiceRecord)) {
10983 throw new IllegalArgumentException("Invalid service token");
10984 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010985 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 }
10987 }
10988
10989 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10990 // Refuse possible leaked file descriptors
10991 if (intent != null && intent.hasFileDescriptors() == true) {
10992 throw new IllegalArgumentException("File descriptors passed in Intent");
10993 }
10994
10995 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010996 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 }
10998 }
10999
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011000 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 synchronized(this) {
11002 if (!(token instanceof ServiceRecord)) {
11003 throw new IllegalArgumentException("Invalid service token");
11004 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011005 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011007 }
11008
11009 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011010 // BACKUP AND RESTORE
11011 // =========================================================
11012
11013 // Cause the target app to be launched if necessary and its backup agent
11014 // instantiated. The backup agent will invoke backupAgentCreated() on the
11015 // activity manager to announce its creation.
11016 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011017 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11018 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011019
11020 synchronized(this) {
11021 // !!! TODO: currently no check here that we're already bound
11022 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11023 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11024 synchronized (stats) {
11025 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11026 }
11027
Dianne Hackborne7f97212011-02-24 14:40:20 -080011028 // Backup agent is now in use, its package can't be stopped.
11029 try {
11030 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011031 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011032 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011033 } catch (IllegalArgumentException e) {
11034 Slog.w(TAG, "Failed trying to unstop package "
11035 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011036 }
11037
Christopher Tate181fafa2009-05-14 11:12:14 -070011038 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011039 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11040 ? new ComponentName(app.packageName, app.backupAgentName)
11041 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011042 // startProcessLocked() returns existing proc's record if it's already running
11043 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011044 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011045 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011046 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011047 return false;
11048 }
11049
11050 r.app = proc;
11051 mBackupTarget = r;
11052 mBackupAppName = app.packageName;
11053
Christopher Tate6fa95972009-06-05 18:43:55 -070011054 // Try not to kill the process during backup
11055 updateOomAdjLocked(proc);
11056
Christopher Tate181fafa2009-05-14 11:12:14 -070011057 // If the process is already attached, schedule the creation of the backup agent now.
11058 // If it is not yet live, this will be done when it attaches to the framework.
11059 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011060 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011061 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011062 proc.thread.scheduleCreateBackupAgent(app,
11063 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011064 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011065 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011066 }
11067 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011068 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011069 }
11070 // Invariants: at this point, the target app process exists and the application
11071 // is either already running or in the process of coming up. mBackupTarget and
11072 // mBackupAppName describe the app, so that when it binds back to the AM we
11073 // know that it's scheduled for a backup-agent operation.
11074 }
11075
11076 return true;
11077 }
11078
Christopher Tate346acb12012-10-15 19:20:25 -070011079 @Override
11080 public void clearPendingBackup() {
11081 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11082 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11083
11084 synchronized (this) {
11085 mBackupTarget = null;
11086 mBackupAppName = null;
11087 }
11088 }
11089
Christopher Tate181fafa2009-05-14 11:12:14 -070011090 // A backup agent has just come up
11091 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011092 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011093 + " = " + agent);
11094
11095 synchronized(this) {
11096 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011097 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011098 return;
11099 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011100 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011101
Dianne Hackborn06740692010-09-22 22:46:21 -070011102 long oldIdent = Binder.clearCallingIdentity();
11103 try {
11104 IBackupManager bm = IBackupManager.Stub.asInterface(
11105 ServiceManager.getService(Context.BACKUP_SERVICE));
11106 bm.agentConnected(agentPackageName, agent);
11107 } catch (RemoteException e) {
11108 // can't happen; the backup manager service is local
11109 } catch (Exception e) {
11110 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11111 e.printStackTrace();
11112 } finally {
11113 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011114 }
11115 }
11116
11117 // done with this agent
11118 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011119 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011120 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011121 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011122 return;
11123 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011124
11125 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011126 try {
11127 if (mBackupAppName == null) {
11128 Slog.w(TAG, "Unbinding backup agent with no active backup");
11129 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011130 }
Christopher Tate346acb12012-10-15 19:20:25 -070011131
11132 if (!mBackupAppName.equals(appInfo.packageName)) {
11133 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11134 return;
11135 }
11136
11137 // Not backing this app up any more; reset its OOM adjustment
11138 final ProcessRecord proc = mBackupTarget.app;
11139 updateOomAdjLocked(proc);
11140
11141 // If the app crashed during backup, 'thread' will be null here
11142 if (proc.thread != null) {
11143 try {
11144 proc.thread.scheduleDestroyBackupAgent(appInfo,
11145 compatibilityInfoForPackageLocked(appInfo));
11146 } catch (Exception e) {
11147 Slog.e(TAG, "Exception when unbinding backup agent:");
11148 e.printStackTrace();
11149 }
11150 }
11151 } finally {
11152 mBackupTarget = null;
11153 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011154 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011155 }
11156 }
11157 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 // BROADCASTS
11159 // =========================================================
11160
Josh Bartel7f208742010-02-25 11:01:44 -060011161 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011162 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011164 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11165 if (stickies == null) {
11166 return cur;
11167 }
11168 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 if (list == null) {
11170 return cur;
11171 }
11172 int N = list.size();
11173 for (int i=0; i<N; i++) {
11174 Intent intent = list.get(i);
11175 if (filter.match(resolver, intent, true, TAG) >= 0) {
11176 if (cur == null) {
11177 cur = new ArrayList<Intent>();
11178 }
11179 cur.add(intent);
11180 }
11181 }
11182 return cur;
11183 }
11184
Christopher Tatef46723b2012-01-26 14:19:24 -080011185 boolean isPendingBroadcastProcessLocked(int pid) {
11186 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11187 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189
Christopher Tatef46723b2012-01-26 14:19:24 -080011190 void skipPendingBroadcastLocked(int pid) {
11191 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11192 for (BroadcastQueue queue : mBroadcastQueues) {
11193 queue.skipPendingBroadcastLocked(pid);
11194 }
11195 }
11196
11197 // The app just attached; send any pending broadcasts that it should receive
11198 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11199 boolean didSomething = false;
11200 for (BroadcastQueue queue : mBroadcastQueues) {
11201 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011203 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 }
11205
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011206 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011207 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011208 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011209 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011210 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 synchronized(this) {
11212 ProcessRecord callerApp = null;
11213 if (caller != null) {
11214 callerApp = getRecordForAppLocked(caller);
11215 if (callerApp == null) {
11216 throw new SecurityException(
11217 "Unable to find app for caller " + caller
11218 + " (pid=" + Binder.getCallingPid()
11219 + ") when registering receiver " + receiver);
11220 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011221 if (callerApp.info.uid != Process.SYSTEM_UID &&
11222 !callerApp.pkgList.contains(callerPackage)) {
11223 throw new SecurityException("Given caller package " + callerPackage
11224 + " is not running in process " + callerApp);
11225 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011226 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011227 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011228 } else {
11229 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011230 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011231 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 }
11233
Dianne Hackborn139748f2012-09-24 11:36:57 -070011234 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011235 true, true, "registerReceiver", callerPackage);
11236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 List allSticky = null;
11238
11239 // Look for any matching sticky broadcasts...
11240 Iterator actions = filter.actionsIterator();
11241 if (actions != null) {
11242 while (actions.hasNext()) {
11243 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011244 allSticky = getStickiesLocked(action, filter, allSticky,
11245 UserHandle.USER_ALL);
11246 allSticky = getStickiesLocked(action, filter, allSticky,
11247 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 }
11249 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011250 allSticky = getStickiesLocked(null, filter, allSticky,
11251 UserHandle.USER_ALL);
11252 allSticky = getStickiesLocked(null, filter, allSticky,
11253 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 }
11255
11256 // The first sticky in the list is returned directly back to
11257 // the client.
11258 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11259
Joe Onorato8a9b2202010-02-26 18:56:32 -080011260 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 + ": " + sticky);
11262
11263 if (receiver == null) {
11264 return sticky;
11265 }
11266
11267 ReceiverList rl
11268 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11269 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011270 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11271 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 if (rl.app != null) {
11273 rl.app.receivers.add(rl);
11274 } else {
11275 try {
11276 receiver.asBinder().linkToDeath(rl, 0);
11277 } catch (RemoteException e) {
11278 return sticky;
11279 }
11280 rl.linkedToDeath = true;
11281 }
11282 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011283 } else if (rl.uid != callingUid) {
11284 throw new IllegalArgumentException(
11285 "Receiver requested to register for uid " + callingUid
11286 + " was previously registered for uid " + rl.uid);
11287 } else if (rl.pid != callingPid) {
11288 throw new IllegalArgumentException(
11289 "Receiver requested to register for pid " + callingPid
11290 + " was previously registered for pid " + rl.pid);
11291 } else if (rl.userId != userId) {
11292 throw new IllegalArgumentException(
11293 "Receiver requested to register for user " + userId
11294 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011296 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011297 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 rl.add(bf);
11299 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011300 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 }
11302 mReceiverResolver.addFilter(bf);
11303
11304 // Enqueue broadcasts for all existing stickies that match
11305 // this filter.
11306 if (allSticky != null) {
11307 ArrayList receivers = new ArrayList();
11308 receivers.add(bf);
11309
11310 int N = allSticky.size();
11311 for (int i=0; i<N; i++) {
11312 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011313 BroadcastQueue queue = broadcastQueueForIntent(intent);
11314 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011315 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11316 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011317 queue.enqueueParallelBroadcastLocked(r);
11318 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 }
11320 }
11321
11322 return sticky;
11323 }
11324 }
11325
11326 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011327 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328
Christopher Tatef46723b2012-01-26 14:19:24 -080011329 final long origId = Binder.clearCallingIdentity();
11330 try {
11331 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332
Christopher Tatef46723b2012-01-26 14:19:24 -080011333 synchronized(this) {
11334 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011335 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011336 if (rl != null) {
11337 if (rl.curBroadcast != null) {
11338 BroadcastRecord r = rl.curBroadcast;
11339 final boolean doNext = finishReceiverLocked(
11340 receiver.asBinder(), r.resultCode, r.resultData,
11341 r.resultExtras, r.resultAbort, true);
11342 if (doNext) {
11343 doTrim = true;
11344 r.queue.processNextBroadcast(false);
11345 }
11346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011347
Christopher Tatef46723b2012-01-26 14:19:24 -080011348 if (rl.app != null) {
11349 rl.app.receivers.remove(rl);
11350 }
11351 removeReceiverLocked(rl);
11352 if (rl.linkedToDeath) {
11353 rl.linkedToDeath = false;
11354 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 }
11357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358
Christopher Tatef46723b2012-01-26 14:19:24 -080011359 // If we actually concluded any broadcasts, we might now be able
11360 // to trim the recipients' apps from our working set
11361 if (doTrim) {
11362 trimApplications();
11363 return;
11364 }
11365
11366 } finally {
11367 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 }
11370
11371 void removeReceiverLocked(ReceiverList rl) {
11372 mRegisteredReceivers.remove(rl.receiver.asBinder());
11373 int N = rl.size();
11374 for (int i=0; i<N; i++) {
11375 mReceiverResolver.removeFilter(rl.get(i));
11376 }
11377 }
11378
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011379 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011380 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11381 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011382 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011383 try {
11384 r.thread.dispatchPackageBroadcast(cmd, packages);
11385 } catch (RemoteException ex) {
11386 }
11387 }
11388 }
11389 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011390
11391 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11392 int[] users) {
11393 List<ResolveInfo> receivers = null;
11394 try {
11395 HashSet<ComponentName> singleUserReceivers = null;
11396 boolean scannedFirstReceivers = false;
11397 for (int user : users) {
11398 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11399 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011400 if (user != 0 && newReceivers != null) {
11401 // If this is not the primary user, we need to check for
11402 // any receivers that should be filtered out.
11403 for (int i=0; i<newReceivers.size(); i++) {
11404 ResolveInfo ri = newReceivers.get(i);
11405 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11406 newReceivers.remove(i);
11407 i--;
11408 }
11409 }
11410 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011411 if (newReceivers != null && newReceivers.size() == 0) {
11412 newReceivers = null;
11413 }
11414 if (receivers == null) {
11415 receivers = newReceivers;
11416 } else if (newReceivers != null) {
11417 // We need to concatenate the additional receivers
11418 // found with what we have do far. This would be easy,
11419 // but we also need to de-dup any receivers that are
11420 // singleUser.
11421 if (!scannedFirstReceivers) {
11422 // Collect any single user receivers we had already retrieved.
11423 scannedFirstReceivers = true;
11424 for (int i=0; i<receivers.size(); i++) {
11425 ResolveInfo ri = receivers.get(i);
11426 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11427 ComponentName cn = new ComponentName(
11428 ri.activityInfo.packageName, ri.activityInfo.name);
11429 if (singleUserReceivers == null) {
11430 singleUserReceivers = new HashSet<ComponentName>();
11431 }
11432 singleUserReceivers.add(cn);
11433 }
11434 }
11435 }
11436 // Add the new results to the existing results, tracking
11437 // and de-dupping single user receivers.
11438 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011439 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011440 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11441 ComponentName cn = new ComponentName(
11442 ri.activityInfo.packageName, ri.activityInfo.name);
11443 if (singleUserReceivers == null) {
11444 singleUserReceivers = new HashSet<ComponentName>();
11445 }
11446 if (!singleUserReceivers.contains(cn)) {
11447 singleUserReceivers.add(cn);
11448 receivers.add(ri);
11449 }
11450 } else {
11451 receivers.add(ri);
11452 }
11453 }
11454 }
11455 }
11456 } catch (RemoteException ex) {
11457 // pm is in same process, this will never happen.
11458 }
11459 return receivers;
11460 }
11461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 private final int broadcastIntentLocked(ProcessRecord callerApp,
11463 String callerPackage, Intent intent, String resolvedType,
11464 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011465 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011466 boolean ordered, boolean sticky, int callingPid, int callingUid,
11467 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011468 intent = new Intent(intent);
11469
Dianne Hackborne7f97212011-02-24 14:40:20 -080011470 // By default broadcasts do not go to stopped apps.
11471 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11472
Joe Onorato8a9b2202010-02-26 18:56:32 -080011473 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011475 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011477 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011479
Dianne Hackborn139748f2012-09-24 11:36:57 -070011480 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011481 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011482
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011483 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011484 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011485 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011486 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11487 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11488 Slog.w(TAG, "Skipping broadcast of " + intent
11489 + ": user " + userId + " is stopped");
11490 return ActivityManager.BROADCAST_SUCCESS;
11491 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011492 }
11493
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011494 /*
11495 * Prevent non-system code (defined here to be non-persistent
11496 * processes) from sending protected broadcasts.
11497 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011498 int callingAppId = UserHandle.getAppId(callingUid);
11499 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11500 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011501 callingUid == 0) {
11502 // Always okay.
11503 } else if (callerApp == null || !callerApp.persistent) {
11504 try {
11505 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11506 intent.getAction())) {
11507 String msg = "Permission Denial: not allowed to send broadcast "
11508 + intent.getAction() + " from pid="
11509 + callingPid + ", uid=" + callingUid;
11510 Slog.w(TAG, msg);
11511 throw new SecurityException(msg);
11512 }
11513 } catch (RemoteException e) {
11514 Slog.w(TAG, "Remote exception", e);
11515 return ActivityManager.BROADCAST_SUCCESS;
11516 }
11517 }
11518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 // Handle special intents: if this broadcast is from the package
11520 // manager about a package being removed, we need to remove all of
11521 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011522 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011524 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11525 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011526 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 || uidRemoved) {
11528 if (checkComponentPermission(
11529 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011530 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 == PackageManager.PERMISSION_GRANTED) {
11532 if (uidRemoved) {
11533 final Bundle intentExtras = intent.getExtras();
11534 final int uid = intentExtras != null
11535 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11536 if (uid >= 0) {
11537 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11538 synchronized (bs) {
11539 bs.removeUidStatsLocked(uid);
11540 }
Dianne Hackborn514074f2013-02-11 10:52:46 -080011541 mAppOpsService.uidRemoved(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 }
11543 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011544 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011545 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011546 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011547 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11548 if (list != null && (list.length > 0)) {
11549 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011550 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011551 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011552 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011553 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011554 }
11555 } else {
11556 Uri data = intent.getData();
11557 String ssp;
11558 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11559 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11560 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011561 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11562 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011563 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011564 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011565 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011566 new String[] {ssp}, userId);
Dianne Hackborn514074f2013-02-11 10:52:46 -080011567 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
11568 mAppOpsService.packageRemoved(
11569 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
11570 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011572 }
11573 }
11574 }
11575 } else {
11576 String msg = "Permission Denial: " + intent.getAction()
11577 + " broadcast from " + callerPackage + " (pid=" + callingPid
11578 + ", uid=" + callingUid + ")"
11579 + " requires "
11580 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011581 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011582 throw new SecurityException(msg);
11583 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011584
11585 // Special case for adding a package: by default turn on compatibility
11586 // mode.
11587 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011588 Uri data = intent.getData();
11589 String ssp;
11590 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11591 mCompatModePackages.handlePackageAddedLocked(ssp,
11592 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 }
11595
11596 /*
11597 * If this is the time zone changed action, queue up a message that will reset the timezone
11598 * of all currently running processes. This message will get queued up before the broadcast
11599 * happens.
11600 */
11601 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11602 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11603 }
11604
Robert Greenwalt03595d02010-11-02 14:08:23 -070011605 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11606 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11607 }
11608
Robert Greenwalt434203a2010-10-11 16:00:27 -070011609 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11610 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11611 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11612 }
11613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 // Add to the sticky list if requested.
11615 if (sticky) {
11616 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11617 callingPid, callingUid)
11618 != PackageManager.PERMISSION_GRANTED) {
11619 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11620 + callingPid + ", uid=" + callingUid
11621 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011622 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 throw new SecurityException(msg);
11624 }
11625 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011628 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 }
11630 if (intent.getComponent() != null) {
11631 throw new SecurityException(
11632 "Sticky broadcasts can't target a specific component");
11633 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011634 // We use userId directly here, since the "all" target is maintained
11635 // as a separate set of sticky broadcasts.
11636 if (userId != UserHandle.USER_ALL) {
11637 // But first, if this is not a broadcast to all users, then
11638 // make sure it doesn't conflict with an existing broadcast to
11639 // all users.
11640 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11641 UserHandle.USER_ALL);
11642 if (stickies != null) {
11643 ArrayList<Intent> list = stickies.get(intent.getAction());
11644 if (list != null) {
11645 int N = list.size();
11646 int i;
11647 for (i=0; i<N; i++) {
11648 if (intent.filterEquals(list.get(i))) {
11649 throw new IllegalArgumentException(
11650 "Sticky broadcast " + intent + " for user "
11651 + userId + " conflicts with existing global broadcast");
11652 }
11653 }
11654 }
11655 }
11656 }
11657 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11658 if (stickies == null) {
11659 stickies = new HashMap<String, ArrayList<Intent>>();
11660 mStickyBroadcasts.put(userId, stickies);
11661 }
11662 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011663 if (list == null) {
11664 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011665 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 }
11667 int N = list.size();
11668 int i;
11669 for (i=0; i<N; i++) {
11670 if (intent.filterEquals(list.get(i))) {
11671 // This sticky already exists, replace it.
11672 list.set(i, new Intent(intent));
11673 break;
11674 }
11675 }
11676 if (i >= N) {
11677 list.add(new Intent(intent));
11678 }
11679 }
11680
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011681 int[] users;
11682 if (userId == UserHandle.USER_ALL) {
11683 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011684 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011685 } else {
11686 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011687 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011688 }
11689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011690 // Figure out who all will receive this broadcast.
11691 List receivers = null;
11692 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011693 // Need to resolve the intent to interested receivers...
11694 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11695 == 0) {
11696 receivers = collectReceiverComponents(intent, resolvedType, users);
11697 }
11698 if (intent.getComponent() == null) {
11699 registeredReceivers = mReceiverResolver.queryIntent(intent,
11700 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701 }
11702
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011703 final boolean replacePending =
11704 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11705
Joe Onorato8a9b2202010-02-26 18:56:32 -080011706 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011707 + " replacePending=" + replacePending);
11708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11710 if (!ordered && NR > 0) {
11711 // If we are not serializing this broadcast, then send the
11712 // registered receivers separately so they don't wait for the
11713 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011714 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11715 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011716 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011718 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011719 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011720 TAG, "Enqueueing parallel broadcast " + r);
11721 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011722 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011723 queue.enqueueParallelBroadcastLocked(r);
11724 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 registeredReceivers = null;
11727 NR = 0;
11728 }
11729
11730 // Merge into one list.
11731 int ir = 0;
11732 if (receivers != null) {
11733 // A special case for PACKAGE_ADDED: do not allow the package
11734 // being added to see this broadcast. This prevents them from
11735 // using this as a back door to get run as soon as they are
11736 // installed. Maybe in the future we want to have a special install
11737 // broadcast or such for apps, but we'd like to deliberately make
11738 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011739 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011740 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11741 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11742 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011743 Uri data = intent.getData();
11744 if (data != null) {
11745 String pkgName = data.getSchemeSpecificPart();
11746 if (pkgName != null) {
11747 skipPackages = new String[] { pkgName };
11748 }
11749 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011750 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011751 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011752 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011753 if (skipPackages != null && (skipPackages.length > 0)) {
11754 for (String skipPackage : skipPackages) {
11755 if (skipPackage != null) {
11756 int NT = receivers.size();
11757 for (int it=0; it<NT; it++) {
11758 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11759 if (curt.activityInfo.packageName.equals(skipPackage)) {
11760 receivers.remove(it);
11761 it--;
11762 NT--;
11763 }
11764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 }
11766 }
11767 }
11768
11769 int NT = receivers != null ? receivers.size() : 0;
11770 int it = 0;
11771 ResolveInfo curt = null;
11772 BroadcastFilter curr = null;
11773 while (it < NT && ir < NR) {
11774 if (curt == null) {
11775 curt = (ResolveInfo)receivers.get(it);
11776 }
11777 if (curr == null) {
11778 curr = registeredReceivers.get(ir);
11779 }
11780 if (curr.getPriority() >= curt.priority) {
11781 // Insert this broadcast record into the final list.
11782 receivers.add(it, curr);
11783 ir++;
11784 curr = null;
11785 it++;
11786 NT++;
11787 } else {
11788 // Skip to the next ResolveInfo in the final list.
11789 it++;
11790 curt = null;
11791 }
11792 }
11793 }
11794 while (ir < NR) {
11795 if (receivers == null) {
11796 receivers = new ArrayList();
11797 }
11798 receivers.add(registeredReceivers.get(ir));
11799 ir++;
11800 }
11801
11802 if ((receivers != null && receivers.size() > 0)
11803 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011804 BroadcastQueue queue = broadcastQueueForIntent(intent);
11805 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011806 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011807 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011808 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011809 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011811 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 if (DEBUG_BROADCAST) {
11813 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011814 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011816 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011817 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011818 queue.enqueueOrderedBroadcastLocked(r);
11819 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 }
11822
Dianne Hackborna4972e92012-03-14 10:38:05 -070011823 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 }
11825
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011826 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 // Refuse possible leaked file descriptors
11828 if (intent != null && intent.hasFileDescriptors() == true) {
11829 throw new IllegalArgumentException("File descriptors passed in Intent");
11830 }
11831
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011832 int flags = intent.getFlags();
11833
11834 if (!mProcessesReady) {
11835 // if the caller really truly claims to know what they're doing, go
11836 // ahead and allow the broadcast without launching any receivers
11837 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11838 intent = new Intent(intent);
11839 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11840 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11841 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11842 + " before boot completion");
11843 throw new IllegalStateException("Cannot broadcast before boot completed");
11844 }
11845 }
11846
11847 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11848 throw new IllegalArgumentException(
11849 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11850 }
11851
11852 return intent;
11853 }
11854
11855 public final int broadcastIntent(IApplicationThread caller,
11856 Intent intent, String resolvedType, IIntentReceiver resultTo,
11857 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011858 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011859 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011861 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11864 final int callingPid = Binder.getCallingPid();
11865 final int callingUid = Binder.getCallingUid();
11866 final long origId = Binder.clearCallingIdentity();
11867 int res = broadcastIntentLocked(callerApp,
11868 callerApp != null ? callerApp.info.packageName : null,
11869 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011870 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070011871 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011872 Binder.restoreCallingIdentity(origId);
11873 return res;
11874 }
11875 }
11876
11877 int broadcastIntentInPackage(String packageName, int uid,
11878 Intent intent, String resolvedType, IIntentReceiver resultTo,
11879 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011880 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011882 intent = verifyBroadcastLocked(intent);
11883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 final long origId = Binder.clearCallingIdentity();
11885 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11886 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011887 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 Binder.restoreCallingIdentity(origId);
11889 return res;
11890 }
11891 }
11892
Amith Yamasani742a6712011-05-04 14:49:28 -070011893 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 // Refuse possible leaked file descriptors
11895 if (intent != null && intent.hasFileDescriptors() == true) {
11896 throw new IllegalArgumentException("File descriptors passed in Intent");
11897 }
11898
Dianne Hackborn139748f2012-09-24 11:36:57 -070011899 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011900 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011902 synchronized(this) {
11903 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11904 != PackageManager.PERMISSION_GRANTED) {
11905 String msg = "Permission Denial: unbroadcastIntent() from pid="
11906 + Binder.getCallingPid()
11907 + ", uid=" + Binder.getCallingUid()
11908 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011909 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011910 throw new SecurityException(msg);
11911 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011912 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11913 if (stickies != null) {
11914 ArrayList<Intent> list = stickies.get(intent.getAction());
11915 if (list != null) {
11916 int N = list.size();
11917 int i;
11918 for (i=0; i<N; i++) {
11919 if (intent.filterEquals(list.get(i))) {
11920 list.remove(i);
11921 break;
11922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011924 if (list.size() <= 0) {
11925 stickies.remove(intent.getAction());
11926 }
11927 }
11928 if (stickies.size() <= 0) {
11929 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930 }
11931 }
11932 }
11933 }
11934
11935 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11936 String resultData, Bundle resultExtras, boolean resultAbort,
11937 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011938 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11939 if (r == null) {
11940 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 return false;
11942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943
Christopher Tatef46723b2012-01-26 14:19:24 -080011944 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11945 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011946 }
11947
11948 public void finishReceiver(IBinder who, int resultCode, String resultData,
11949 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011950 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951
11952 // Refuse possible leaked file descriptors
11953 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11954 throw new IllegalArgumentException("File descriptors passed in Bundle");
11955 }
11956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011958 try {
11959 boolean doNext = false;
11960 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961
Christopher Tatef46723b2012-01-26 14:19:24 -080011962 synchronized(this) {
11963 r = broadcastRecordForReceiverLocked(who);
11964 if (r != null) {
11965 doNext = r.queue.finishReceiverLocked(r, resultCode,
11966 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011968 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011969
Christopher Tatef46723b2012-01-26 14:19:24 -080011970 if (doNext) {
11971 r.queue.processNextBroadcast(false);
11972 }
11973 trimApplications();
11974 } finally {
11975 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 // =========================================================
11980 // INSTRUMENTATION
11981 // =========================================================
11982
11983 public boolean startInstrumentation(ComponentName className,
11984 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080011985 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
11986 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011987 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070011988 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011989 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011990 // Refuse possible leaked file descriptors
11991 if (arguments != null && arguments.hasFileDescriptors()) {
11992 throw new IllegalArgumentException("File descriptors passed in Bundle");
11993 }
11994
11995 synchronized(this) {
11996 InstrumentationInfo ii = null;
11997 ApplicationInfo ai = null;
11998 try {
11999 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012000 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012001 ai = AppGlobals.getPackageManager().getApplicationInfo(
12002 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012004 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012005 }
12006 if (ii == null) {
12007 reportStartInstrumentationFailure(watcher, className,
12008 "Unable to find instrumentation info for: " + className);
12009 return false;
12010 }
12011 if (ai == null) {
12012 reportStartInstrumentationFailure(watcher, className,
12013 "Unable to find instrumentation target package: " + ii.targetPackage);
12014 return false;
12015 }
12016
12017 int match = mContext.getPackageManager().checkSignatures(
12018 ii.targetPackage, ii.packageName);
12019 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12020 String msg = "Permission Denial: starting instrumentation "
12021 + className + " from pid="
12022 + Binder.getCallingPid()
12023 + ", uid=" + Binder.getCallingPid()
12024 + " not allowed because package " + ii.packageName
12025 + " does not have a signature matching the target "
12026 + ii.targetPackage;
12027 reportStartInstrumentationFailure(watcher, className, msg);
12028 throw new SecurityException(msg);
12029 }
12030
12031 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012032 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012033 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012034 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012036 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 app.instrumentationProfileFile = profileFile;
12038 app.instrumentationArguments = arguments;
12039 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012040 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012041 app.instrumentationResultClass = className;
12042 Binder.restoreCallingIdentity(origId);
12043 }
12044
12045 return true;
12046 }
12047
12048 /**
12049 * Report errors that occur while attempting to start Instrumentation. Always writes the
12050 * error to the logs, but if somebody is watching, send the report there too. This enables
12051 * the "am" command to report errors with more information.
12052 *
12053 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12054 * @param cn The component name of the instrumentation.
12055 * @param report The error report.
12056 */
12057 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12058 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012059 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 try {
12061 if (watcher != null) {
12062 Bundle results = new Bundle();
12063 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12064 results.putString("Error", report);
12065 watcher.instrumentationStatus(cn, -1, results);
12066 }
12067 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012068 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 }
12070 }
12071
12072 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12073 if (app.instrumentationWatcher != null) {
12074 try {
12075 // NOTE: IInstrumentationWatcher *must* be oneway here
12076 app.instrumentationWatcher.instrumentationFinished(
12077 app.instrumentationClass,
12078 resultCode,
12079 results);
12080 } catch (RemoteException e) {
12081 }
12082 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012083 if (app.instrumentationUiAutomationConnection != null) {
12084 try {
12085 app.instrumentationUiAutomationConnection.shutdown();
12086 } catch (RemoteException re) {
12087 /* ignore */
12088 }
12089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012091 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012093 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012094 app.instrumentationProfileFile = null;
12095 app.instrumentationArguments = null;
12096
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012097 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098 }
12099
12100 public void finishInstrumentation(IApplicationThread target,
12101 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012102 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 // Refuse possible leaked file descriptors
12104 if (results != null && results.hasFileDescriptors()) {
12105 throw new IllegalArgumentException("File descriptors passed in Intent");
12106 }
12107
12108 synchronized(this) {
12109 ProcessRecord app = getRecordForAppLocked(target);
12110 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012111 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 return;
12113 }
12114 final long origId = Binder.clearCallingIdentity();
12115 finishInstrumentationLocked(app, resultCode, results);
12116 Binder.restoreCallingIdentity(origId);
12117 }
12118 }
12119
12120 // =========================================================
12121 // CONFIGURATION
12122 // =========================================================
12123
12124 public ConfigurationInfo getDeviceConfigurationInfo() {
12125 ConfigurationInfo config = new ConfigurationInfo();
12126 synchronized (this) {
12127 config.reqTouchScreen = mConfiguration.touchscreen;
12128 config.reqKeyboardType = mConfiguration.keyboard;
12129 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012130 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12131 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12133 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012134 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12135 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12137 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012138 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 }
12140 return config;
12141 }
12142
12143 public Configuration getConfiguration() {
12144 Configuration ci;
12145 synchronized(this) {
12146 ci = new Configuration(mConfiguration);
12147 }
12148 return ci;
12149 }
12150
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012151 public void updatePersistentConfiguration(Configuration values) {
12152 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12153 "updateConfiguration()");
12154 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12155 "updateConfiguration()");
12156 if (values == null) {
12157 throw new NullPointerException("Configuration must not be null");
12158 }
12159
12160 synchronized(this) {
12161 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012162 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012163 Binder.restoreCallingIdentity(origId);
12164 }
12165 }
12166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167 public void updateConfiguration(Configuration values) {
12168 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12169 "updateConfiguration()");
12170
12171 synchronized(this) {
12172 if (values == null && mWindowManager != null) {
12173 // sentinel: fetch the current configuration from the window manager
12174 values = mWindowManager.computeNewConfiguration();
12175 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012176
12177 if (mWindowManager != null) {
12178 mProcessList.applyDisplaySize(mWindowManager);
12179 }
12180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012182 if (values != null) {
12183 Settings.System.clearConfiguration(values);
12184 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012185 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012186 Binder.restoreCallingIdentity(origId);
12187 }
12188 }
12189
12190 /**
12191 * Do either or both things: (1) change the current configuration, and (2)
12192 * make sure the given activity is running with the (now) current
12193 * configuration. Returns true if the activity has been left running, or
12194 * false if <var>starting</var> is being destroyed to match the new
12195 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012196 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012198 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012199 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012200 // do nothing if we are headless
12201 if (mHeadless) return true;
12202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203 int changes = 0;
12204
12205 boolean kept = true;
12206
12207 if (values != null) {
12208 Configuration newConfig = new Configuration(mConfiguration);
12209 changes = newConfig.updateFrom(values);
12210 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012211 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012213 }
12214
Doug Zongker2bec3d42009-12-04 12:52:44 -080012215 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216
Dianne Hackborn813075a62011-11-14 17:45:19 -080012217 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012218 saveLocaleLocked(values.locale,
12219 !values.locale.equals(mConfiguration.locale),
12220 values.userSetLocale);
12221 }
12222
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012223 mConfigurationSeq++;
12224 if (mConfigurationSeq <= 0) {
12225 mConfigurationSeq = 1;
12226 }
12227 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012229 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012230
12231 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012232
12233 // TODO: If our config changes, should we auto dismiss any currently
12234 // showing dialogs?
12235 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012236
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012237 AttributeCache ac = AttributeCache.instance();
12238 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012239 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012242 // Make sure all resources in our process are updated
12243 // right now, so that anyone who is going to retrieve
12244 // resource values after we return will be sure to get
12245 // the new ones. This is especially important during
12246 // boot, where the first config change needs to guarantee
12247 // all resources have that config before following boot
12248 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012249 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012250
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012251 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012252 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012253 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012254 mHandler.sendMessage(msg);
12255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012257 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12258 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012259 try {
12260 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012261 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012262 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012263 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012264 }
12265 } catch (Exception e) {
12266 }
12267 }
12268 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012269 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012270 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12271 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012272 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012273 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12274 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012275 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012276 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12277 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12278 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012279 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12280 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012282 }
12283 }
12284
12285 if (changes != 0 && starting == null) {
12286 // If the configuration changed, and the caller is not already
12287 // in the process of starting an activity, then find the top
12288 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012289 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 }
12291
12292 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012293 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012294 // And we need to make sure at this point that all other activities
12295 // are made visible with the correct configuration.
12296 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012297 }
12298
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012299 if (values != null && mWindowManager != null) {
12300 mWindowManager.setNewConfiguration(mConfiguration);
12301 }
12302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303 return kept;
12304 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012305
12306 /**
12307 * Decide based on the configuration whether we should shouw the ANR,
12308 * crash, etc dialogs. The idea is that if there is no affordnace to
12309 * press the on-screen buttons, we shouldn't show the dialog.
12310 *
12311 * A thought: SystemUI might also want to get told about this, the Power
12312 * dialog / global actions also might want different behaviors.
12313 */
12314 private static final boolean shouldShowDialogs(Configuration config) {
12315 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12316 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318
12319 /**
12320 * Save the locale. You must be inside a synchronized (this) block.
12321 */
12322 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12323 if(isDiff) {
12324 SystemProperties.set("user.language", l.getLanguage());
12325 SystemProperties.set("user.region", l.getCountry());
12326 }
12327
12328 if(isPersist) {
12329 SystemProperties.set("persist.sys.language", l.getLanguage());
12330 SystemProperties.set("persist.sys.country", l.getCountry());
12331 SystemProperties.set("persist.sys.localevar", l.getVariant());
12332 }
12333 }
12334
Adam Powelldd8fab22012-03-22 17:47:27 -070012335 @Override
12336 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12337 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012338 return srec != null && srec.task.affinity != null &&
12339 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012340 }
12341
12342 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12343 Intent resultData) {
Adam Powelldd8fab22012-03-22 17:47:27 -070012344
12345 synchronized (this) {
12346 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012347 if (srec == null) {
12348 return false;
12349 }
Craig Mautnercae015f2013-02-08 14:31:27 -080012350 ActivityStack stack = srec.stack;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080012351 return stack.navigateUpToLocked(srec, destIntent, resultCode, resultData);
Adam Powelldd8fab22012-03-22 17:47:27 -070012352 }
12353 }
12354
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012355 public int getLaunchedFromUid(IBinder activityToken) {
12356 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12357 if (srec == null) {
12358 return -1;
12359 }
12360 return srec.launchedFromUid;
12361 }
12362
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012363 public String getLaunchedFromPackage(IBinder activityToken) {
12364 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12365 if (srec == null) {
12366 return null;
12367 }
12368 return srec.launchedFromPackage;
12369 }
12370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 // =========================================================
12372 // LIFETIME MANAGEMENT
12373 // =========================================================
12374
Christopher Tatef46723b2012-01-26 14:19:24 -080012375 // Returns which broadcast queue the app is the current [or imminent] receiver
12376 // on, or 'null' if the app is not an active broadcast recipient.
12377 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12378 BroadcastRecord r = app.curReceiver;
12379 if (r != null) {
12380 return r.queue;
12381 }
12382
12383 // It's not the current receiver, but it might be starting up to become one
12384 synchronized (this) {
12385 for (BroadcastQueue queue : mBroadcastQueues) {
12386 r = queue.mPendingBroadcast;
12387 if (r != null && r.curApp == app) {
12388 // found it; report which queue it's in
12389 return queue;
12390 }
12391 }
12392 }
12393
12394 return null;
12395 }
12396
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012397 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012398 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012400 // This adjustment has already been computed. If we are calling
12401 // from the top, we may have already computed our adjustment with
12402 // an earlier hidden adjustment that isn't really for us... if
12403 // so, use the new hidden adjustment.
12404 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012405 if (app.hasActivities) {
12406 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12407 } else if (app.hasClientActivities) {
12408 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12409 } else {
12410 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12411 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012412 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012413 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 }
12415
12416 if (app.thread == null) {
12417 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012418 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012419 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012420 }
12421
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012422 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12423 app.adjSource = null;
12424 app.adjTarget = null;
12425 app.empty = false;
12426 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012427 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012428
12429 final int activitiesSize = app.activities.size();
12430
Dianne Hackborn7d608422011-08-07 16:24:18 -070012431 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012432 // The max adjustment doesn't allow this app to be anything
12433 // below foreground, so it is not worth doing work for it.
12434 app.adjType = "fixed";
12435 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012436 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012437 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012438 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012439 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012440 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012441 // System process can do UI, and when they do we want to have
12442 // them trim their memory after the user leaves the UI. To
12443 // facilitate this, here we need to determine whether or not it
12444 // is currently showing UI.
12445 app.systemNoUi = true;
12446 if (app == TOP_APP) {
12447 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012448 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012449 } else if (activitiesSize > 0) {
12450 for (int j = 0; j < activitiesSize; j++) {
12451 final ActivityRecord r = app.activities.get(j);
12452 if (r.visible) {
12453 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012454 }
12455 if (r.app == app) {
12456 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012457 }
12458 }
12459 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012460 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012461 }
12462
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012463 app.keeping = false;
12464 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012465 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466
The Android Open Source Project4df24232009-03-05 14:34:35 -080012467 // Determine the importance of the process, starting with most
12468 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012470 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012471 boolean foregroundActivities = false;
12472 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012473 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012474 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012476 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012477 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012478 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012479 foregroundActivities = true;
12480 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012481 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012482 } else if (app.instrumentationClass != null) {
12483 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012484 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012485 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012486 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012487 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012488 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012490 // counts as being in the foreground for OOM killer purposes.
12491 // It's placed in a sched group based on the nature of the
12492 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012493 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012494 schedGroup = (queue == mFgBroadcastQueue)
12495 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012496 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012497 } else if (app.executingServices.size() > 0) {
12498 // An app that is currently executing a service callback also
12499 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012500 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012501 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012502 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012503 } else {
12504 // Assume process is hidden (has activities); we will correct
12505 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012507 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012508 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012509 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012511
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012512 boolean hasStoppingActivities = false;
12513
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012514 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012515 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012516 for (int j = 0; j < activitiesSize; j++) {
12517 final ActivityRecord r = app.activities.get(j);
12518 if (r.visible) {
12519 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012520 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12521 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012522 app.adjType = "visible";
12523 }
12524 schedGroup = Process.THREAD_GROUP_DEFAULT;
12525 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012526 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012527 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012528 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012529 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012530 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12531 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012532 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012533 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012534 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012535 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012536 } else if (r.state == ActivityState.STOPPING) {
12537 // We will apply the actual adjustment later, because
12538 // we want to allow this process to immediately go through
12539 // any memory trimming that is in effect.
12540 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012541 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012542 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012543 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012544 if (r.app == app) {
12545 app.hasActivities = true;
12546 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012547 }
12548 }
12549
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012550 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012551 if (app.hasClientActivities) {
12552 adj = clientHiddenAdj;
12553 app.adjType = "bg-client-act";
12554 } else {
12555 // Whoops, this process is completely empty as far as we know
12556 // at this point.
12557 adj = emptyAdj;
12558 app.empty = true;
12559 app.adjType = "bg-empty";
12560 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012561 }
12562
Dianne Hackborn7d608422011-08-07 16:24:18 -070012563 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012564 if (app.foregroundServices) {
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 = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012569 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012570 } else if (app.forcingToForeground != null) {
12571 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012572 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012573 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012574 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012575 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012576 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012577 }
12578 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012579
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012580 if (app.foregroundServices) {
12581 interesting = true;
12582 }
12583
Dianne Hackborn7d608422011-08-07 16:24:18 -070012584 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012585 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012586 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012587 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012588 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012589 app.adjType = "heavy";
12590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591
Dianne Hackborn7d608422011-08-07 16:24:18 -070012592 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012593 // This process is hosting what we currently consider to be the
12594 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012595 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012596 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012597 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012598 app.adjType = "home";
12599 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012600
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012601 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12602 && app.activities.size() > 0) {
12603 // This was the previous process that showed UI to the user.
12604 // We want to try to keep it around more aggressively, to give
12605 // a good experience around switching between two apps.
12606 adj = ProcessList.PREVIOUS_APP_ADJ;
12607 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12608 app.hidden = false;
12609 app.adjType = "previous";
12610 }
12611
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012612 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12613 + " reason=" + app.adjType);
12614
The Android Open Source Project4df24232009-03-05 14:34:35 -080012615 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 // there are applications dependent on our services or providers, but
12617 // this gives us a baseline and makes sure we don't get into an
12618 // infinite recursion.
12619 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012620 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621
Christopher Tate6fa95972009-06-05 18:43:55 -070012622 if (mBackupTarget != null && app == mBackupTarget.app) {
12623 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012624 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012625 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012627 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012628 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012629 }
12630 }
12631
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012633 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012634 final long now = SystemClock.uptimeMillis();
12635 // This process is more important if the top activity is
12636 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012637 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012638 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012639 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012641 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012642 // If this process has shown some UI, let it immediately
12643 // go to the LRU list because it may be pretty heavy with
12644 // UI stuff. We'll tag it with a label just to help
12645 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012646 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012647 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012649 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012650 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012651 // This service has seen some activity within
12652 // recent memory, so we will keep its process ahead
12653 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012654 if (adj > ProcessList.SERVICE_ADJ) {
12655 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012656 app.adjType = "started-services";
12657 app.hidden = false;
12658 }
12659 }
12660 // If we have let the service slide into the background
12661 // state, still have some text describing what it is doing
12662 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012663 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012664 app.adjType = "started-bg-services";
12665 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012666 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012667 // Don't kill this process because it is doing work; it
12668 // has said it is doing work.
12669 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012670 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012671 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012672 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012673 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012674 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012675 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012676 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012677 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012678 // XXX should compute this based on the max of
12679 // all connected clients.
12680 ConnectionRecord cr = clist.get(i);
12681 if (cr.binding.client == app) {
12682 // Binding to ourself is not interesting.
12683 continue;
12684 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012685 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012686 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012687 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012688 int myHiddenAdj = hiddenAdj;
12689 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012690 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012691 myHiddenAdj = client.hiddenAdj;
12692 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012693 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012694 }
12695 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012696 int myClientHiddenAdj = clientHiddenAdj;
12697 if (myClientHiddenAdj > client.clientHiddenAdj) {
12698 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12699 myClientHiddenAdj = client.clientHiddenAdj;
12700 } else {
12701 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12702 }
12703 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012704 int myEmptyAdj = emptyAdj;
12705 if (myEmptyAdj > client.emptyAdj) {
12706 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12707 myEmptyAdj = client.emptyAdj;
12708 } else {
12709 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12710 }
12711 }
12712 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012713 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012714 String adjType = null;
12715 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12716 // Not doing bind OOM management, so treat
12717 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012718 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012719 // If this process has shown some UI, let it immediately
12720 // go to the LRU list because it may be pretty heavy with
12721 // UI stuff. We'll tag it with a label just to help
12722 // debug and understand what is going on.
12723 if (adj > clientAdj) {
12724 adjType = "bound-bg-ui-services";
12725 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012726 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012727 clientAdj = adj;
12728 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012729 if (now >= (s.lastActivity
12730 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012731 // This service has not seen activity within
12732 // recent memory, so allow it to drop to the
12733 // LRU list if there is no other reason to keep
12734 // it around. We'll also tag it with a label just
12735 // to help debug and undertand what is going on.
12736 if (adj > clientAdj) {
12737 adjType = "bound-bg-services";
12738 }
12739 clientAdj = adj;
12740 }
12741 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012742 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12743 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12744 // If this connection is keeping the service
12745 // created, then we want to try to better follow
12746 // its memory management semantics for activities.
12747 // That is, if it is sitting in the background
12748 // LRU list as a hidden process (with activities),
12749 // we don't want the service it is connected to
12750 // to go into the empty LRU and quickly get killed,
12751 // because I'll we'll do is just end up restarting
12752 // the service.
12753 app.hasClientActivities |= client.hasActivities;
12754 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012755 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012756 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012757 // If this process has recently shown UI, and
12758 // the process that is binding to it is less
12759 // important than being visible, then we don't
12760 // care about the binding as much as we care
12761 // about letting this process get into the LRU
12762 // list to be killed and restarted if needed for
12763 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012764 if (app.hasShownUi && app != mHomeProcess
12765 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012766 adjType = "bound-bg-ui-services";
12767 } else {
12768 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12769 |Context.BIND_IMPORTANT)) != 0) {
12770 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012771 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12772 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12773 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12774 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12775 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012776 adj = clientAdj;
12777 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012778 app.pendingUiClean = true;
12779 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12780 adj = ProcessList.VISIBLE_APP_ADJ;
12781 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012782 }
12783 if (!client.hidden) {
12784 app.hidden = false;
12785 }
12786 if (client.keeping) {
12787 app.keeping = true;
12788 }
12789 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012790 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012791 }
12792 if (adjType != null) {
12793 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012794 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12795 .REASON_SERVICE_IN_USE;
12796 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012797 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012798 app.adjTarget = s.name;
12799 }
12800 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12801 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12802 schedGroup = Process.THREAD_GROUP_DEFAULT;
12803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012804 }
12805 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012806 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012807 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012808 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012809 (a.visible || a.state == ActivityState.RESUMED
12810 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012811 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012812 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12813 schedGroup = Process.THREAD_GROUP_DEFAULT;
12814 }
12815 app.hidden = false;
12816 app.adjType = "service";
12817 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12818 .REASON_SERVICE_IN_USE;
12819 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012820 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012821 app.adjTarget = s.name;
12822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 }
12825 }
12826 }
12827 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012828
Dianne Hackborn287952c2010-09-22 22:34:31 -070012829 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012830 // would like to avoid killing it unless it would prevent the current
12831 // application from running. By default we put the process in
12832 // with the rest of the background processes; as we scan through
12833 // its services we may bump it up from there.
12834 if (adj > hiddenAdj) {
12835 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012836 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012837 app.adjType = "bg-services";
12838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012839 }
12840
Dianne Hackborn7d608422011-08-07 16:24:18 -070012841 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012842 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012843 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012844 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012845 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012846 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012847 for (int i = cpr.connections.size()-1;
12848 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12849 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12850 i--) {
12851 ContentProviderConnection conn = cpr.connections.get(i);
12852 ProcessRecord client = conn.client;
12853 if (client == app) {
12854 // Being our own client is not interesting.
12855 continue;
12856 }
12857 int myHiddenAdj = hiddenAdj;
12858 if (myHiddenAdj > client.hiddenAdj) {
12859 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12860 myHiddenAdj = client.hiddenAdj;
12861 } else {
12862 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012863 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012864 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012865 int myClientHiddenAdj = clientHiddenAdj;
12866 if (myClientHiddenAdj > client.clientHiddenAdj) {
12867 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
12868 myClientHiddenAdj = client.clientHiddenAdj;
12869 } else {
12870 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
12871 }
12872 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012873 int myEmptyAdj = emptyAdj;
12874 if (myEmptyAdj > client.emptyAdj) {
12875 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12876 myEmptyAdj = client.emptyAdj;
12877 } else {
12878 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12879 }
12880 }
12881 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012882 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012883 if (adj > clientAdj) {
12884 if (app.hasShownUi && app != mHomeProcess
12885 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12886 app.adjType = "bg-ui-provider";
12887 } else {
12888 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12889 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12890 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012891 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012892 if (!client.hidden) {
12893 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012895 if (client.keeping) {
12896 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012897 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012898 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12899 .REASON_PROVIDER_IN_USE;
12900 app.adjSource = client;
12901 app.adjSourceOom = clientAdj;
12902 app.adjTarget = cpr.name;
12903 }
12904 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12905 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 }
12907 }
12908 // If the provider has external (non-framework) process
12909 // dependencies, ensure that its adjustment is at least
12910 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012911 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012912 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12913 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012914 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012915 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012916 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012917 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012918 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 }
12920 }
12921 }
12922 }
12923
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012924 if (adj == ProcessList.SERVICE_ADJ) {
12925 if (doingAll) {
12926 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12927 mNewNumServiceProcs++;
12928 }
12929 if (app.serviceb) {
12930 adj = ProcessList.SERVICE_B_ADJ;
12931 }
12932 } else {
12933 app.serviceb = false;
12934 }
12935
12936 app.nonStoppingAdj = adj;
12937
12938 if (hasStoppingActivities) {
12939 // Only upgrade adjustment.
12940 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12941 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12942 app.adjType = "stopping";
12943 }
12944 }
12945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012946 app.curRawAdj = adj;
12947
Joe Onorato8a9b2202010-02-26 18:56:32 -080012948 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12950 if (adj > app.maxAdj) {
12951 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012952 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012953 schedGroup = Process.THREAD_GROUP_DEFAULT;
12954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012956 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012957 app.keeping = true;
12958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012960 if (app.hasAboveClient) {
12961 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12962 // then we need to drop its adjustment to be lower than the service's
12963 // in order to honor the request. We want to drop it by one adjustment
12964 // level... but there is special meaning applied to various levels so
12965 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012966 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012967 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012968 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12969 adj = ProcessList.VISIBLE_APP_ADJ;
12970 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12971 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12972 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12973 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012974 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012975 adj++;
12976 }
12977 }
12978
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012979 int importance = app.memImportance;
12980 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12981 app.curAdj = adj;
12982 app.curSchedGroup = schedGroup;
12983 if (!interesting) {
12984 // For this reporting, if there is not something explicitly
12985 // interesting in this process then we will push it to the
12986 // background importance.
12987 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12988 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12989 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12990 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12991 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12992 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12993 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12994 } else if (adj >= ProcessList.SERVICE_ADJ) {
12995 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12996 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12997 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12998 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12999 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13000 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13001 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13002 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13003 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13004 } else {
13005 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13006 }
13007 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013008
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013009 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13010 if (foregroundActivities != app.foregroundActivities) {
13011 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13012 }
13013 if (changes != 0) {
13014 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13015 app.memImportance = importance;
13016 app.foregroundActivities = foregroundActivities;
13017 int i = mPendingProcessChanges.size()-1;
13018 ProcessChangeItem item = null;
13019 while (i >= 0) {
13020 item = mPendingProcessChanges.get(i);
13021 if (item.pid == app.pid) {
13022 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13023 break;
13024 }
13025 i--;
13026 }
13027 if (i < 0) {
13028 // No existing item in pending changes; need a new one.
13029 final int NA = mAvailProcessChanges.size();
13030 if (NA > 0) {
13031 item = mAvailProcessChanges.remove(NA-1);
13032 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13033 } else {
13034 item = new ProcessChangeItem();
13035 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13036 }
13037 item.changes = 0;
13038 item.pid = app.pid;
13039 item.uid = app.info.uid;
13040 if (mPendingProcessChanges.size() == 0) {
13041 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13042 "*** Enqueueing dispatch processes changed!");
13043 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13044 }
13045 mPendingProcessChanges.add(item);
13046 }
13047 item.changes |= changes;
13048 item.importance = importance;
13049 item.foregroundActivities = foregroundActivities;
13050 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13051 + Integer.toHexString(System.identityHashCode(item))
13052 + " " + app.toShortString() + ": changes=" + item.changes
13053 + " importance=" + item.importance
13054 + " foreground=" + item.foregroundActivities
13055 + " type=" + app.adjType + " source=" + app.adjSource
13056 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013057 }
13058
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013059 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 }
13061
13062 /**
13063 * Ask a given process to GC right now.
13064 */
13065 final void performAppGcLocked(ProcessRecord app) {
13066 try {
13067 app.lastRequestedGc = SystemClock.uptimeMillis();
13068 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013069 if (app.reportLowMemory) {
13070 app.reportLowMemory = false;
13071 app.thread.scheduleLowMemory();
13072 } else {
13073 app.thread.processInBackground();
13074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013075 }
13076 } catch (Exception e) {
13077 // whatever.
13078 }
13079 }
13080
13081 /**
13082 * Returns true if things are idle enough to perform GCs.
13083 */
Josh Bartel7f208742010-02-25 11:01:44 -060013084 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013085 boolean processingBroadcasts = false;
13086 for (BroadcastQueue q : mBroadcastQueues) {
13087 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13088 processingBroadcasts = true;
13089 }
13090 }
13091 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013092 && (mSleeping || (mMainStack.mResumedActivity != null &&
13093 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 }
13095
13096 /**
13097 * Perform GCs on all processes that are waiting for it, but only
13098 * if things are idle.
13099 */
13100 final void performAppGcsLocked() {
13101 final int N = mProcessesToGc.size();
13102 if (N <= 0) {
13103 return;
13104 }
Josh Bartel7f208742010-02-25 11:01:44 -060013105 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 while (mProcessesToGc.size() > 0) {
13107 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013108 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013109 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13110 <= SystemClock.uptimeMillis()) {
13111 // To avoid spamming the system, we will GC processes one
13112 // at a time, waiting a few seconds between each.
13113 performAppGcLocked(proc);
13114 scheduleAppGcsLocked();
13115 return;
13116 } else {
13117 // It hasn't been long enough since we last GCed this
13118 // process... put it in the list to wait for its time.
13119 addProcessToGcListLocked(proc);
13120 break;
13121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013122 }
13123 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013124
13125 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013126 }
13127 }
13128
13129 /**
13130 * If all looks good, perform GCs on all processes waiting for them.
13131 */
13132 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013133 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013134 performAppGcsLocked();
13135 return;
13136 }
13137 // Still not idle, wait some more.
13138 scheduleAppGcsLocked();
13139 }
13140
13141 /**
13142 * Schedule the execution of all pending app GCs.
13143 */
13144 final void scheduleAppGcsLocked() {
13145 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013146
13147 if (mProcessesToGc.size() > 0) {
13148 // Schedule a GC for the time to the next process.
13149 ProcessRecord proc = mProcessesToGc.get(0);
13150 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13151
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013152 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013153 long now = SystemClock.uptimeMillis();
13154 if (when < (now+GC_TIMEOUT)) {
13155 when = now + GC_TIMEOUT;
13156 }
13157 mHandler.sendMessageAtTime(msg, when);
13158 }
13159 }
13160
13161 /**
13162 * Add a process to the array of processes waiting to be GCed. Keeps the
13163 * list in sorted order by the last GC time. The process can't already be
13164 * on the list.
13165 */
13166 final void addProcessToGcListLocked(ProcessRecord proc) {
13167 boolean added = false;
13168 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13169 if (mProcessesToGc.get(i).lastRequestedGc <
13170 proc.lastRequestedGc) {
13171 added = true;
13172 mProcessesToGc.add(i+1, proc);
13173 break;
13174 }
13175 }
13176 if (!added) {
13177 mProcessesToGc.add(0, proc);
13178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 }
13180
13181 /**
13182 * Set up to ask a process to GC itself. This will either do it
13183 * immediately, or put it on the list of processes to gc the next
13184 * time things are idle.
13185 */
13186 final void scheduleAppGcLocked(ProcessRecord app) {
13187 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013188 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013189 return;
13190 }
13191 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013192 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013193 scheduleAppGcsLocked();
13194 }
13195 }
13196
Dianne Hackborn287952c2010-09-22 22:34:31 -070013197 final void checkExcessivePowerUsageLocked(boolean doKills) {
13198 updateCpuStatsNow();
13199
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013200 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013201 boolean doWakeKills = doKills;
13202 boolean doCpuKills = doKills;
13203 if (mLastPowerCheckRealtime == 0) {
13204 doWakeKills = false;
13205 }
13206 if (mLastPowerCheckUptime == 0) {
13207 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013208 }
13209 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013210 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013211 }
13212 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013213 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13214 final long curUptime = SystemClock.uptimeMillis();
13215 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13216 mLastPowerCheckRealtime = curRealtime;
13217 mLastPowerCheckUptime = curUptime;
13218 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13219 doWakeKills = false;
13220 }
13221 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13222 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013223 }
13224 int i = mLruProcesses.size();
13225 while (i > 0) {
13226 i--;
13227 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013229 long wtime;
13230 synchronized (stats) {
13231 wtime = stats.getProcessWakeTime(app.info.uid,
13232 app.pid, curRealtime);
13233 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013234 long wtimeUsed = wtime - app.lastWakeTime;
13235 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13236 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013237 StringBuilder sb = new StringBuilder(128);
13238 sb.append("Wake for ");
13239 app.toShortString(sb);
13240 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013241 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013242 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013243 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013244 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013245 sb.append((wtimeUsed*100)/realtimeSince);
13246 sb.append("%)");
13247 Slog.i(TAG, sb.toString());
13248 sb.setLength(0);
13249 sb.append("CPU for ");
13250 app.toShortString(sb);
13251 sb.append(": over ");
13252 TimeUtils.formatDuration(uptimeSince, sb);
13253 sb.append(" used ");
13254 TimeUtils.formatDuration(cputimeUsed, sb);
13255 sb.append(" (");
13256 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013257 sb.append("%)");
13258 Slog.i(TAG, sb.toString());
13259 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013260 // If a process has held a wake lock for more
13261 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013262 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013263 if (doWakeKills && realtimeSince > 0
13264 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13265 synchronized (stats) {
13266 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13267 realtimeSince, wtimeUsed);
13268 }
13269 Slog.w(TAG, "Excessive wake lock in " + app.processName
13270 + " (pid " + app.pid + "): held " + wtimeUsed
13271 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013272 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013273 app.processName, app.setAdj, "excessive wake lock");
13274 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013275 } else if (doCpuKills && uptimeSince > 0
13276 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13277 synchronized (stats) {
13278 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13279 uptimeSince, cputimeUsed);
13280 }
13281 Slog.w(TAG, "Excessive CPU in " + app.processName
13282 + " (pid " + app.pid + "): used " + cputimeUsed
13283 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013284 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013285 app.processName, app.setAdj, "excessive cpu");
13286 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013287 } else {
13288 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013289 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013290 }
13291 }
13292 }
13293 }
13294
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013295 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013296 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013298 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013299 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013300
13301 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013302 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013303 }
13304
Dianne Hackborn287952c2010-09-22 22:34:31 -070013305 final boolean wasKeeping = app.keeping;
13306
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013307 boolean success = true;
13308
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013309 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310
Jeff Brown10e89712011-07-08 18:52:57 -070013311 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013312 if (wasKeeping && !app.keeping) {
13313 // This app is no longer something we want to keep. Note
13314 // its current wake lock time to later know to kill it if
13315 // it is not behaving well.
13316 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13317 synchronized (stats) {
13318 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13319 app.pid, SystemClock.elapsedRealtime());
13320 }
13321 app.lastCpuTime = app.curCpuTime;
13322 }
13323
13324 app.setRawAdj = app.curRawAdj;
13325 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013326
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013327 if (app.curAdj != app.setAdj) {
13328 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013329 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013330 TAG, "Set " + app.pid + " " + app.processName +
13331 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013332 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013333 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013334 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013335 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013336 }
13337 }
13338 if (app.setSchedGroup != app.curSchedGroup) {
13339 app.setSchedGroup = app.curSchedGroup;
13340 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13341 "Setting process group of " + app.processName
13342 + " to " + app.curSchedGroup);
13343 if (app.waitingToKill != null &&
13344 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13345 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013346 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013347 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013348 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013349 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013350 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013351 } else {
13352 if (true) {
13353 long oldId = Binder.clearCallingIdentity();
13354 try {
13355 Process.setProcessGroup(app.pid, app.curSchedGroup);
13356 } catch (Exception e) {
13357 Slog.w(TAG, "Failed setting process group of " + app.pid
13358 + " to " + app.curSchedGroup);
13359 e.printStackTrace();
13360 } finally {
13361 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013362 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013363 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013364 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013365 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013366 app.thread.setSchedulingGroup(app.curSchedGroup);
13367 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013368 }
13369 }
13370 }
13371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013372 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013373 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 }
13375
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013376 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013377 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013378 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013379 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013380 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013381 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013382 }
13383 }
13384 return resumedActivity;
13385 }
13386
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013387 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013388 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13390 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013391 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13392 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393
13394 mAdjSeq++;
13395
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013396 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13397 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013398 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13399 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013400 if (nowHidden != wasHidden) {
13401 // Changed to/from hidden state, so apps after it in the LRU
13402 // list may also be changed.
13403 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013404 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013405 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013406 }
13407
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013408 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013409 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013410 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013411 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013412
13413 if (false) {
13414 RuntimeException e = new RuntimeException();
13415 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013416 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 }
13418
13419 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013420 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013421
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013422 final int emptyProcessLimit;
13423 final int hiddenProcessLimit;
13424 if (mProcessLimit <= 0) {
13425 emptyProcessLimit = hiddenProcessLimit = 0;
13426 } else if (mProcessLimit == 1) {
13427 emptyProcessLimit = 1;
13428 hiddenProcessLimit = 0;
13429 } else {
13430 emptyProcessLimit = (mProcessLimit*2)/3;
13431 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13432 }
13433
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013434 // Let's determine how many processes we have running vs.
13435 // how many slots we have for background processes; we may want
13436 // to put multiple processes in a slot of there are enough of
13437 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013438 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13439 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013440 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13441 if (numEmptyProcs > hiddenProcessLimit) {
13442 // If there are more empty processes than our limit on hidden
13443 // processes, then use the hidden process limit for the factor.
13444 // This ensures that the really old empty processes get pushed
13445 // down to the bottom, so if we are running low on memory we will
13446 // have a better chance at keeping around more hidden processes
13447 // instead of a gazillion empty processes.
13448 numEmptyProcs = hiddenProcessLimit;
13449 }
13450 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013451 if (emptyFactor < 1) emptyFactor = 1;
13452 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13453 if (hiddenFactor < 1) hiddenFactor = 1;
13454 int stepHidden = 0;
13455 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013456 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013457 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013458 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013459
13460 mNumNonHiddenProcs = 0;
13461 mNumHiddenProcs = 0;
13462
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013463 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013465 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013466 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013467 int nextHiddenAdj = curHiddenAdj+1;
13468 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13469 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013470 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 while (i > 0) {
13472 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013473 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013474 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013475 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013476 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013477 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13478 // This process was assigned as a hidden process... step the
13479 // hidden level.
13480 mNumHiddenProcs++;
13481 if (curHiddenAdj != nextHiddenAdj) {
13482 stepHidden++;
13483 if (stepHidden >= hiddenFactor) {
13484 stepHidden = 0;
13485 curHiddenAdj = nextHiddenAdj;
13486 nextHiddenAdj += 2;
13487 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13488 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13489 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013490 if (curClientHiddenAdj <= curHiddenAdj) {
13491 curClientHiddenAdj = curHiddenAdj + 1;
13492 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13493 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13494 }
13495 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013496 }
13497 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013498 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013499 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013500 Slog.i(TAG, "No longer want " + app.processName
13501 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013502 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013503 app.processName, app.setAdj, "too many background");
13504 app.killedBackground = true;
13505 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013506 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013507 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13508 // This process has a client that has activities. We will have
13509 // given it the current hidden adj; here we will just leave it
13510 // without stepping the hidden adj.
13511 curClientHiddenAdj++;
13512 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13513 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13514 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013515 } else {
13516 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13517 // This process was assigned as an empty process... step the
13518 // empty level.
13519 if (curEmptyAdj != nextEmptyAdj) {
13520 stepEmpty++;
13521 if (stepEmpty >= emptyFactor) {
13522 stepEmpty = 0;
13523 curEmptyAdj = nextEmptyAdj;
13524 nextEmptyAdj += 2;
13525 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13526 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13527 }
13528 }
13529 }
13530 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13531 mNumNonHiddenProcs++;
13532 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013533 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13534 && !app.hasClientActivities) {
13535 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13536 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013537 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013538 + " (pid " + app.pid + "): empty for "
13539 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13540 / 1000) + "s");
13541 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13542 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013543 app.killedBackground = true;
13544 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013545 } else {
13546 numEmpty++;
13547 if (numEmpty > emptyProcessLimit) {
13548 Slog.i(TAG, "No longer want " + app.processName
13549 + " (pid " + app.pid + "): empty #" + numEmpty);
13550 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13551 app.processName, app.setAdj, "too many background");
13552 app.killedBackground = true;
13553 Process.killProcessQuiet(app.pid);
13554 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013555 }
13556 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013557 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013558 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013559 // If this is an isolated process, and there are no
13560 // services running in it, then the process is no longer
13561 // needed. We agressively kill these because we can by
13562 // definition not re-use the same process again, and it is
13563 // good to avoid having whatever code was running in them
13564 // left sitting around after no longer needed.
13565 Slog.i(TAG, "Isolated process " + app.processName
13566 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013567 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013568 app.processName, app.setAdj, "isolated not needed");
13569 app.killedBackground = true;
13570 Process.killProcessQuiet(app.pid);
13571 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013572 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13573 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13574 && !app.killedBackground) {
13575 numTrimming++;
13576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013577 }
13578 }
13579
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013580 mNumServiceProcs = mNewNumServiceProcs;
13581
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013582 // Now determine the memory trimming level of background processes.
13583 // Unfortunately we need to start at the back of the list to do this
13584 // properly. We only do this if the number of background apps we
13585 // are managing to keep around is less than half the maximum we desire;
13586 // if we are keeping a good number around, we'll let them use whatever
13587 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013588 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13589 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013590 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013591 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013592 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013593 int minFactor = 2;
13594 if (mHomeProcess != null) minFactor++;
13595 if (mPreviousProcess != null) minFactor++;
13596 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013597 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013598 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013599 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013600 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013601 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013602 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13603 } else {
13604 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13605 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013606 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013607 for (i=0; i<N; i++) {
13608 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013609 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13610 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013611 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013612 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13613 try {
13614 app.thread.scheduleTrimMemory(curLevel);
13615 } catch (RemoteException e) {
13616 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013617 if (false) {
13618 // For now we won't do this; our memory trimming seems
13619 // to be good enough at this point that destroying
13620 // activities causes more harm than good.
13621 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13622 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013623 // Need to do this on its own message because the stack may not
13624 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013625 // For these apps we will also finish their activities
13626 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013627 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013628 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013629 }
13630 }
13631 app.trimMemoryLevel = curLevel;
13632 step++;
13633 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013634 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013635 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013636 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13637 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013638 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013639 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13640 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013641 break;
13642 }
13643 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013644 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013645 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013646 && app.thread != null) {
13647 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013648 app.thread.scheduleTrimMemory(
13649 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013650 } catch (RemoteException e) {
13651 }
13652 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013653 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013654 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013655 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013656 && app.pendingUiClean) {
13657 // If this application is now in the background and it
13658 // had done UI, then give it the special trim level to
13659 // have it free UI resources.
13660 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13661 if (app.trimMemoryLevel < level && app.thread != null) {
13662 try {
13663 app.thread.scheduleTrimMemory(level);
13664 } catch (RemoteException e) {
13665 }
13666 }
13667 app.pendingUiClean = false;
13668 }
13669 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013670 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013671 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013672 } catch (RemoteException e) {
13673 }
13674 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013675 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013676 }
13677 }
13678 } else {
13679 final int N = mLruProcesses.size();
13680 for (i=0; i<N; i++) {
13681 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013682 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013683 && app.pendingUiClean) {
13684 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13685 && app.thread != null) {
13686 try {
13687 app.thread.scheduleTrimMemory(
13688 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13689 } catch (RemoteException e) {
13690 }
13691 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013692 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013693 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013694 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013695 }
13696 }
13697
13698 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013699 // Need to do this on its own message because the stack may not
13700 // be in a consistent state at this point.
13701 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 }
13704
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013705 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 synchronized (this) {
13707 int i;
13708
13709 // First remove any unused application processes whose package
13710 // has been removed.
13711 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13712 final ProcessRecord app = mRemovedProcesses.get(i);
13713 if (app.activities.size() == 0
13714 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013715 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716 TAG, "Exiting empty application process "
13717 + app.processName + " ("
13718 + (app.thread != null ? app.thread.asBinder() : null)
13719 + ")\n");
13720 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013721 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013722 app.processName, app.setAdj, "empty");
13723 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013724 } else {
13725 try {
13726 app.thread.scheduleExit();
13727 } catch (Exception e) {
13728 // Ignore exceptions.
13729 }
13730 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013731 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013732 mRemovedProcesses.remove(i);
13733
13734 if (app.persistent) {
13735 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013736 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013737 }
13738 }
13739 }
13740 }
13741
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013742 // Now update the oom adj for all processes.
13743 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013744 }
13745 }
13746
13747 /** This method sends the specified signal to each of the persistent apps */
13748 public void signalPersistentProcesses(int sig) throws RemoteException {
13749 if (sig != Process.SIGNAL_USR1) {
13750 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13751 }
13752
13753 synchronized (this) {
13754 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13755 != PackageManager.PERMISSION_GRANTED) {
13756 throw new SecurityException("Requires permission "
13757 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13758 }
13759
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013760 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13761 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013762 if (r.thread != null && r.persistent) {
13763 Process.sendSignal(r.pid, sig);
13764 }
13765 }
13766 }
13767 }
13768
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013769 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13770 if (proc == null || proc == mProfileProc) {
13771 proc = mProfileProc;
13772 path = mProfileFile;
13773 profileType = mProfileType;
13774 clearProfilerLocked();
13775 }
13776 if (proc == null) {
13777 return;
13778 }
13779 try {
13780 proc.thread.profilerControl(false, path, null, profileType);
13781 } catch (RemoteException e) {
13782 throw new IllegalStateException("Process disappeared");
13783 }
13784 }
13785
13786 private void clearProfilerLocked() {
13787 if (mProfileFd != null) {
13788 try {
13789 mProfileFd.close();
13790 } catch (IOException e) {
13791 }
13792 }
13793 mProfileApp = null;
13794 mProfileProc = null;
13795 mProfileFile = null;
13796 mProfileType = 0;
13797 mAutoStopProfiler = false;
13798 }
13799
Dianne Hackborn1676c852012-09-10 14:52:30 -070013800 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013801 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013802
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013803 try {
13804 synchronized (this) {
13805 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13806 // its own permission.
13807 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13808 != PackageManager.PERMISSION_GRANTED) {
13809 throw new SecurityException("Requires permission "
13810 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013811 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013812
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013813 if (start && fd == null) {
13814 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013815 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013816
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013817 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013818 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013819 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013820 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013821
13822 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013823 throw new IllegalArgumentException("Unknown process: " + process);
13824 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013825
13826 if (start) {
13827 stopProfilerLocked(null, null, 0);
13828 setProfileApp(proc.info, proc.processName, path, fd, false);
13829 mProfileProc = proc;
13830 mProfileType = profileType;
13831 try {
13832 fd = fd.dup();
13833 } catch (IOException e) {
13834 fd = null;
13835 }
13836 proc.thread.profilerControl(start, path, fd, profileType);
13837 fd = null;
13838 mProfileFd = null;
13839 } else {
13840 stopProfilerLocked(proc, path, profileType);
13841 if (fd != null) {
13842 try {
13843 fd.close();
13844 } catch (IOException e) {
13845 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013846 }
13847 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013848
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013849 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013850 }
13851 } catch (RemoteException e) {
13852 throw new IllegalStateException("Process disappeared");
13853 } finally {
13854 if (fd != null) {
13855 try {
13856 fd.close();
13857 } catch (IOException e) {
13858 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013859 }
13860 }
13861 }
Andy McFadden824c5102010-07-09 16:26:57 -070013862
Dianne Hackborn1676c852012-09-10 14:52:30 -070013863 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070013864 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070013865 userId, true, true, callName, null);
13866 ProcessRecord proc = null;
13867 try {
13868 int pid = Integer.parseInt(process);
13869 synchronized (mPidsSelfLocked) {
13870 proc = mPidsSelfLocked.get(pid);
13871 }
13872 } catch (NumberFormatException e) {
13873 }
13874
13875 if (proc == null) {
13876 HashMap<String, SparseArray<ProcessRecord>> all
13877 = mProcessNames.getMap();
13878 SparseArray<ProcessRecord> procs = all.get(process);
13879 if (procs != null && procs.size() > 0) {
13880 proc = procs.valueAt(0);
13881 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13882 for (int i=1; i<procs.size(); i++) {
13883 ProcessRecord thisProc = procs.valueAt(i);
13884 if (thisProc.userId == userId) {
13885 proc = thisProc;
13886 break;
13887 }
13888 }
13889 }
13890 }
13891 }
13892
13893 return proc;
13894 }
13895
13896 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013897 String path, ParcelFileDescriptor fd) throws RemoteException {
13898
13899 try {
13900 synchronized (this) {
13901 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13902 // its own permission (same as profileControl).
13903 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13904 != PackageManager.PERMISSION_GRANTED) {
13905 throw new SecurityException("Requires permission "
13906 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13907 }
13908
13909 if (fd == null) {
13910 throw new IllegalArgumentException("null fd");
13911 }
13912
Dianne Hackborn1676c852012-09-10 14:52:30 -070013913 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013914 if (proc == null || proc.thread == null) {
13915 throw new IllegalArgumentException("Unknown process: " + process);
13916 }
13917
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013918 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13919 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013920 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13921 throw new SecurityException("Process not debuggable: " + proc);
13922 }
13923 }
13924
13925 proc.thread.dumpHeap(managed, path, fd);
13926 fd = null;
13927 return true;
13928 }
13929 } catch (RemoteException e) {
13930 throw new IllegalStateException("Process disappeared");
13931 } finally {
13932 if (fd != null) {
13933 try {
13934 fd.close();
13935 } catch (IOException e) {
13936 }
13937 }
13938 }
13939 }
13940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013941 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13942 public void monitor() {
13943 synchronized (this) { }
13944 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013945
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013946 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013947 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13948 ProcessRecord processRecord = mLruProcesses.get(i);
13949 try {
13950 if (processRecord.thread != null) {
13951 processRecord.thread.setCoreSettings(settings);
13952 }
13953 } catch (RemoteException re) {
13954 /* ignore */
13955 }
13956 }
13957 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013958
13959 // Multi-user methods
13960
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013961 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080013962 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013963 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13964 != PackageManager.PERMISSION_GRANTED) {
13965 String msg = "Permission Denial: switchUser() from pid="
13966 + Binder.getCallingPid()
13967 + ", uid=" + Binder.getCallingUid()
13968 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13969 Slog.w(TAG, msg);
13970 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013971 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013972
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013973 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013974 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013975 synchronized (this) {
13976 final int oldUserId = mCurrentUserId;
13977 if (oldUserId == userId) {
13978 return true;
13979 }
13980
13981 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
13982 if (userInfo == null) {
13983 Slog.w(TAG, "No user info for user #" + userId);
13984 return false;
13985 }
13986
13987 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13988 R.anim.screen_user_enter);
13989
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070013990 boolean needStart = false;
13991
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013992 // If the user we are switching to is not currently started, then
13993 // we need to start it now.
13994 if (mStartedUsers.get(userId) == null) {
13995 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070013996 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070013997 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070013998 }
13999
14000 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014001 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014002 final Integer userIdInt = Integer.valueOf(userId);
14003 mUserLru.remove(userIdInt);
14004 mUserLru.add(userIdInt);
14005
Craig Mautnerf1b67412012-09-19 13:18:29 -070014006 mWindowManager.setCurrentUser(userId);
14007
Adam Cohenf7522022012-10-03 20:03:18 -070014008 // Once the internal notion of the active user has switched, we lock the device
14009 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014010 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014011
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014012 final UserStartedState uss = mStartedUsers.get(userId);
14013
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014014 // Make sure user is in the started state. If it is currently
14015 // stopping, we need to knock that off.
14016 if (uss.mState == UserStartedState.STATE_STOPPING) {
14017 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14018 // so we can just fairly silently bring the user back from
14019 // the almost-dead.
14020 uss.mState = UserStartedState.STATE_RUNNING;
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 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14024 // This means ACTION_SHUTDOWN has been sent, so we will
14025 // need to treat this as a new boot of the user.
14026 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014027 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014028 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014029 }
14030
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014031 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14032 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14033 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14034 oldUserId, userId, uss));
14035 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14036 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014037 if (needStart) {
14038 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14039 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14040 | Intent.FLAG_RECEIVER_FOREGROUND);
14041 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14042 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014043 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014044 false, false, MY_PID, Process.SYSTEM_UID, userId);
14045 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014046
14047 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14048 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014049 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014050 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014051 broadcastIntentLocked(null, null, intent, null,
14052 new IIntentReceiver.Stub() {
14053 public void performReceive(Intent intent, int resultCode,
14054 String data, Bundle extras, boolean ordered,
14055 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014056 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014057 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014058 }, 0, null, null, null, AppOpsManager.OP_NONE,
14059 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014060 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014061 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014062 } else {
14063 getUserManagerLocked().makeInitialized(userInfo.id);
14064 }
14065 }
14066
14067 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14068 if (!haveActivities) {
14069 startHomeActivityLocked(userId);
14070 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014071
Jeff Sharkey86597df2012-11-09 15:00:31 -080014072 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014073 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014074 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014075 if (needStart) {
14076 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14077 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14078 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14079 broadcastIntentLocked(null, null, intent,
14080 null, new IIntentReceiver.Stub() {
14081 @Override
14082 public void performReceive(Intent intent, int resultCode, String data,
14083 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14084 throws RemoteException {
14085 }
14086 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014087 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014088 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014089 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014090 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014091 } finally {
14092 Binder.restoreCallingIdentity(ident);
14093 }
Amith Yamasani13593602012-03-22 16:16:17 -070014094
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014095 return true;
14096 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014097
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014098 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14099 long ident = Binder.clearCallingIdentity();
14100 try {
14101 Intent intent;
14102 if (oldUserId >= 0) {
14103 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014104 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14105 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014106 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14107 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014108 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014109 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14110 }
14111 if (newUserId >= 0) {
14112 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014113 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14114 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014115 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14116 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014117 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014118 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14119 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014120 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14121 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014122 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14123 broadcastIntentLocked(null, null, intent,
14124 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014125 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014126 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14127 }
14128 } finally {
14129 Binder.restoreCallingIdentity(ident);
14130 }
14131 }
14132
14133 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14134 final int newUserId) {
14135 final int N = mUserSwitchObservers.beginBroadcast();
14136 if (N > 0) {
14137 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14138 int mCount = 0;
14139 @Override
14140 public void sendResult(Bundle data) throws RemoteException {
14141 synchronized (ActivityManagerService.this) {
14142 if (mCurUserSwitchCallback == this) {
14143 mCount++;
14144 if (mCount == N) {
14145 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14146 }
14147 }
14148 }
14149 }
14150 };
14151 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014152 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014153 mCurUserSwitchCallback = callback;
14154 }
14155 for (int i=0; i<N; i++) {
14156 try {
14157 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14158 newUserId, callback);
14159 } catch (RemoteException e) {
14160 }
14161 }
14162 } else {
14163 synchronized (this) {
14164 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14165 }
14166 }
14167 mUserSwitchObservers.finishBroadcast();
14168 }
14169
14170 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14171 synchronized (this) {
14172 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14173 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14174 }
14175 }
14176
14177 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14178 mCurUserSwitchCallback = null;
14179 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14180 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14181 oldUserId, newUserId, uss));
14182 }
14183
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014184 void userInitialized(UserStartedState uss, int newUserId) {
14185 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014186 }
14187
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014188 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014189 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014190 }
14191
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014192 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14193 boolean clearInitializing, boolean clearSwitching) {
14194 boolean unfrozen = false;
14195 synchronized (this) {
14196 if (clearInitializing) {
14197 uss.initializing = false;
14198 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14199 }
14200 if (clearSwitching) {
14201 uss.switching = false;
14202 }
14203 if (!uss.switching && !uss.initializing) {
14204 mWindowManager.stopFreezingScreen();
14205 unfrozen = true;
14206 }
14207 }
14208 if (unfrozen) {
14209 final int N = mUserSwitchObservers.beginBroadcast();
14210 for (int i=0; i<N; i++) {
14211 try {
14212 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14213 } catch (RemoteException e) {
14214 }
14215 }
14216 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014217 }
14218 }
14219
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014220 void finishUserSwitch(UserStartedState uss) {
14221 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014222 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014223 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14224 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014225 final int userId = uss.mHandle.getIdentifier();
14226 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14227 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14228 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014229 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014230 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014231 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014232 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014233 int num = mUserLru.size();
14234 int i = 0;
14235 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14236 Integer oldUserId = mUserLru.get(i);
14237 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14238 if (oldUss == null) {
14239 // Shouldn't happen, but be sane if it does.
14240 mUserLru.remove(i);
14241 num--;
14242 continue;
14243 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014244 if (oldUss.mState == UserStartedState.STATE_STOPPING
14245 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014246 // This user is already stopping, doesn't count.
14247 num--;
14248 i++;
14249 continue;
14250 }
14251 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14252 // Owner and current can't be stopped, but count as running.
14253 i++;
14254 continue;
14255 }
14256 // This is a user to be stopped.
14257 stopUserLocked(oldUserId, null);
14258 num--;
14259 i++;
14260 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014261 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014262 }
14263
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014264 @Override
14265 public int stopUser(final int userId, final IStopUserCallback callback) {
14266 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14267 != PackageManager.PERMISSION_GRANTED) {
14268 String msg = "Permission Denial: switchUser() from pid="
14269 + Binder.getCallingPid()
14270 + ", uid=" + Binder.getCallingUid()
14271 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14272 Slog.w(TAG, msg);
14273 throw new SecurityException(msg);
14274 }
14275 if (userId <= 0) {
14276 throw new IllegalArgumentException("Can't stop primary user " + userId);
14277 }
Amith Yamasani13593602012-03-22 16:16:17 -070014278 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014279 return stopUserLocked(userId, callback);
14280 }
14281 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014282
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014283 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14284 if (mCurrentUserId == userId) {
14285 return ActivityManager.USER_OP_IS_CURRENT;
14286 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014287
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014288 final UserStartedState uss = mStartedUsers.get(userId);
14289 if (uss == null) {
14290 // User is not started, nothing to do... but we do need to
14291 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014292 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014293 mHandler.post(new Runnable() {
14294 @Override
14295 public void run() {
14296 try {
14297 callback.userStopped(userId);
14298 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014299 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014300 }
14301 });
14302 }
14303 return ActivityManager.USER_OP_SUCCESS;
14304 }
14305
14306 if (callback != null) {
14307 uss.mStopCallbacks.add(callback);
14308 }
14309
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014310 if (uss.mState != UserStartedState.STATE_STOPPING
14311 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014312 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014313 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014314
14315 long ident = Binder.clearCallingIdentity();
14316 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014317 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014318 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014319 // stop the user.
14320 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14321 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14322 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14323 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14324 // This is the result receiver for the final shutdown broadcast.
14325 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014326 @Override
14327 public void performReceive(Intent intent, int resultCode, String data,
14328 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14329 finishUserStop(uss);
14330 }
14331 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014332 // This is the result receiver for the initial stopping broadcast.
14333 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14334 @Override
14335 public void performReceive(Intent intent, int resultCode, String data,
14336 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14337 // On to the next.
14338 synchronized (ActivityManagerService.this) {
14339 if (uss.mState != UserStartedState.STATE_STOPPING) {
14340 // Whoops, we are being started back up. Abort, abort!
14341 return;
14342 }
14343 uss.mState = UserStartedState.STATE_SHUTDOWN;
14344 }
14345 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014346 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014347 true, false, MY_PID, Process.SYSTEM_UID, userId);
14348 }
14349 };
14350 // Kick things off.
14351 broadcastIntentLocked(null, null, stoppingIntent,
14352 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014353 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014354 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014355 } finally {
14356 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014357 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014358 }
Amith Yamasani13593602012-03-22 16:16:17 -070014359
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014360 return ActivityManager.USER_OP_SUCCESS;
14361 }
14362
14363 void finishUserStop(UserStartedState uss) {
14364 final int userId = uss.mHandle.getIdentifier();
14365 boolean stopped;
14366 ArrayList<IStopUserCallback> callbacks;
14367 synchronized (this) {
14368 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014369 if (mStartedUsers.get(userId) != uss) {
14370 stopped = false;
14371 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014372 stopped = false;
14373 } else {
14374 stopped = true;
14375 // User can no longer run.
14376 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014377 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014378 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014379
14380 // Clean up all state and processes associated with the user.
14381 // Kill all the processes for the user.
14382 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014383 }
14384 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014385
14386 for (int i=0; i<callbacks.size(); i++) {
14387 try {
14388 if (stopped) callbacks.get(i).userStopped(userId);
14389 else callbacks.get(i).userStopAborted(userId);
14390 } catch (RemoteException e) {
14391 }
14392 }
14393 }
14394
14395 @Override
14396 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014397 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14398 != PackageManager.PERMISSION_GRANTED) && (
14399 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14400 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014401 String msg = "Permission Denial: getCurrentUser() from pid="
14402 + Binder.getCallingPid()
14403 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014404 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014405 Slog.w(TAG, msg);
14406 throw new SecurityException(msg);
14407 }
14408 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014409 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014410 }
Amith Yamasani13593602012-03-22 16:16:17 -070014411 }
14412
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014413 int getCurrentUserIdLocked() {
14414 return mCurrentUserId;
14415 }
14416
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014417 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014418 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014419 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14420 != PackageManager.PERMISSION_GRANTED) {
14421 String msg = "Permission Denial: isUserRunning() from pid="
14422 + Binder.getCallingPid()
14423 + ", uid=" + Binder.getCallingUid()
14424 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14425 Slog.w(TAG, msg);
14426 throw new SecurityException(msg);
14427 }
14428 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014429 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014430 }
14431 }
14432
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014433 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014434 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014435 if (state == null) {
14436 return false;
14437 }
14438 if (orStopped) {
14439 return true;
14440 }
14441 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014442 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014443 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014444
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014445 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014446 public int[] getRunningUserIds() {
14447 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14448 != PackageManager.PERMISSION_GRANTED) {
14449 String msg = "Permission Denial: isUserRunning() from pid="
14450 + Binder.getCallingPid()
14451 + ", uid=" + Binder.getCallingUid()
14452 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14453 Slog.w(TAG, msg);
14454 throw new SecurityException(msg);
14455 }
14456 synchronized (this) {
14457 return mStartedUserArray;
14458 }
14459 }
14460
14461 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014462 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014463 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014464 UserStartedState uss = mStartedUsers.valueAt(i);
14465 // This list does not include stopping users.
14466 if (uss.mState != UserStartedState.STATE_STOPPING
14467 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14468 num++;
14469 }
14470 }
14471 mStartedUserArray = new int[num];
14472 num = 0;
14473 for (int i=0; i<mStartedUsers.size(); i++) {
14474 UserStartedState uss = mStartedUsers.valueAt(i);
14475 if (uss.mState != UserStartedState.STATE_STOPPING
14476 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14477 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14478 num++;
14479 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014480 }
14481 }
14482
14483 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014484 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14485 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14486 != PackageManager.PERMISSION_GRANTED) {
14487 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14488 + Binder.getCallingPid()
14489 + ", uid=" + Binder.getCallingUid()
14490 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14491 Slog.w(TAG, msg);
14492 throw new SecurityException(msg);
14493 }
14494
14495 mUserSwitchObservers.register(observer);
14496 }
14497
14498 @Override
14499 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14500 mUserSwitchObservers.unregister(observer);
14501 }
14502
Dianne Hackborn1676c852012-09-10 14:52:30 -070014503 private boolean userExists(int userId) {
14504 if (userId == 0) {
14505 return true;
14506 }
14507 UserManagerService ums = getUserManagerLocked();
14508 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14509 }
14510
14511 int[] getUsersLocked() {
14512 UserManagerService ums = getUserManagerLocked();
14513 return ums != null ? ums.getUserIds() : new int[] { 0 };
14514 }
14515
14516 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014517 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014518 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14519 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014520 }
14521 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014522 }
14523
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014524 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014525 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014526
14527 throw new SecurityException("Caller uid=" + uid
14528 + " is not privileged to communicate with user=" + userId);
14529 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014530
14531 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014532 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014533 }
14534
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014535 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014536 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014537 ApplicationInfo newInfo = new ApplicationInfo(info);
14538 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014539 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14540 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014541 return newInfo;
14542 }
14543
14544 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014545 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014546 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014547 return aInfo;
14548 }
14549
14550 ActivityInfo info = new ActivityInfo(aInfo);
14551 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14552 return info;
14553 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014554}