blob: db016558a76b4e1c15c09d94718e2b80f21e4320 [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 Hackborna40cfeb2013-03-25 17:49:36 -070022import android.appwidget.AppWidgetManager;
Dianne Hackborn860755f2010-06-03 18:47:52 -070023import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070025import com.android.internal.os.ProcessStats;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080026import com.android.server.AppOpsService;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070027import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.server.IntentResolver;
29import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import com.android.server.SystemServer;
31import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070032import com.android.server.am.ActivityStack.ActivityState;
Ben Gruver4efe9402013-04-02 21:18:41 -070033import com.android.server.firewall.IntentFirewall;
Dianne Hackborn1676c852012-09-10 14:52:30 -070034import com.android.server.pm.UserManagerService;
Craig Mautner4b71aa12012-12-27 17:20:01 -080035import com.android.server.wm.AppTransition;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080036import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037
Dianne Hackborndd71fc82009-12-16 19:24:32 -080038import dalvik.system.Zygote;
39
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.app.Activity;
41import android.app.ActivityManager;
42import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070043import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.ActivityThread;
45import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070046import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020047import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070049import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.IApplicationThread;
51import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070053import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070055import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.app.IThumbnailReceiver;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080057import android.app.IUiAutomationConnection;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070058import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070060import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070061import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080063import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020064import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080065import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080066import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070067import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070069import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.ContentResolver;
71import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020072import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070073import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070074import android.content.IIntentReceiver;
75import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070076import android.content.Intent;
77import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070078import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.content.pm.ActivityInfo;
80import android.content.pm.ApplicationInfo;
81import android.content.pm.ConfigurationInfo;
82import android.content.pm.IPackageDataObserver;
83import android.content.pm.IPackageManager;
84import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080085import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070087import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070088import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070089import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.content.pm.ProviderInfo;
91import android.content.pm.ResolveInfo;
92import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040093import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.content.res.Configuration;
95import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070096import android.net.Proxy;
97import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.net.Uri;
99import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -0800100import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -0800101import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700102import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -0800103import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800105import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.FileUtils;
107import android.os.Handler;
108import android.os.IBinder;
109import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700110import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700111import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.Looper;
113import android.os.Message;
114import android.os.Parcel;
115import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700117import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400119import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700121import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.os.SystemClock;
123import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700124import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700125import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700127import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800129import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700130import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700132import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700134import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import android.view.Gravity;
136import android.view.LayoutInflater;
137import android.view.View;
138import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700140import java.io.BufferedInputStream;
141import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700143import java.io.DataInputStream;
144import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.File;
146import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700147import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700149import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200150import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800151import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700153import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.lang.ref.WeakReference;
155import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700156import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700157import java.util.Collections;
158import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.util.HashMap;
160import java.util.HashSet;
161import java.util.Iterator;
162import java.util.List;
163import java.util.Locale;
164import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700165import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700166import java.util.concurrent.atomic.AtomicBoolean;
167import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800169public final class ActivityManagerService extends ActivityManagerNative
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700170 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700171 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700173 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400175 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_SWITCH = localLOGV || false;
177 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700178 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_PAUSE = localLOGV || false;
180 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
181 static final boolean DEBUG_TRANSITION = localLOGV || false;
182 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800183 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700184 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean DEBUG_VISBILITY = localLOGV || false;
188 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700189 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700190 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700191 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800192 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700194 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700195 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700196 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700197 static final boolean DEBUG_POWER = localLOGV || false;
198 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700199 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700200 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
Craig Mautner2ad92072013-02-25 16:19:24 -0800201 static final boolean VALIDATE_TOKENS = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 static final boolean SHOW_ACTIVITY_START_TIME = true;
203
204 // Control over CPU and battery monitoring.
205 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
206 static final boolean MONITOR_CPU_USAGE = true;
207 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
208 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
209 static final boolean MONITOR_THREAD_CPU_USAGE = false;
210
Dianne Hackborn1655be42009-05-08 14:29:01 -0700211 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700212 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700213
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800214 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700216 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 // Maximum number of recent tasks that we can remember.
219 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700220
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700221 // Amount of time after a call to stopAppSwitches() during which we will
222 // prevent further untrusted switches from happening.
223 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
225 // How long we wait for a launched process to attach to the activity manager
226 // before we decide it's never going to come up for real.
227 static final int PROC_START_TIMEOUT = 10*1000;
228
Jeff Brown3f9dd282011-07-08 20:02:19 -0700229 // How long we wait for a launched process to attach to the activity manager
230 // before we decide it's never going to come up for real, when the process was
231 // started with a wrapper for instrumentation (such as Valgrind) because it
232 // could take much longer than usual.
233 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 // How long to wait after going idle before forcing apps to GC.
236 static final int GC_TIMEOUT = 5*1000;
237
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700238 // The minimum amount of time between successive GC requests for a process.
239 static final int GC_MIN_INTERVAL = 60*1000;
240
Dianne Hackborn287952c2010-09-22 22:34:31 -0700241 // The rate at which we check for apps using excessive power -- 15 mins.
242 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
243
244 // The minimum sample duration we will allow before deciding we have
245 // enough data on wake locks to start killing things.
246 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
247
248 // The minimum sample duration we will allow before deciding we have
249 // enough data on CPU usage to start killing things.
250 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800253 static final int BROADCAST_FG_TIMEOUT = 10*1000;
254 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // How long we wait until we timeout on key dispatching.
257 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // How long we wait until we timeout on key dispatching during instrumentation.
260 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
261
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700262 // Amount of time we wait for observers to handle a user switch before
263 // giving up on them and unfreezing the screen.
264 static final int USER_SWITCH_TIMEOUT = 2*1000;
265
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700266 // Maximum number of users we allow to be running at a time.
267 static final int MAX_RUNNING_USERS = 3;
268
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800269 // How long to wait in getTopActivityExtras for the activity to respond with the result.
270 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000;
271
Dan Egnor42471dd2010-01-07 17:25:22 -0800272 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 static final String[] EMPTY_STRING_ARRAY = new String[0];
275
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700276 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700277
Ben Gruver4efe9402013-04-02 21:18:41 -0700278 public IntentFirewall mIntentFirewall;
279
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700280 private final boolean mHeadless;
281
Joe Onorato54a4a412011-11-02 20:50:08 -0700282 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
283 // default actuion automatically. Important for devices without direct input
284 // devices.
285 private boolean mShowDialogs = true;
286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700288 * Description of a request to start a new activity, which has been held
289 * due to app switches being disabled.
290 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700291 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700292 ActivityRecord r;
293 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700294 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700295 }
296
297 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
298 = new ArrayList<PendingActivityLaunch>();
299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800301 BroadcastQueue mFgBroadcastQueue;
302 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800303 // Convenient for easy iteration over the queues. Foreground is first
304 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800305 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800306
307 BroadcastQueue broadcastQueueForIntent(Intent intent) {
308 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
309 if (DEBUG_BACKGROUND_BROADCAST) {
310 Slog.i(TAG, "Broadcast intent " + intent + " on "
311 + (isFg ? "foreground" : "background")
312 + " queue");
313 }
314 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
315 }
316
317 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
318 for (BroadcastQueue queue : mBroadcastQueues) {
319 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
320 if (r != null) {
321 return r;
322 }
323 }
324 return null;
325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326
327 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 * Activity we have told the window manager to have key focus.
329 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700330 ActivityRecord mFocusedActivity = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800331
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 * List of intents that were used to start the most recent tasks.
334 */
Craig Mautner2ad92072013-02-25 16:19:24 -0800335 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800337 public class PendingActivityExtras extends Binder implements Runnable {
338 public final ActivityRecord activity;
339 public boolean haveResult = false;
340 public Bundle result = null;
341 public PendingActivityExtras(ActivityRecord _activity) {
342 activity = _activity;
343 }
344 @Override
345 public void run() {
346 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity);
347 synchronized (this) {
348 haveResult = true;
349 notifyAll();
350 }
351 }
352 }
353
354 final ArrayList<PendingActivityExtras> mPendingActivityExtras
355 = new ArrayList<PendingActivityExtras>();
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700358 * Process management.
359 */
360 final ProcessList mProcessList = new ProcessList();
361
362 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363 * All of the applications we currently have running organized by name.
364 * The keys are strings of the application package name (as
365 * returned by the package manager), and the keys are ApplicationRecord
366 * objects.
367 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700368 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800369
370 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800371 * The currently running isolated processes.
372 */
373 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
374
375 /**
376 * Counter for assigning isolated process uids, to avoid frequently reusing the
377 * same ones.
378 */
379 int mNextIsolatedProcessUid = 0;
380
381 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700382 * The currently running heavy-weight process, if any.
383 */
384 ProcessRecord mHeavyWeightProcess = null;
385
386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * The last time that various processes have crashed.
388 */
389 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
390
391 /**
392 * Set of applications that we consider to be bad, and will reject
393 * incoming broadcasts from (which the user has no control over).
394 * Processes are added to this set when they have crashed twice within
395 * a minimum amount of time; they are removed from it when they are
396 * later restarted (hopefully due to some user action). The value is the
397 * time it was added to the list.
398 */
399 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
400
401 /**
402 * All of the processes we currently have running organized by pid.
403 * The keys are the pid running the application.
404 *
405 * <p>NOTE: This object is protected by its own lock, NOT the global
406 * activity manager lock!
407 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700408 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409
410 /**
411 * All of the processes that have been forced to be foreground. The key
412 * is the pid of the caller who requested it (we hold a death
413 * link on it).
414 */
415 abstract class ForegroundToken implements IBinder.DeathRecipient {
416 int pid;
417 IBinder token;
418 }
419 final SparseArray<ForegroundToken> mForegroundProcesses
420 = new SparseArray<ForegroundToken>();
421
422 /**
423 * List of records for processes that someone had tried to start before the
424 * system was ready. We don't start them at that point, but ensure they
425 * are started by the time booting is complete.
426 */
427 final ArrayList<ProcessRecord> mProcessesOnHold
428 = new ArrayList<ProcessRecord>();
429
430 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 * List of persistent applications that are in the process
432 * of being started.
433 */
434 final ArrayList<ProcessRecord> mPersistentStartingProcesses
435 = new ArrayList<ProcessRecord>();
436
437 /**
438 * Processes that are being forcibly torn down.
439 */
440 final ArrayList<ProcessRecord> mRemovedProcesses
441 = new ArrayList<ProcessRecord>();
442
443 /**
444 * List of running applications, sorted by recent usage.
445 * The first entry in the list is the least recently used.
446 * It contains ApplicationRecord objects. This list does NOT include
447 * any persistent application records (since we never want to exit them).
448 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800449 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450 = new ArrayList<ProcessRecord>();
451
452 /**
453 * List of processes that should gc as soon as things are idle.
454 */
455 final ArrayList<ProcessRecord> mProcessesToGc
456 = new ArrayList<ProcessRecord>();
457
458 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800459 * This is the process holding what we currently consider to be
460 * the "home" activity.
461 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700462 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800463
464 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700465 * This is the process holding the activity the user last visited that
466 * is in a different process from the one they are currently in.
467 */
468 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800469
470 /**
471 * The time at which the previous process was last visible.
472 */
473 long mPreviousProcessVisibleTime;
474
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700475 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700476 * Which uses have been started, so are allowed to run code.
477 */
478 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
479
480 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700481 * LRU list of history of current users. Most recently current is at the end.
482 */
483 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
484
485 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700486 * Constant array of the users that are currently started.
487 */
488 int[] mStartedUserArray = new int[] { 0 };
489
490 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700491 * Registered observers of the user switching mechanics.
492 */
493 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
494 = new RemoteCallbackList<IUserSwitchObserver>();
495
496 /**
497 * Currently active user switch.
498 */
499 Object mCurUserSwitchCallback;
500
501 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400502 * Packages that the user has asked to have run in screen size
503 * compatibility mode instead of filling the screen.
504 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700505 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400506
507 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 * Set of PendingResultRecord objects that are currently active.
509 */
510 final HashSet mPendingResultRecords = new HashSet();
511
512 /**
513 * Set of IntentSenderRecord objects that are currently active.
514 */
515 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
516 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
517
518 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800519 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700520 * already logged DropBox entries for. Guarded by itself. If
521 * something (rogue user app) forces this over
522 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
523 */
524 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
525 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
526
527 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700528 * Strict Mode background batched logging state.
529 *
530 * The string buffer is guarded by itself, and its lock is also
531 * used to determine if another batched write is already
532 * in-flight.
533 */
534 private final StringBuilder mStrictModeBuffer = new StringBuilder();
535
536 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 * Keeps track of all IIntentReceivers that have been registered for
538 * broadcasts. Hash keys are the receiver IBinder, hash value is
539 * a ReceiverList.
540 */
541 final HashMap mRegisteredReceivers = new HashMap();
542
543 /**
544 * Resolver for broadcast intents to registered receivers.
545 * Holds BroadcastFilter (subclass of IntentFilter).
546 */
547 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
548 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
549 @Override
550 protected boolean allowFilterResult(
551 BroadcastFilter filter, List<BroadcastFilter> dest) {
552 IBinder target = filter.receiverList.receiver.asBinder();
553 for (int i=dest.size()-1; i>=0; i--) {
554 if (dest.get(i).receiverList.receiver.asBinder() == target) {
555 return false;
556 }
557 }
558 return true;
559 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700560
561 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700562 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700563 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
564 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700565 return super.newResult(filter, match, userId);
566 }
567 return null;
568 }
569
570 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700571 protected BroadcastFilter[] newArray(int size) {
572 return new BroadcastFilter[size];
573 }
574
575 @Override
Ben Gruver4efe9402013-04-02 21:18:41 -0700576 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) {
577 return packageName.equals(filter.packageName);
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 };
580
581 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700582 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700584 * that action (which should usually be one). The SparseArray is keyed
585 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
586 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700588 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
589 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700591 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592
593 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700594 * Backup/restore process management
595 */
596 String mBackupAppName = null;
597 BackupRecord mBackupTarget = null;
598
599 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 * List of PendingThumbnailsRecord objects of clients who are still
601 * waiting to receive all of the thumbnails for a task.
602 */
Craig Mautner2ad92072013-02-25 16:19:24 -0800603 final ArrayList mPendingThumbnails = new ArrayList();
604
605 /**
606 * List of HistoryRecord objects that have been finished and must
607 * still report back to a pending thumbnail receiver.
608 */
609 final ArrayList mCancelledThumbnails = new ArrayList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700611 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 /**
614 * List of content providers who have clients waiting for them. The
615 * application is currently being launched and the provider will be
616 * removed from this list once it is published.
617 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700618 final ArrayList<ContentProviderRecord> mLaunchingProviders
619 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
621 /**
622 * Global set of specific Uri permissions that have been granted.
623 */
624 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
625 = new SparseArray<HashMap<Uri, UriPermission>>();
626
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800627 CoreSettingsObserver mCoreSettingsObserver;
628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 /**
630 * Thread-local storage used to carry caller permissions over through
631 * indirect content-provider access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 */
633 private class Identity {
634 public int pid;
635 public int uid;
636
637 Identity(int _pid, int _uid) {
638 pid = _pid;
639 uid = _uid;
640 }
641 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800643 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
644
645 /**
646 * All information we have collected about the runtime performance of
647 * any user id that can impact battery performance.
648 */
649 final BatteryStatsService mBatteryStatsService;
650
651 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800652 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 */
654 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800655
656 /**
657 * Information about and control over application operations
658 */
659 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660
661 /**
662 * Current configuration information. HistoryRecord objects are given
663 * a reference to this object to indicate which configuration they are
664 * currently running in, so this object must be kept immutable.
665 */
666 Configuration mConfiguration = new Configuration();
667
668 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800669 * Current sequencing integer of the configuration, for skipping old
670 * configurations.
671 */
672 int mConfigurationSeq = 0;
673
674 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700675 * Hardware-reported OpenGLES version.
676 */
677 final int GL_ES_VERSION;
678
679 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680 * List of initialization arguments to pass to all processes when binding applications to them.
681 * For example, references to the commonly used services.
682 */
683 HashMap<String, IBinder> mAppBindArgs;
684
685 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700686 * Temporary to avoid allocations. Protected by main lock.
687 */
688 final StringBuilder mStringBuilder = new StringBuilder(256);
689
690 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800691 * Used to control how we initialize the service.
692 */
693 boolean mStartRunning = false;
694 ComponentName mTopComponent;
695 String mTopAction;
696 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700697 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800698 boolean mSystemReady = false;
699 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700700 boolean mWaitingUpdate = false;
701 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700702 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700703 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704
705 Context mContext;
706
707 int mFactoryTest;
708
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700709 boolean mCheckedForSetup;
710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700712 * The time at which we will allow normal application switches again,
713 * after a call to {@link #stopAppSwitches()}.
714 */
715 long mAppSwitchesAllowedTime;
716
717 /**
718 * This is set to true after the first switch after mAppSwitchesAllowedTime
719 * is set; any switches after that will clear the time.
720 */
721 boolean mDidAppSwitch;
722
723 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700724 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700725 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700726 long mLastPowerCheckRealtime;
727
728 /**
729 * Last time (in uptime) at which we checked for power usage.
730 */
731 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700732
733 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 * Set while we are wanting to sleep, to prevent any
735 * activities from being started/resumed.
736 */
737 boolean mSleeping = false;
738
739 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700740 * State of external calls telling us if the device is asleep.
741 */
742 boolean mWentToSleep = false;
743
744 /**
745 * State of external call telling us if the lock screen is shown.
746 */
747 boolean mLockScreenShown = false;
748
749 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700750 * Set if we are shutting down the system, similar to sleeping.
751 */
752 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753
754 /**
755 * Task identifier that activities are currently being started
756 * in. Incremented each time a new task is created.
757 * todo: Replace this with a TokenSpace class that generates non-repeating
758 * integers that won't wrap.
759 */
760 int mCurTask = 1;
761
762 /**
763 * Current sequence id for oom_adj computation traversal.
764 */
765 int mAdjSeq = 0;
766
767 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700768 * Current sequence id for process LRU updating.
769 */
770 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771
772 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700773 * Keep track of the non-hidden/empty process we last found, to help
774 * determine how to distribute hidden/empty processes next time.
775 */
776 int mNumNonHiddenProcs = 0;
777
778 /**
779 * Keep track of the number of hidden procs, to balance oom adj
780 * distribution between those and empty procs.
781 */
782 int mNumHiddenProcs = 0;
783
784 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700785 * Keep track of the number of service processes we last found, to
786 * determine on the next iteration which should be B services.
787 */
788 int mNumServiceProcs = 0;
789 int mNewNumServiceProcs = 0;
790
791 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 * System monitoring: number of processes that died since the last
793 * N procs were started.
794 */
795 int[] mProcDeaths = new int[20];
796
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700797 /**
798 * This is set if we had to do a delayed dexopt of an app before launching
799 * it, to increasing the ANR timeouts in that case.
800 */
801 boolean mDidDexOpt;
802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 String mDebugApp = null;
804 boolean mWaitForDebugger = false;
805 boolean mDebugTransient = false;
806 String mOrigDebugApp = null;
807 boolean mOrigWaitForDebugger = false;
808 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700809 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700810 String mProfileApp = null;
811 ProcessRecord mProfileProc = null;
812 String mProfileFile;
813 ParcelFileDescriptor mProfileFd;
814 int mProfileType = 0;
815 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800816 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700818 static class ProcessChangeItem {
819 static final int CHANGE_ACTIVITIES = 1<<0;
820 static final int CHANGE_IMPORTANCE= 1<<1;
821 int changes;
822 int uid;
823 int pid;
824 int importance;
825 boolean foregroundActivities;
826 }
827
Jeff Sharkeya4620792011-05-20 15:29:23 -0700828 final RemoteCallbackList<IProcessObserver> mProcessObservers
829 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700830 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
831
832 final ArrayList<ProcessChangeItem> mPendingProcessChanges
833 = new ArrayList<ProcessChangeItem>();
834 final ArrayList<ProcessChangeItem> mAvailProcessChanges
835 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 * Runtime statistics collection thread. This object's lock is used to
839 * protect all related state.
840 */
841 final Thread mProcessStatsThread;
842
843 /**
844 * Used to collect process stats when showing not responding dialog.
845 * Protected by mProcessStatsThread.
846 */
847 final ProcessStats mProcessStats = new ProcessStats(
848 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700849 final AtomicLong mLastCpuTime = new AtomicLong(0);
850 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 long mLastWriteTime = 0;
853
854 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700855 * Used to retain an update lock when the foreground activity is in
856 * immersive mode.
857 */
858 final UpdateLock mUpdateLock = new UpdateLock("immersive");
859
860 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 * Set to true after the system has finished booting.
862 */
863 boolean mBooted = false;
864
Dianne Hackborn7d608422011-08-07 16:24:18 -0700865 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700866 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867
868 WindowManagerService mWindowManager;
869
870 static ActivityManagerService mSelf;
871 static ActivityThread mSystemThread;
872
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700873 private int mCurrentUserId = 0;
874 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700875 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 private final class AppDeathRecipient implements IBinder.DeathRecipient {
878 final ProcessRecord mApp;
879 final int mPid;
880 final IApplicationThread mAppThread;
881
882 AppDeathRecipient(ProcessRecord app, int pid,
883 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800884 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 TAG, "New death recipient " + this
886 + " for thread " + thread.asBinder());
887 mApp = app;
888 mPid = pid;
889 mAppThread = thread;
890 }
891
892 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800893 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 TAG, "Death received in " + this
895 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 synchronized(ActivityManagerService.this) {
897 appDiedLocked(mApp, mPid, mAppThread);
898 }
899 }
900 }
901
902 static final int SHOW_ERROR_MSG = 1;
903 static final int SHOW_NOT_RESPONDING_MSG = 2;
904 static final int SHOW_FACTORY_ERROR_MSG = 3;
905 static final int UPDATE_CONFIGURATION_MSG = 4;
906 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
907 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 static final int SERVICE_TIMEOUT_MSG = 12;
909 static final int UPDATE_TIME_ZONE = 13;
910 static final int SHOW_UID_ERROR_MSG = 14;
911 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700913 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700914 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800915 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700916 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
917 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700918 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700919 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700920 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700921 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700922 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700923 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700924 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700925 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700926 static final int REPORT_USER_SWITCH_MSG = 34;
927 static final int CONTINUE_USER_SWITCH_MSG = 35;
928 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700929 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800931 static final int FIRST_ACTIVITY_STACK_MSG = 100;
932 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
933 static final int FIRST_COMPAT_MODE_MSG = 300;
934
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700936 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700937 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938
Adam Momtaz8f6f1f42013-04-10 12:42:58 -0700939 /**
940 * Flag whether the current user is a "monkey", i.e. whether
941 * the UI is driven by a UI automation tool.
942 */
943 private boolean mUserIsMonkey;
944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 final Handler mHandler = new Handler() {
946 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800947 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 //}
949
950 public void handleMessage(Message msg) {
951 switch (msg.what) {
952 case SHOW_ERROR_MSG: {
953 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700954 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
955 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 synchronized (ActivityManagerService.this) {
957 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700958 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800960 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700961 if (res != null) {
962 res.set(0);
963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 return;
965 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700966 if (!showBackground && UserHandle.getAppId(proc.uid)
967 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
968 && proc.pid != MY_PID) {
969 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
970 if (res != null) {
971 res.set(0);
972 }
973 return;
974 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700975 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700976 Dialog d = new AppErrorDialog(mContext,
977 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800978 d.show();
979 proc.crashDialog = d;
980 } else {
981 // The device is asleep, so just pretend that the user
982 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700983 if (res != null) {
984 res.set(0);
985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 }
987 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700988
989 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 } break;
991 case SHOW_NOT_RESPONDING_MSG: {
992 synchronized (ActivityManagerService.this) {
993 HashMap data = (HashMap) msg.obj;
994 ProcessRecord proc = (ProcessRecord)data.get("app");
995 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800996 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 return;
998 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800999
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001000 Intent intent = new Intent("android.intent.action.ANR");
1001 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -08001002 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1003 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001004 }
1005 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08001006 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -07001007 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -08001008
Justin Kohbc52ca22012-03-29 15:11:44 -07001009 if (mShowDialogs) {
1010 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07001011 mContext, proc, (ActivityRecord)data.get("activity"),
1012 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -07001013 d.show();
1014 proc.anrDialog = d;
1015 } else {
1016 // Just kill the app if there is no dialog to be shown.
1017 killAppAtUsersRequest(proc, null);
1018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001020
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001021 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001023 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1024 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1025 synchronized (ActivityManagerService.this) {
1026 ProcessRecord proc = (ProcessRecord) data.get("app");
1027 if (proc == null) {
1028 Slog.e(TAG, "App not found when showing strict mode dialog.");
1029 break;
1030 }
1031 if (proc.crashDialog != null) {
1032 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1033 return;
1034 }
1035 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001036 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001037 Dialog d = new StrictModeViolationDialog(mContext,
1038 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001039 d.show();
1040 proc.crashDialog = d;
1041 } else {
1042 // The device is asleep, so just pretend that the user
1043 // saw a crash dialog and hit "force quit".
1044 res.set(0);
1045 }
1046 }
1047 ensureBootCompleted();
1048 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 case SHOW_FACTORY_ERROR_MSG: {
1050 Dialog d = new FactoryErrorDialog(
1051 mContext, msg.getData().getCharSequence("msg"));
1052 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001053 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 } break;
1055 case UPDATE_CONFIGURATION_MSG: {
1056 final ContentResolver resolver = mContext.getContentResolver();
1057 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1058 } break;
1059 case GC_BACKGROUND_PROCESSES_MSG: {
1060 synchronized (ActivityManagerService.this) {
1061 performAppGcsIfAppropriateLocked();
1062 }
1063 } break;
1064 case WAIT_FOR_DEBUGGER_MSG: {
1065 synchronized (ActivityManagerService.this) {
1066 ProcessRecord app = (ProcessRecord)msg.obj;
1067 if (msg.arg1 != 0) {
1068 if (!app.waitedForDebugger) {
1069 Dialog d = new AppWaitingForDebuggerDialog(
1070 ActivityManagerService.this,
1071 mContext, app);
1072 app.waitDialog = d;
1073 app.waitedForDebugger = true;
1074 d.show();
1075 }
1076 } else {
1077 if (app.waitDialog != null) {
1078 app.waitDialog.dismiss();
1079 app.waitDialog = null;
1080 }
1081 }
1082 }
1083 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001085 if (mDidDexOpt) {
1086 mDidDexOpt = false;
1087 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1088 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001089 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001090 return;
1091 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001092 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 } break;
1094 case UPDATE_TIME_ZONE: {
1095 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001096 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1097 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 if (r.thread != null) {
1099 try {
1100 r.thread.updateTimeZone();
1101 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001102 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 }
1104 }
1105 }
1106 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001107 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001108 case CLEAR_DNS_CACHE: {
1109 synchronized (ActivityManagerService.this) {
1110 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1111 ProcessRecord r = mLruProcesses.get(i);
1112 if (r.thread != null) {
1113 try {
1114 r.thread.clearDnsCache();
1115 } catch (RemoteException ex) {
1116 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1117 }
1118 }
1119 }
1120 }
1121 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001122 case UPDATE_HTTP_PROXY: {
1123 ProxyProperties proxy = (ProxyProperties)msg.obj;
1124 String host = "";
1125 String port = "";
1126 String exclList = "";
1127 if (proxy != null) {
1128 host = proxy.getHost();
1129 port = Integer.toString(proxy.getPort());
1130 exclList = proxy.getExclusionList();
1131 }
1132 synchronized (ActivityManagerService.this) {
1133 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1134 ProcessRecord r = mLruProcesses.get(i);
1135 if (r.thread != null) {
1136 try {
1137 r.thread.setHttpProxy(host, port, exclList);
1138 } catch (RemoteException ex) {
1139 Slog.w(TAG, "Failed to update http proxy for: " +
1140 r.info.processName);
1141 }
1142 }
1143 }
1144 }
1145 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001147 String title = "System UIDs Inconsistent";
1148 String text = "UIDs on the system are inconsistent, you need to wipe your"
1149 + " data partition or your device will be unstable.";
1150 Log.e(TAG, title + ": " + text);
1151 if (mShowDialogs) {
1152 // XXX This is a temporary dialog, no need to localize.
1153 AlertDialog d = new BaseErrorDialog(mContext);
1154 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1155 d.setCancelable(false);
1156 d.setTitle(title);
1157 d.setMessage(text);
1158 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1159 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1160 mUidAlert = d;
1161 d.show();
1162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 } break;
1164 case IM_FEELING_LUCKY_MSG: {
1165 if (mUidAlert != null) {
1166 mUidAlert.dismiss();
1167 mUidAlert = null;
1168 }
1169 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001171 if (mDidDexOpt) {
1172 mDidDexOpt = false;
1173 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1174 nmsg.obj = msg.obj;
1175 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1176 return;
1177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 ProcessRecord app = (ProcessRecord)msg.obj;
1179 synchronized (ActivityManagerService.this) {
1180 processStartTimedOutLocked(app);
1181 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001182 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001183 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1184 synchronized (ActivityManagerService.this) {
1185 doPendingActivityLaunchesLocked(true);
1186 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001187 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001188 case KILL_APPLICATION_MSG: {
1189 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001190 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001191 boolean restart = (msg.arg2 == 1);
1192 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001193 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1194 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001195 }
1196 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001197 case FINALIZE_PENDING_INTENT_MSG: {
1198 ((PendingIntentRecord)msg.obj).completeFinalize();
1199 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001200 case POST_HEAVY_NOTIFICATION_MSG: {
1201 INotificationManager inm = NotificationManager.getService();
1202 if (inm == null) {
1203 return;
1204 }
1205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001206 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001207 ProcessRecord process = root.app;
1208 if (process == null) {
1209 return;
1210 }
1211
1212 try {
1213 Context context = mContext.createPackageContext(process.info.packageName, 0);
1214 String text = mContext.getString(R.string.heavy_weight_notification,
1215 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1216 Notification notification = new Notification();
1217 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1218 notification.when = 0;
1219 notification.flags = Notification.FLAG_ONGOING_EVENT;
1220 notification.tickerText = text;
1221 notification.defaults = 0; // please be quiet
1222 notification.sound = null;
1223 notification.vibrate = null;
1224 notification.setLatestEventInfo(context, text,
1225 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001226 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1227 PendingIntent.FLAG_CANCEL_CURRENT, null,
1228 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001229
1230 try {
1231 int[] outId = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001232 inm.enqueueNotificationWithTag("android", "android", null,
Dianne Hackborn41203752012-08-31 14:05:51 -07001233 R.string.heavy_weight_notification,
1234 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001235 } catch (RuntimeException e) {
1236 Slog.w(ActivityManagerService.TAG,
1237 "Error showing notification for heavy-weight app", e);
1238 } catch (RemoteException e) {
1239 }
1240 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001241 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001242 }
1243 } break;
1244 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1245 INotificationManager inm = NotificationManager.getService();
1246 if (inm == null) {
1247 return;
1248 }
1249 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001250 inm.cancelNotificationWithTag("android", null,
1251 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001252 } catch (RuntimeException e) {
1253 Slog.w(ActivityManagerService.TAG,
1254 "Error canceling notification for service", e);
1255 } catch (RemoteException e) {
1256 }
1257 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001258 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1259 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001260 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001261 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001262 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1263 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001264 }
1265 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001266 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1267 synchronized (ActivityManagerService.this) {
1268 ActivityRecord ar = (ActivityRecord)msg.obj;
1269 if (mCompatModeDialog != null) {
1270 if (mCompatModeDialog.mAppInfo.packageName.equals(
1271 ar.info.applicationInfo.packageName)) {
1272 return;
1273 }
1274 mCompatModeDialog.dismiss();
1275 mCompatModeDialog = null;
1276 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001277 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001278 if (mCompatModePackages.getPackageAskCompatModeLocked(
1279 ar.packageName)) {
1280 int mode = mCompatModePackages.computeCompatModeLocked(
1281 ar.info.applicationInfo);
1282 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1283 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1284 mCompatModeDialog = new CompatModeDialog(
1285 ActivityManagerService.this, mContext,
1286 ar.info.applicationInfo);
1287 mCompatModeDialog.show();
1288 }
1289 }
1290 }
1291 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001292 break;
1293 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001294 case DISPATCH_PROCESSES_CHANGED: {
1295 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001296 break;
1297 }
1298 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001299 final int pid = msg.arg1;
1300 final int uid = msg.arg2;
1301 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001302 break;
1303 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001304 case REPORT_MEM_USAGE: {
1305 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1306 if (!isDebuggable) {
1307 return;
1308 }
1309 synchronized (ActivityManagerService.this) {
1310 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001311 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1312 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001313 // avoid spamming.
1314 return;
1315 }
1316 mLastMemUsageReportTime = now;
1317 }
1318 Thread thread = new Thread() {
1319 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001320 StringBuilder dropBuilder = new StringBuilder(1024);
1321 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001322 StringWriter oomSw = new StringWriter();
1323 PrintWriter oomPw = new PrintWriter(oomSw);
1324 StringWriter catSw = new StringWriter();
1325 PrintWriter catPw = new PrintWriter(catSw);
1326 String[] emptyArgs = new String[] { };
1327 StringBuilder tag = new StringBuilder(128);
1328 StringBuilder stack = new StringBuilder(128);
1329 tag.append("Low on memory -- ");
1330 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1331 tag, stack);
1332 dropBuilder.append(stack);
1333 dropBuilder.append('\n');
1334 dropBuilder.append('\n');
1335 String oomString = oomSw.toString();
1336 dropBuilder.append(oomString);
1337 dropBuilder.append('\n');
1338 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001339 try {
1340 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1341 "procrank", });
1342 final InputStreamReader converter = new InputStreamReader(
1343 proc.getInputStream());
1344 BufferedReader in = new BufferedReader(converter);
1345 String line;
1346 while (true) {
1347 line = in.readLine();
1348 if (line == null) {
1349 break;
1350 }
1351 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001352 logBuilder.append(line);
1353 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001354 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001355 dropBuilder.append(line);
1356 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001357 }
1358 converter.close();
1359 } catch (IOException e) {
1360 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001361 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001362 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001363 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001364 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001365 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1366 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001367 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001368 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001369 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001370 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001371 addErrorToDropBox("lowmem", null, "system_server", null,
1372 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001373 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001374 synchronized (ActivityManagerService.this) {
1375 long now = SystemClock.uptimeMillis();
1376 if (mLastMemUsageReportTime < now) {
1377 mLastMemUsageReportTime = now;
1378 }
1379 }
1380 }
1381 };
1382 thread.start();
1383 break;
1384 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001385 case REPORT_USER_SWITCH_MSG: {
1386 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1387 break;
1388 }
1389 case CONTINUE_USER_SWITCH_MSG: {
1390 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1391 break;
1392 }
1393 case USER_SWITCH_TIMEOUT_MSG: {
1394 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1395 break;
1396 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001397 case IMMERSIVE_MODE_LOCK_MSG: {
1398 final boolean nextState = (msg.arg1 != 0);
1399 if (mUpdateLock.isHeld() != nextState) {
1400 if (DEBUG_IMMERSIVE) {
1401 final ActivityRecord r = (ActivityRecord) msg.obj;
1402 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1403 }
1404 if (nextState) {
1405 mUpdateLock.acquire();
1406 } else {
1407 mUpdateLock.release();
1408 }
1409 }
1410 break;
1411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 }
1413 }
1414 };
1415
1416 public static void setSystemProcess() {
1417 try {
1418 ActivityManagerService m = mSelf;
Christopher Tate58d380d2013-03-19 13:10:03 -07001419
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001420 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001422 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001423 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (MONITOR_CPU_USAGE) {
1425 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 ServiceManager.addService("permission", new PermissionController(m));
1428
1429 ApplicationInfo info =
1430 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001431 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001432 mSystemThread.installSystemApplicationInfo(info);
1433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 synchronized (mSelf) {
1435 ProcessRecord app = mSelf.newProcessRecordLocked(
1436 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001437 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001439 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001440 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001441 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 synchronized (mSelf.mPidsSelfLocked) {
1443 mSelf.mPidsSelfLocked.put(app.pid, app);
1444 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001445 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447 } catch (PackageManager.NameNotFoundException e) {
1448 throw new RuntimeException(
1449 "Unable to find android system package", e);
1450 }
1451 }
1452
1453 public void setWindowManager(WindowManagerService wm) {
1454 mWindowManager = wm;
1455 }
1456
Christopher Tate58d380d2013-03-19 13:10:03 -07001457 public void startObservingNativeCrashes() {
1458 final NativeCrashListener ncl = new NativeCrashListener();
1459 ncl.start();
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 public static final Context main(int factoryTest) {
1463 AThread thr = new AThread();
1464 thr.start();
1465
1466 synchronized (thr) {
1467 while (thr.mService == null) {
1468 try {
1469 thr.wait();
1470 } catch (InterruptedException e) {
1471 }
1472 }
1473 }
1474
1475 ActivityManagerService m = thr.mService;
1476 mSelf = m;
1477 ActivityThread at = ActivityThread.systemMain();
1478 mSystemThread = at;
1479 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001480 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 m.mContext = context;
1482 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001483 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
Ben Gruver4efe9402013-04-02 21:18:41 -07001484 m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface());
1485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 m.mBatteryStatsService.publish(context);
1487 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001488 m.mAppOpsService.publish(context);
1489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 synchronized (thr) {
1491 thr.mReady = true;
1492 thr.notifyAll();
1493 }
1494
1495 m.startRunning(null, null, null, null);
1496
1497 return context;
1498 }
1499
1500 public static ActivityManagerService self() {
1501 return mSelf;
1502 }
1503
1504 static class AThread extends Thread {
1505 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001506 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 boolean mReady = false;
1508
1509 public AThread() {
1510 super("ActivityManager");
1511 }
1512
1513 public void run() {
1514 Looper.prepare();
1515
1516 android.os.Process.setThreadPriority(
1517 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001518 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
1520 ActivityManagerService m = new ActivityManagerService();
1521
1522 synchronized (this) {
1523 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001524 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 notifyAll();
1526 }
1527
1528 synchronized (this) {
1529 while (!mReady) {
1530 try {
1531 wait();
1532 } catch (InterruptedException e) {
1533 }
1534 }
1535 }
1536
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001537 // For debug builds, log event loop stalls to dropbox for analysis.
1538 if (StrictMode.conditionallyEnableDebugLogging()) {
1539 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1540 }
1541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 Looper.loop();
1543 }
1544 }
1545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 static class MemBinder extends Binder {
1547 ActivityManagerService mActivityManagerService;
1548 MemBinder(ActivityManagerService activityManagerService) {
1549 mActivityManagerService = activityManagerService;
1550 }
1551
1552 @Override
1553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001554 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1555 != PackageManager.PERMISSION_GRANTED) {
1556 pw.println("Permission Denial: can't dump meminfo from from pid="
1557 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1558 + " without permission " + android.Manifest.permission.DUMP);
1559 return;
1560 }
1561
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001562 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001563 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 }
1566
Chet Haase9c1e23b2011-03-24 10:51:31 -07001567 static class GraphicsBinder extends Binder {
1568 ActivityManagerService mActivityManagerService;
1569 GraphicsBinder(ActivityManagerService activityManagerService) {
1570 mActivityManagerService = activityManagerService;
1571 }
1572
1573 @Override
1574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001575 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1576 != PackageManager.PERMISSION_GRANTED) {
1577 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1578 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1579 + " without permission " + android.Manifest.permission.DUMP);
1580 return;
1581 }
1582
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001583 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001584 }
1585 }
1586
Jeff Brown6754ba22011-12-14 20:20:01 -08001587 static class DbBinder extends Binder {
1588 ActivityManagerService mActivityManagerService;
1589 DbBinder(ActivityManagerService activityManagerService) {
1590 mActivityManagerService = activityManagerService;
1591 }
1592
1593 @Override
1594 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1595 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1596 != PackageManager.PERMISSION_GRANTED) {
1597 pw.println("Permission Denial: can't dump dbinfo from from pid="
1598 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1599 + " without permission " + android.Manifest.permission.DUMP);
1600 return;
1601 }
1602
1603 mActivityManagerService.dumpDbInfo(fd, pw, args);
1604 }
1605 }
1606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 static class CpuBinder extends Binder {
1608 ActivityManagerService mActivityManagerService;
1609 CpuBinder(ActivityManagerService activityManagerService) {
1610 mActivityManagerService = activityManagerService;
1611 }
1612
1613 @Override
1614 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001615 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1616 != PackageManager.PERMISSION_GRANTED) {
1617 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1618 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1619 + " without permission " + android.Manifest.permission.DUMP);
1620 return;
1621 }
1622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001624 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1625 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1626 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627 }
1628 }
1629 }
1630
1631 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001632 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001633
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001634 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1635 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1636 mBroadcastQueues[0] = mFgBroadcastQueue;
1637 mBroadcastQueues[1] = mBgBroadcastQueue;
1638
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001639 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001640 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 File dataDir = Environment.getDataDirectory();
1643 File systemDir = new File(dataDir, "system");
1644 systemDir.mkdirs();
1645 mBatteryStatsService = new BatteryStatsService(new File(
1646 systemDir, "batterystats.bin").toString());
1647 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001648 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001649 mOnBattery = DEBUG_POWER ? true
1650 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001651 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001652
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001653 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001654 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001655 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001656 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001658 // User 0 is the first and only user that runs at boot.
1659 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001660 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001661 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001662
Jack Palevichb90d28c2009-07-22 15:35:24 -07001663 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1664 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1665
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001666 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001667 mConfiguration.setLocale(Locale.getDefault());
1668
Dianne Hackborn813075a62011-11-14 17:45:19 -08001669 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 mProcessStats.init();
1671
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001672 mCompatModePackages = new CompatModePackages(this, systemDir);
1673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 // Add ourself to the Watchdog monitors.
1675 Watchdog.getInstance().addMonitor(this);
1676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 mProcessStatsThread = new Thread("ProcessStats") {
1678 public void run() {
1679 while (true) {
1680 try {
1681 try {
1682 synchronized(this) {
1683 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001684 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001686 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 // + ", write delay=" + nextWriteDelay);
1688 if (nextWriteDelay < nextCpuDelay) {
1689 nextCpuDelay = nextWriteDelay;
1690 }
1691 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001692 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 this.wait(nextCpuDelay);
1694 }
1695 }
1696 } catch (InterruptedException e) {
1697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 updateCpuStatsNow();
1699 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001700 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
1703 }
1704 };
1705 mProcessStatsThread.start();
1706 }
1707
1708 @Override
1709 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1710 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001711 if (code == SYSPROPS_TRANSACTION) {
1712 // We need to tell all apps about the system property change.
1713 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1714 synchronized(this) {
1715 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1716 final int NA = apps.size();
1717 for (int ia=0; ia<NA; ia++) {
1718 ProcessRecord app = apps.valueAt(ia);
1719 if (app.thread != null) {
1720 procs.add(app.thread.asBinder());
1721 }
1722 }
1723 }
1724 }
1725
1726 int N = procs.size();
1727 for (int i=0; i<N; i++) {
1728 Parcel data2 = Parcel.obtain();
1729 try {
1730 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1731 } catch (RemoteException e) {
1732 }
1733 data2.recycle();
1734 }
1735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 try {
1737 return super.onTransact(code, data, reply, flags);
1738 } catch (RuntimeException e) {
1739 // The activity manager only throws security exceptions, so let's
1740 // log all others.
1741 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001742 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744 throw e;
1745 }
1746 }
1747
1748 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001749 final long now = SystemClock.uptimeMillis();
1750 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1751 return;
1752 }
1753 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1754 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 mProcessStatsThread.notify();
1756 }
1757 }
1758 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 void updateCpuStatsNow() {
1761 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001762 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001763 final long now = SystemClock.uptimeMillis();
1764 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001767 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1768 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 haveNewCpuStats = true;
1770 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001771 //Slog.i(TAG, mProcessStats.printCurrentState());
1772 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 // + mProcessStats.getTotalCpuPercent() + "%");
1774
Joe Onorato8a9b2202010-02-26 18:56:32 -08001775 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 if ("true".equals(SystemProperties.get("events.cpu"))) {
1777 int user = mProcessStats.getLastUserTime();
1778 int system = mProcessStats.getLastSystemTime();
1779 int iowait = mProcessStats.getLastIoWaitTime();
1780 int irq = mProcessStats.getLastIrqTime();
1781 int softIrq = mProcessStats.getLastSoftIrqTime();
1782 int idle = mProcessStats.getLastIdleTime();
1783
1784 int total = user + system + iowait + irq + softIrq + idle;
1785 if (total == 0) total = 1;
1786
Doug Zongker2bec3d42009-12-04 12:52:44 -08001787 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 ((user+system+iowait+irq+softIrq) * 100) / total,
1789 (user * 100) / total,
1790 (system * 100) / total,
1791 (iowait * 100) / total,
1792 (irq * 100) / total,
1793 (softIrq * 100) / total);
1794 }
1795 }
1796
Amith Yamasanie43530a2009-08-21 13:11:37 -07001797 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001798 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001799 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 synchronized(mPidsSelfLocked) {
1801 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001802 if (mOnBattery) {
1803 int perc = bstats.startAddingCpuLocked();
1804 int totalUTime = 0;
1805 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001806 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001808 ProcessStats.Stats st = mProcessStats.getStats(i);
1809 if (!st.working) {
1810 continue;
1811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001813 int otherUTime = (st.rel_utime*perc)/100;
1814 int otherSTime = (st.rel_stime*perc)/100;
1815 totalUTime += otherUTime;
1816 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 if (pr != null) {
1818 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001819 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1820 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001821 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001822 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001823 } else {
1824 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001825 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001826 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001827 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1828 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001829 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001833 bstats.finishAddingCpuLocked(perc, totalUTime,
1834 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 }
1837 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1840 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001841 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843 }
1844 }
1845 }
1846
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001847 @Override
1848 public void batteryNeedsCpuUpdate() {
1849 updateCpuStatsNow();
1850 }
1851
1852 @Override
1853 public void batteryPowerChanged(boolean onBattery) {
1854 // When plugging in, update the CPU stats first before changing
1855 // the plug state.
1856 updateCpuStatsNow();
1857 synchronized (this) {
1858 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001859 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001860 }
1861 }
1862 }
1863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 /**
1865 * Initialize the application bind args. These are passed to each
1866 * process when the bindApplication() IPC is sent to the process. They're
1867 * lazily setup to make sure the services are running when they're asked for.
1868 */
1869 private HashMap<String, IBinder> getCommonServicesLocked() {
1870 if (mAppBindArgs == null) {
1871 mAppBindArgs = new HashMap<String, IBinder>();
1872
1873 // Setup the application init args
1874 mAppBindArgs.put("package", ServiceManager.getService("package"));
1875 mAppBindArgs.put("window", ServiceManager.getService("window"));
1876 mAppBindArgs.put(Context.ALARM_SERVICE,
1877 ServiceManager.getService(Context.ALARM_SERVICE));
1878 }
1879 return mAppBindArgs;
1880 }
1881
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001882 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 if (mFocusedActivity != r) {
1884 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001885 if (r != null) {
1886 mWindowManager.setFocusedApp(r.appToken, true);
1887 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001888 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
1890 }
1891
Christopher Tate73c2aee2012-03-15 16:27:14 -07001892 final void applyUpdateLockStateLocked(ActivityRecord r) {
1893 // Modifications to the UpdateLock state are done on our handler, outside
1894 // the activity manager's locks. The new state is determined based on the
1895 // state *now* of the relevant activity record. The object is passed to
1896 // the handler solely for logging detail, not to be consulted/modified.
1897 final boolean nextState = r != null && r.immersive;
1898 mHandler.sendMessage(
1899 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1900 }
1901
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001902 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001904 int lrui = mLruProcesses.indexOf(app);
1905 if (lrui >= 0) mLruProcesses.remove(lrui);
1906
1907 int i = mLruProcesses.size()-1;
1908 int skipTop = 0;
1909
Dianne Hackborn906497c2010-05-10 15:57:38 -07001910 app.lruSeq = mLruSeq;
1911
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001912 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001913 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001914 if (app.activities.size() > 0) {
1915 // If this process has activities, we more strongly want to keep
1916 // it around.
1917 app.lruWeight = app.lastActivityTime;
1918 } else if (app.pubProviders.size() > 0) {
1919 // If this process contains content providers, we want to keep
1920 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001921 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001922 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001923 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001924 } else {
1925 // If this process doesn't have activities, we less strongly
1926 // want to keep it around, and generally want to avoid getting
1927 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001928 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001929 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001930 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001931 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001932
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001933 while (i >= 0) {
1934 ProcessRecord p = mLruProcesses.get(i);
1935 // If this app shouldn't be in front of the first N background
1936 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001937 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001938 skipTop--;
1939 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001940 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001941 mLruProcesses.add(i+1, app);
1942 break;
1943 }
1944 i--;
1945 }
1946 if (i < 0) {
1947 mLruProcesses.add(0, app);
1948 }
1949
Dianne Hackborn906497c2010-05-10 15:57:38 -07001950 // If the app is currently using a content provider or service,
1951 // bump those processes as well.
1952 if (app.connections.size() > 0) {
1953 for (ConnectionRecord cr : app.connections) {
1954 if (cr.binding != null && cr.binding.service != null
1955 && cr.binding.service.app != null
1956 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001957 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001958 }
1959 }
1960 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001961 for (int j=app.conProviders.size()-1; j>=0; j--) {
1962 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1963 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001964 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001965 }
1966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001969 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001970 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001971 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001972 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001973
1974 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1975 if (oomAdj) {
1976 updateOomAdjLocked();
1977 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001978 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001979
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001980 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001982 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001983 // The system gets to run in any process. If there are multiple
1984 // processes with the same uid, just pick the first (this
1985 // should never happen).
1986 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1987 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001988 if (procs == null) return null;
1989 final int N = procs.size();
1990 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001991 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994 ProcessRecord proc = mProcessNames.get(processName, uid);
1995 return proc;
1996 }
1997
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001998 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001999 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002000 try {
2001 if (pm.performDexOpt(packageName)) {
2002 mDidDexOpt = true;
2003 }
2004 } catch (RemoteException e) {
2005 }
2006 }
2007
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002008 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08002010 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
2011 || transit == AppTransition.TRANSIT_TASK_OPEN
2012 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002015 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002017 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2018 boolean isolated) {
2019 ProcessRecord app;
2020 if (!isolated) {
2021 app = getProcessRecordLocked(processName, info.uid);
2022 } else {
2023 // If this is an isolated process, it can't re-use an existing process.
2024 app = null;
2025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 // We don't have to do anything more if:
2027 // (1) There is an existing application record; and
2028 // (2) The caller doesn't think it is dead, OR there is no thread
2029 // object attached to it so we know it couldn't have crashed; and
2030 // (3) There is a pid assigned to it, so it is either starting or
2031 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002032 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 + " app=" + app + " knownToBeDead=" + knownToBeDead
2034 + " thread=" + (app != null ? app.thread : null)
2035 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002036 if (app != null && app.pid > 0) {
2037 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002038 // We already have the app running, or are waiting for it to
2039 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002040 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002041 // If this is a new package in the process, add the package to the list
2042 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002043 return app;
2044 } else {
2045 // An application record is attached to a previous process,
2046 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002047 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002048 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 String hostingNameStr = hostingName != null
2053 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002054
2055 if (!isolated) {
2056 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2057 // If we are in the background, then check to see if this process
2058 // is bad. If so, we will just silently fail.
2059 if (mBadProcesses.get(info.processName, info.uid) != null) {
2060 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2061 + "/" + info.processName);
2062 return null;
2063 }
2064 } else {
2065 // When the user is explicitly starting a process, then clear its
2066 // crash count so that we won't make it bad until they see at
2067 // least one crash dialog again, and make the process good again
2068 // if it had been bad.
2069 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002070 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002071 mProcessCrashTimes.remove(info.processName, info.uid);
2072 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002073 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2074 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002075 info.processName);
2076 mBadProcesses.remove(info.processName, info.uid);
2077 if (app != null) {
2078 app.bad = false;
2079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
2081 }
2082 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002085 app = newProcessRecordLocked(null, info, processName, isolated);
2086 if (app == null) {
2087 Slog.w(TAG, "Failed making new process record for "
2088 + processName + "/" + info.uid + " isolated=" + isolated);
2089 return null;
2090 }
2091 mProcessNames.put(processName, app.uid, app);
2092 if (isolated) {
2093 mIsolatedProcesses.put(app.uid, app);
2094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 } else {
2096 // If this is a new package in the process, add the package to the list
2097 app.addPackage(info.packageName);
2098 }
2099
2100 // If the system is not ready yet, then hold off on starting this
2101 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002102 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002103 && !isAllowedWhileBooting(info)
2104 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if (!mProcessesOnHold.contains(app)) {
2106 mProcessesOnHold.add(app);
2107 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002108 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 return app;
2110 }
2111
2112 startProcessLocked(app, hostingType, hostingNameStr);
2113 return (app.pid != 0) ? app : null;
2114 }
2115
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002116 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2117 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2118 }
2119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 private final void startProcessLocked(ProcessRecord app,
2121 String hostingType, String hostingNameStr) {
2122 if (app.pid > 0 && app.pid != MY_PID) {
2123 synchronized (mPidsSelfLocked) {
2124 mPidsSelfLocked.remove(app.pid);
2125 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2126 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002127 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
2129
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002130 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2131 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 mProcessesOnHold.remove(app);
2133
2134 updateCpuStats();
2135
2136 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2137 mProcDeaths[0] = 0;
2138
2139 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002140 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002143 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002144 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002145 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002146 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002147 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002148 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002149
2150 if (Environment.isExternalStorageEmulated()) {
2151 if (pm.checkPermission(
2152 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2153 app.info.packageName) == PERMISSION_GRANTED) {
2154 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2155 } else {
2156 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2157 }
2158 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002159 } catch (PackageManager.NameNotFoundException e) {
2160 Slog.w(TAG, "Unable to retrieve gids", e);
2161 }
Kenny Roote091f222012-09-11 15:01:26 -07002162
2163 /*
2164 * Add shared application GID so applications can share some
2165 * resources like shared libraries
2166 */
2167 if (permGids == null) {
2168 gids = new int[1];
2169 } else {
2170 gids = new int[permGids.length + 1];
2171 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2172 }
2173 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 }
2175 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2176 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2177 && mTopComponent != null
2178 && app.processName.equals(mTopComponent.getPackageName())) {
2179 uid = 0;
2180 }
2181 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2182 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2183 uid = 0;
2184 }
2185 }
2186 int debugFlags = 0;
2187 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2188 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002189 // Also turn on CheckJNI for debuggable apps. It's quite
2190 // awkward to turn on otherwise.
2191 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002192 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002193 // Run the app in safe mode if its manifest requests so or the
2194 // system is booted in safe mode.
2195 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2196 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002197 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2200 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2201 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002202 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2203 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 if ("1".equals(SystemProperties.get("debug.assert"))) {
2206 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2207 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002208
2209 // Start the process. It will either succeed and return a result containing
2210 // the PID of the new process, or else throw a RuntimeException.
2211 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002212 app.processName, uid, uid, gids, debugFlags, mountExternal,
Robert Craig0f40dc92013-03-25 06:33:03 -04002213 app.info.targetSdkVersion, app.info.seinfo, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2216 synchronized (bs) {
2217 if (bs.isOnBattery()) {
2218 app.batteryStats.incStartsLocked();
2219 }
2220 }
2221
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002222 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2223 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224 app.processName, hostingType,
2225 hostingNameStr != null ? hostingNameStr : "");
2226
2227 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002228 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002231 StringBuilder buf = mStringBuilder;
2232 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 buf.append("Start proc ");
2234 buf.append(app.processName);
2235 buf.append(" for ");
2236 buf.append(hostingType);
2237 if (hostingNameStr != null) {
2238 buf.append(" ");
2239 buf.append(hostingNameStr);
2240 }
2241 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002242 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002243 buf.append(" uid=");
2244 buf.append(uid);
2245 buf.append(" gids={");
2246 if (gids != null) {
2247 for (int gi=0; gi<gids.length; gi++) {
2248 if (gi != 0) buf.append(", ");
2249 buf.append(gids[gi]);
2250
2251 }
2252 }
2253 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002254 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002255 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002256 app.usingWrapper = startResult.usingWrapper;
2257 app.removed = false;
2258 synchronized (mPidsSelfLocked) {
2259 this.mPidsSelfLocked.put(startResult.pid, app);
2260 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2261 msg.obj = app;
2262 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2263 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002264 }
2265 } catch (RuntimeException e) {
2266 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002267 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002268 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
2271
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002272 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 if (resumed) {
2274 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2275 } else {
2276 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2277 }
2278 }
2279
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002280 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002281 if (mHeadless) {
2282 // Added because none of the other calls to ensureBootCompleted seem to fire
2283 // when running headless.
2284 ensureBootCompleted();
2285 return false;
2286 }
2287
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002288 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2289 && mTopAction == null) {
2290 // We are running in factory test mode, but unable to find
2291 // the factory test app, so just sit around displaying the
2292 // error message and don't try to start anything.
2293 return false;
2294 }
2295 Intent intent = new Intent(
2296 mTopAction,
2297 mTopData != null ? Uri.parse(mTopData) : null);
2298 intent.setComponent(mTopComponent);
2299 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2300 intent.addCategory(Intent.CATEGORY_HOME);
2301 }
2302 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002303 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002304 if (aInfo != null) {
2305 intent.setComponent(new ComponentName(
2306 aInfo.applicationInfo.packageName, aInfo.name));
2307 // Don't do this if the home app is currently being
2308 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002309 aInfo = new ActivityInfo(aInfo);
2310 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002311 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2312 aInfo.applicationInfo.uid);
2313 if (app == null || app.instrumentationClass == null) {
2314 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002315 mMainStack.startActivityLocked(null, intent, null, aInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002316 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002317 }
2318 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002319
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002320 return true;
2321 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002322
Amith Yamasani259d5e52012-08-31 15:11:01 -07002323 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2324 ActivityInfo ai = null;
2325 ComponentName comp = intent.getComponent();
2326 try {
2327 if (comp != null) {
2328 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2329 } else {
2330 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2331 intent,
2332 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2333 flags, userId);
2334
2335 if (info != null) {
2336 ai = info.activityInfo;
2337 }
2338 }
2339 } catch (RemoteException e) {
2340 // ignore
2341 }
2342
2343 return ai;
2344 }
2345
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002346 /**
2347 * Starts the "new version setup screen" if appropriate.
2348 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002349 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002350 // Only do this once per boot.
2351 if (mCheckedForSetup) {
2352 return;
2353 }
2354
2355 // We will show this screen if the current one is a different
2356 // version than the last one shown, and we are not running in
2357 // low-level factory test mode.
2358 final ContentResolver resolver = mContext.getContentResolver();
2359 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002360 Settings.Global.getInt(resolver,
2361 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002362 mCheckedForSetup = true;
2363
2364 // See if we should be showing the platform update setup UI.
2365 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2366 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2367 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2368
2369 // We don't allow third party apps to replace this.
2370 ResolveInfo ri = null;
2371 for (int i=0; ris != null && i<ris.size(); i++) {
2372 if ((ris.get(i).activityInfo.applicationInfo.flags
2373 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2374 ri = ris.get(i);
2375 break;
2376 }
2377 }
2378
2379 if (ri != null) {
2380 String vers = ri.activityInfo.metaData != null
2381 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2382 : null;
2383 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2384 vers = ri.activityInfo.applicationInfo.metaData.getString(
2385 Intent.METADATA_SETUP_VERSION);
2386 }
2387 String lastVers = Settings.Secure.getString(
2388 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2389 if (vers != null && !vers.equals(lastVers)) {
2390 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2391 intent.setComponent(new ComponentName(
2392 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002393 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002394 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002395 }
2396 }
2397 }
2398 }
2399
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002400 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002401 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002402 }
2403
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002404 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002405 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 throw new SecurityException("Isolated process not allowed to call " + caller);
2407 }
2408 }
2409
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002410 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002411 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002412 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002413 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2414 }
2415 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002416
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002417 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002418 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2419 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002420 synchronized (this) {
2421 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2422 }
2423 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002424
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002425 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002426 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002427 synchronized (this) {
2428 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2429 }
2430 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002431
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002432 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002433 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2434 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002435 synchronized (this) {
2436 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002437 }
2438 }
2439
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002440 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002441 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002442 synchronized (this) {
2443 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2444 }
2445 }
2446
2447 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002448 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2449 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002450 synchronized (this) {
2451 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2452 }
2453 }
2454
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002455 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002456 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002457 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002460 private void dispatchProcessesChanged() {
2461 int N;
2462 synchronized (this) {
2463 N = mPendingProcessChanges.size();
2464 if (mActiveProcessChanges.length < N) {
2465 mActiveProcessChanges = new ProcessChangeItem[N];
2466 }
2467 mPendingProcessChanges.toArray(mActiveProcessChanges);
2468 mAvailProcessChanges.addAll(mPendingProcessChanges);
2469 mPendingProcessChanges.clear();
2470 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2471 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002472 int i = mProcessObservers.beginBroadcast();
2473 while (i > 0) {
2474 i--;
2475 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2476 if (observer != null) {
2477 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002478 for (int j=0; j<N; j++) {
2479 ProcessChangeItem item = mActiveProcessChanges[j];
2480 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2481 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2482 + item.pid + " uid=" + item.uid + ": "
2483 + item.foregroundActivities);
2484 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2485 item.foregroundActivities);
2486 }
2487 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2488 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2489 + item.pid + " uid=" + item.uid + ": " + item.importance);
2490 observer.onImportanceChanged(item.pid, item.uid,
2491 item.importance);
2492 }
2493 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002494 } catch (RemoteException e) {
2495 }
2496 }
2497 }
2498 mProcessObservers.finishBroadcast();
2499 }
2500
2501 private void dispatchProcessDied(int pid, int uid) {
2502 int i = mProcessObservers.beginBroadcast();
2503 while (i > 0) {
2504 i--;
2505 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2506 if (observer != null) {
2507 try {
2508 observer.onProcessDied(pid, uid);
2509 } catch (RemoteException e) {
2510 }
2511 }
2512 }
2513 mProcessObservers.finishBroadcast();
2514 }
2515
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002516 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002517 final int N = mPendingActivityLaunches.size();
2518 if (N <= 0) {
2519 return;
2520 }
2521 for (int i=0; i<N; i++) {
2522 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002524 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002525 }
2526 mPendingActivityLaunches.clear();
2527 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002528
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002529 public final int startActivity(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 Intent intent, String resolvedType, IBinder resultTo,
2531 String resultWho, int requestCode, int startFlags,
2532 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002533 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
2534 resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002535 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002536 }
2537
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002538 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Amith Yamasani82644082012-08-03 13:09:11 -07002539 Intent intent, String resolvedType, IBinder resultTo,
2540 String resultWho, int requestCode, int startFlags,
2541 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002542 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002543 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002544 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002545 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002546 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2547 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002548 }
2549
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002550 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002551 Intent intent, String resolvedType, IBinder resultTo,
2552 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002553 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002554 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002555 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002556 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002557 WaitResult res = new WaitResult();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002558 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002559 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002560 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002561 return res;
2562 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002563
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002564 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002565 Intent intent, String resolvedType, IBinder resultTo,
2566 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002567 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002568 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002569 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002570 false, true, "startActivityWithConfig", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002571 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002572 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002573 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002574 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002575 }
2576
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002577 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002578 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002579 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002580 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002581 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002582 // Refuse possible leaked file descriptors
2583 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2584 throw new IllegalArgumentException("File descriptors passed in Intent");
2585 }
2586
2587 IIntentSender sender = intent.getTarget();
2588 if (!(sender instanceof PendingIntentRecord)) {
2589 throw new IllegalArgumentException("Bad PendingIntent object");
2590 }
2591
2592 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002593
2594 synchronized (this) {
2595 // If this is coming from the currently resumed activity, it is
2596 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 if (mMainStack.mResumedActivity != null
2598 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002599 Binder.getCallingUid()) {
2600 mAppSwitchesAllowedTime = 0;
2601 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002602 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002603 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2604 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002605 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002606 }
2607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002609 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 // Refuse possible leaked file descriptors
2611 if (intent != null && intent.hasFileDescriptors() == true) {
2612 throw new IllegalArgumentException("File descriptors passed in Intent");
2613 }
2614
2615 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002616 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2617 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002618 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 return false;
2620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 if (r.app == null || r.app.thread == null) {
2622 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002623 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 return false;
2625 }
2626 intent = new Intent(intent);
2627 // The caller is not allowed to change the data.
2628 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2629 // And we are resetting to find the next component...
2630 intent.setComponent(null);
2631
2632 ActivityInfo aInfo = null;
2633 try {
2634 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002635 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002637 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002638 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639
2640 // Look for the original activity in the list...
2641 final int N = resolves != null ? resolves.size() : 0;
2642 for (int i=0; i<N; i++) {
2643 ResolveInfo rInfo = resolves.get(i);
2644 if (rInfo.activityInfo.packageName.equals(r.packageName)
2645 && rInfo.activityInfo.name.equals(r.info.name)) {
2646 // We found the current one... the next matching is
2647 // after it.
2648 i++;
2649 if (i<N) {
2650 aInfo = resolves.get(i).activityInfo;
2651 }
2652 break;
2653 }
2654 }
2655 } catch (RemoteException e) {
2656 }
2657
2658 if (aInfo == null) {
2659 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002660 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 return false;
2662 }
2663
2664 intent.setComponent(new ComponentName(
2665 aInfo.applicationInfo.packageName, aInfo.name));
2666 intent.setFlags(intent.getFlags()&~(
2667 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2668 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2669 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2670 Intent.FLAG_ACTIVITY_NEW_TASK));
2671
2672 // Okay now we need to start the new activity, replacing the
2673 // currently running activity. This is a little tricky because
2674 // we want to start the new one as if the current one is finished,
2675 // but not finish the current one first so that there is no flicker.
2676 // And thus...
2677 final boolean wasFinishing = r.finishing;
2678 r.finishing = true;
2679
2680 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002681 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 final String resultWho = r.resultWho;
2683 final int requestCode = r.requestCode;
2684 r.resultTo = null;
2685 if (resultTo != null) {
2686 resultTo.removeResultsLocked(r, resultWho, requestCode);
2687 }
2688
2689 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002690 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002691 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002692 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002693 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 Binder.restoreCallingIdentity(origId);
2695
2696 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002697 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 return false;
2699 }
2700 return true;
2701 }
2702 }
2703
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002704 final int startActivityInPackage(int uid, String callingPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002705 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002706 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2707
Dianne Hackborn139748f2012-09-24 11:36:57 -07002708 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002709 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002711 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002712 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002713 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002714 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002715 }
2716
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002717 public final int startActivities(IApplicationThread caller, String callingPackage,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002718 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2719 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002720 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002721 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002722 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002723 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents,
2724 resolvedTypes, resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002725 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002726 }
2727
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002728 final int startActivitiesInPackage(int uid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002729 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002730 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002731
Dianne Hackborn139748f2012-09-24 11:36:57 -07002732 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002733 false, true, "startActivityInPackage", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002734 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes,
2735 resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002736 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737 }
2738
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002739 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002740 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002741 // Quick case: check if the top-most recent task is the same.
2742 if (N > 0 && mRecentTasks.get(0) == task) {
2743 return;
2744 }
2745 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 for (int i=0; i<N; i++) {
2747 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002748 if (task.userId == tr.userId
2749 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2750 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 mRecentTasks.remove(i);
2752 i--;
2753 N--;
2754 if (task.intent == null) {
2755 // If the new recent task we are adding is not fully
2756 // specified, then replace it with the existing recent task.
2757 task = tr;
2758 }
2759 }
2760 }
2761 if (N >= MAX_RECENT_TASKS) {
2762 mRecentTasks.remove(N-1);
2763 }
2764 mRecentTasks.add(0, task);
2765 }
2766
2767 public void setRequestedOrientation(IBinder token,
2768 int requestedOrientation) {
2769 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002770 ActivityRecord r = mMainStack.isInStackLocked(token);
2771 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 return;
2773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002775 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002777 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002778 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 if (config != null) {
2780 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002781 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002782 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 }
2784 }
2785 Binder.restoreCallingIdentity(origId);
2786 }
2787 }
2788
2789 public int getRequestedOrientation(IBinder token) {
2790 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002791 ActivityRecord r = mMainStack.isInStackLocked(token);
2792 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2794 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002795 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 }
2797 }
2798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 /**
2800 * This is the internal entry point for handling Activity.finish().
2801 *
2802 * @param token The Binder token referencing the Activity we want to finish.
2803 * @param resultCode Result code, if any, from this Activity.
2804 * @param resultData Result data (Intent), if any, from this Activity.
2805 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002806 * @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 -08002807 */
2808 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2809 // Refuse possible leaked file descriptors
2810 if (resultData != null && resultData.hasFileDescriptors() == true) {
2811 throw new IllegalArgumentException("File descriptors passed in Intent");
2812 }
2813
2814 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002815 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002817 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if (next != null) {
2819 // ask watcher if this is allowed
2820 boolean resumeOK = true;
2821 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002822 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002824 mController = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -07002825 Watchdog.getInstance().setActivityController(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827
2828 if (!resumeOK) {
2829 return false;
2830 }
2831 }
2832 }
2833 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002835 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 Binder.restoreCallingIdentity(origId);
2837 return res;
2838 }
2839 }
2840
Dianne Hackborn860755f2010-06-03 18:47:52 -07002841 public final void finishHeavyWeightApp() {
2842 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2843 != PackageManager.PERMISSION_GRANTED) {
2844 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2845 + Binder.getCallingPid()
2846 + ", uid=" + Binder.getCallingUid()
2847 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2848 Slog.w(TAG, msg);
2849 throw new SecurityException(msg);
2850 }
2851
2852 synchronized(this) {
2853 if (mHeavyWeightProcess == null) {
2854 return;
2855 }
2856
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002857 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002858 mHeavyWeightProcess.activities);
2859 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002860 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002861 if (!r.finishing) {
Craig Mautner2ad92072013-02-25 16:19:24 -08002862 int index = mMainStack.indexOfTokenLocked(r.appToken);
2863 if (index >= 0) {
2864 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
2865 null, "finish-heavy", true);
2866 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07002867 }
2868 }
2869
Dianne Hackborn41203752012-08-31 14:05:51 -07002870 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2871 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002872 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002873 }
2874 }
2875
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002876 public void crashApplication(int uid, int initialPid, String packageName,
2877 String message) {
2878 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2879 != PackageManager.PERMISSION_GRANTED) {
2880 String msg = "Permission Denial: crashApplication() from pid="
2881 + Binder.getCallingPid()
2882 + ", uid=" + Binder.getCallingUid()
2883 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2884 Slog.w(TAG, msg);
2885 throw new SecurityException(msg);
2886 }
2887
2888 synchronized(this) {
2889 ProcessRecord proc = null;
2890
2891 // Figure out which process to kill. We don't trust that initialPid
2892 // still has any relation to current pids, so must scan through the
2893 // list.
2894 synchronized (mPidsSelfLocked) {
2895 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2896 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002897 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002898 continue;
2899 }
2900 if (p.pid == initialPid) {
2901 proc = p;
2902 break;
2903 }
2904 for (String str : p.pkgList) {
2905 if (str.equals(packageName)) {
2906 proc = p;
2907 }
2908 }
2909 }
2910 }
2911
2912 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002913 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002914 + " initialPid=" + initialPid
2915 + " packageName=" + packageName);
2916 return;
2917 }
2918
2919 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002920 if (proc.pid == Process.myPid()) {
2921 Log.w(TAG, "crashApplication: trying to crash self!");
2922 return;
2923 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002924 long ident = Binder.clearCallingIdentity();
2925 try {
2926 proc.thread.scheduleCrash(message);
2927 } catch (RemoteException e) {
2928 }
2929 Binder.restoreCallingIdentity(ident);
2930 }
2931 }
2932 }
2933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 public final void finishSubActivity(IBinder token, String resultWho,
2935 int requestCode) {
2936 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002938 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 Binder.restoreCallingIdentity(origId);
2940 }
2941 }
2942
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002943 public boolean finishActivityAffinity(IBinder token) {
2944 synchronized(this) {
2945 final long origId = Binder.clearCallingIdentity();
2946 boolean res = mMainStack.finishActivityAffinityLocked(token);
2947 Binder.restoreCallingIdentity(origId);
2948 return res;
2949 }
2950 }
2951
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002952 public boolean willActivityBeVisible(IBinder token) {
2953 synchronized(this) {
Craig Mautner2ad92072013-02-25 16:19:24 -08002954 int i;
2955 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2956 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
2957 if (r.appToken == token) {
2958 return true;
2959 }
2960 if (r.fullscreen && !r.finishing) {
2961 return false;
2962 }
2963 }
2964 return true;
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002965 }
2966 }
Craig Mautner2ad92072013-02-25 16:19:24 -08002967
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002968 public void overridePendingTransition(IBinder token, String packageName,
2969 int enterAnim, int exitAnim) {
2970 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002971 ActivityRecord self = mMainStack.isInStackLocked(token);
2972 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002973 return;
2974 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002975
2976 final long origId = Binder.clearCallingIdentity();
2977
2978 if (self.state == ActivityState.RESUMED
2979 || self.state == ActivityState.PAUSING) {
2980 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002981 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002982 }
2983
2984 Binder.restoreCallingIdentity(origId);
2985 }
2986 }
2987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 * Main function for removing an existing process from the activity manager
2990 * as a result of that process going away. Clears out all connections
2991 * to the process.
2992 */
2993 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002994 boolean restarting, boolean allowRestart) {
2995 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002997 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003000 if (mProfileProc == app) {
3001 clearProfilerLocked();
3002 }
3003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003005 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003006 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
3007 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003008 mMainStack.mPausingActivity = null;
3009 }
3010 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
3011 mMainStack.mLastPausedActivity = null;
3012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013
3014 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003015 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016
3017 app.activities.clear();
3018
3019 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003020 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 + " running instrumentation " + app.instrumentationClass);
3022 Bundle info = new Bundle();
3023 info.putString("shortMsg", "Process crashed.");
3024 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3025 }
3026
3027 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003028 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 // If there was nothing to resume, and we are not already
3030 // restarting this process, but there is a visible activity that
3031 // is hosted by the process... then make sure all visible
3032 // activities are running, taking care of restarting this
3033 // process.
3034 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003035 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 }
3037 }
3038 }
3039 }
3040
3041 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3042 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003044 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3045 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3047 return i;
3048 }
3049 }
3050 return -1;
3051 }
3052
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003053 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 IApplicationThread thread) {
3055 if (thread == null) {
3056 return null;
3057 }
3058
3059 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003060 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 }
3062
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003063 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 IApplicationThread thread) {
3065
3066 mProcDeaths[0]++;
3067
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003068 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3069 synchronized (stats) {
3070 stats.noteProcessDiedLocked(app.info.uid, pid);
3071 }
3072
Magnus Edlund7bb25812010-02-24 15:45:06 +01003073 // Clean up already done if the process has been re-started.
3074 if (app.pid == pid && app.thread != null &&
3075 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003076 if (!app.killedBackground) {
3077 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3078 + ") has died.");
3079 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003080 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003081 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 TAG, "Dying app: " + app + ", pid: " + pid
3083 + ", thread: " + thread.asBinder());
3084 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003085 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086
3087 if (doLowMem) {
3088 // If there are no longer any background processes running,
3089 // and the app that died was not running instrumentation,
3090 // then tell everyone we are now low on memory.
3091 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003092 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3093 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003094 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 haveBg = true;
3096 break;
3097 }
3098 }
3099
3100 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003101 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003102 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003103 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3104 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003105 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003106 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3107 // The low memory report is overriding any current
3108 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003109 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003110 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003111 rec.lastRequestedGc = 0;
3112 } else {
3113 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003115 rec.reportLowMemory = true;
3116 rec.lastLowMemory = now;
3117 mProcessesToGc.remove(rec);
3118 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
3120 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003121 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003122 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 }
3124 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003125 } else if (app.pid != pid) {
3126 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003127 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003128 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003129 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003130 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003131 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 + thread.asBinder());
3133 }
3134 }
3135
Dan Egnor42471dd2010-01-07 17:25:22 -08003136 /**
3137 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003138 * @param clearTraces causes the dump file to be erased prior to the new
3139 * traces being written, if true; when false, the new traces will be
3140 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003141 * @param firstPids of dalvik VM processes to dump stack traces for first
3142 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003143 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003144 * @return file containing stack traces, or null if no dump file is configured
3145 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003146 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003147 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3149 if (tracesPath == null || tracesPath.length() == 0) {
3150 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003152
3153 File tracesFile = new File(tracesPath);
3154 try {
3155 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003156 if (!tracesDir.exists()) {
3157 tracesFile.mkdirs();
3158 if (!SELinux.restorecon(tracesDir)) {
3159 return null;
3160 }
3161 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003162 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3163
Christopher Tate6ee412d2010-05-28 12:01:56 -07003164 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003165 tracesFile.createNewFile();
3166 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3167 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003168 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003169 return null;
3170 }
3171
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003172 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003173 return tracesFile;
3174 }
3175
3176 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003177 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003178 // Use a FileObserver to detect when traces finish writing.
3179 // The order of traces is considered important to maintain for legibility.
3180 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3181 public synchronized void onEvent(int event, String path) { notify(); }
3182 };
3183
3184 try {
3185 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003186
3187 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003188 if (firstPids != null) {
3189 try {
3190 int num = firstPids.size();
3191 for (int i = 0; i < num; i++) {
3192 synchronized (observer) {
3193 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3194 observer.wait(200); // Wait for write-close, give up after 200msec
3195 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003196 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003197 } catch (InterruptedException e) {
3198 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003199 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003200 }
3201
3202 // Next measure CPU usage.
3203 if (processStats != null) {
3204 processStats.init();
3205 System.gc();
3206 processStats.update();
3207 try {
3208 synchronized (processStats) {
3209 processStats.wait(500); // measure over 1/2 second.
3210 }
3211 } catch (InterruptedException e) {
3212 }
3213 processStats.update();
3214
3215 // We'll take the stack crawls of just the top apps using CPU.
3216 final int N = processStats.countWorkingStats();
3217 int numProcs = 0;
3218 for (int i=0; i<N && numProcs<5; i++) {
3219 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3220 if (lastPids.indexOfKey(stats.pid) >= 0) {
3221 numProcs++;
3222 try {
3223 synchronized (observer) {
3224 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3225 observer.wait(200); // Wait for write-close, give up after 200msec
3226 }
3227 } catch (InterruptedException e) {
3228 Log.wtf(TAG, e);
3229 }
3230
3231 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003232 }
3233 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003234
Dan Egnor42471dd2010-01-07 17:25:22 -08003235 } finally {
3236 observer.stopWatching();
3237 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003238
3239 if (nativeProcs != null) {
3240 int[] pids = Process.getPidsForCommands(nativeProcs);
3241 if (pids != null) {
3242 for (int pid : pids) {
3243 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3244 }
3245 }
3246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003249 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003250 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003251 return;
3252 }
3253 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3254 if (tracesPath == null || tracesPath.length() == 0) {
3255 return;
3256 }
3257
3258 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3259 StrictMode.allowThreadDiskWrites();
3260 try {
3261 final File tracesFile = new File(tracesPath);
3262 final File tracesDir = tracesFile.getParentFile();
3263 final File tracesTmp = new File(tracesDir, "__tmp__");
3264 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003265 if (!tracesDir.exists()) {
3266 tracesFile.mkdirs();
3267 if (!SELinux.restorecon(tracesDir.getPath())) {
3268 return;
3269 }
3270 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003271 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3272
3273 if (tracesFile.exists()) {
3274 tracesTmp.delete();
3275 tracesFile.renameTo(tracesTmp);
3276 }
3277 StringBuilder sb = new StringBuilder();
3278 Time tobj = new Time();
3279 tobj.set(System.currentTimeMillis());
3280 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3281 sb.append(": ");
3282 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3283 sb.append(" since ");
3284 sb.append(msg);
3285 FileOutputStream fos = new FileOutputStream(tracesFile);
3286 fos.write(sb.toString().getBytes());
3287 if (app == null) {
3288 fos.write("\n*** No application process!".getBytes());
3289 }
3290 fos.close();
3291 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3292 } catch (IOException e) {
3293 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3294 return;
3295 }
3296
3297 if (app != null) {
3298 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3299 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003300 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003301 }
3302
3303 File lastTracesFile = null;
3304 File curTracesFile = null;
3305 for (int i=9; i>=0; i--) {
3306 String name = String.format("slow%02d.txt", i);
3307 curTracesFile = new File(tracesDir, name);
3308 if (curTracesFile.exists()) {
3309 if (lastTracesFile != null) {
3310 curTracesFile.renameTo(lastTracesFile);
3311 } else {
3312 curTracesFile.delete();
3313 }
3314 }
3315 lastTracesFile = curTracesFile;
3316 }
3317 tracesFile.renameTo(curTracesFile);
3318 if (tracesTmp.exists()) {
3319 tracesTmp.renameTo(tracesFile);
3320 }
3321 } finally {
3322 StrictMode.setThreadPolicy(oldPolicy);
3323 }
3324 }
3325
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003326 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003327 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003328 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3329 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3330
Dianne Hackborn287952c2010-09-22 22:34:31 -07003331 if (mController != null) {
3332 try {
3333 // 0 == continue, -1 = kill process immediately
3334 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3335 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3336 } catch (RemoteException e) {
3337 mController = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -07003338 Watchdog.getInstance().setActivityController(null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003339 }
3340 }
3341
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003342 long anrTime = SystemClock.uptimeMillis();
3343 if (MONITOR_CPU_USAGE) {
3344 updateCpuStatsNow();
3345 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003346
3347 synchronized (this) {
3348 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3349 if (mShuttingDown) {
3350 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3351 return;
3352 } else if (app.notResponding) {
3353 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3354 return;
3355 } else if (app.crashing) {
3356 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3357 return;
3358 }
3359
3360 // In case we come through here for the same app before completing
3361 // this one, mark as anring now so we will bail out.
3362 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003363
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003364 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003365 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3366 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003367
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003368 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003369 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003370
3371 int parentPid = app.pid;
3372 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003373 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003374
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003375 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003376
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003377 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3378 ProcessRecord r = mLruProcesses.get(i);
3379 if (r != null && r.thread != null) {
3380 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003381 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3382 if (r.persistent) {
3383 firstPids.add(pid);
3384 } else {
3385 lastPids.put(pid, Boolean.TRUE);
3386 }
3387 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 }
3390 }
3391
Dan Egnor42471dd2010-01-07 17:25:22 -08003392 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003393 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003394 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003395 info.append("ANR in ").append(app.processName);
3396 if (activity != null && activity.shortComponentName != null) {
3397 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003398 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003399 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003401 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003403 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003404 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406
Dianne Hackborn287952c2010-09-22 22:34:31 -07003407 final ProcessStats processStats = new ProcessStats(true);
3408
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003409 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003410
Dan Egnor42471dd2010-01-07 17:25:22 -08003411 String cpuInfo = null;
3412 if (MONITOR_CPU_USAGE) {
3413 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003414 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003415 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003416 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003417 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003418 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 }
3420
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003421 info.append(processStats.printCurrentState(anrTime));
3422
Joe Onorato8a9b2202010-02-26 18:56:32 -08003423 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003424 if (tracesFile == null) {
3425 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3426 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3427 }
3428
Jeff Sharkeya353d262011-10-28 11:12:06 -07003429 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3430 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003431
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003432 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003434 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3435 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003437 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3438 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 }
3440 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003441 mController = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -07003442 Watchdog.getInstance().setActivityController(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 }
3444 }
3445
Dan Egnor42471dd2010-01-07 17:25:22 -08003446 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3447 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3448 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003449
3450 synchronized (this) {
3451 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003452 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003453 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003454 app.processName, app.setAdj, "background ANR");
3455 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003456 return;
3457 }
3458
3459 // Set the app's notResponding state, and look up the errorReportReceiver
3460 makeAppNotRespondingLocked(app,
3461 activity != null ? activity.shortComponentName : null,
3462 annotation != null ? "ANR " + annotation : "ANR",
3463 info.toString());
3464
3465 // Bring up the infamous App Not Responding dialog
3466 Message msg = Message.obtain();
3467 HashMap map = new HashMap();
3468 msg.what = SHOW_NOT_RESPONDING_MSG;
3469 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003470 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003471 map.put("app", app);
3472 if (activity != null) {
3473 map.put("activity", activity);
3474 }
3475
3476 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
3479
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003480 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3481 if (!mLaunchWarningShown) {
3482 mLaunchWarningShown = true;
3483 mHandler.post(new Runnable() {
3484 @Override
3485 public void run() {
3486 synchronized (ActivityManagerService.this) {
3487 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3488 d.show();
3489 mHandler.postDelayed(new Runnable() {
3490 @Override
3491 public void run() {
3492 synchronized (ActivityManagerService.this) {
3493 d.dismiss();
3494 mLaunchWarningShown = false;
3495 }
3496 }
3497 }, 4000);
3498 }
3499 }
3500 });
3501 }
3502 }
3503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003505 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003506 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 int uid = Binder.getCallingUid();
3508 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003509 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003510 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 long callingId = Binder.clearCallingIdentity();
3512 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003513 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 int pkgUid = -1;
3515 synchronized(this) {
3516 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003517 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 } catch (RemoteException e) {
3519 }
3520 if (pkgUid == -1) {
Christopher Tatea83cab02013-03-07 17:50:11 -08003521 Slog.w(TAG, "Invalid packageName: " + packageName);
3522 if (observer != null) {
3523 try {
3524 observer.onRemoveCompleted(packageName, false);
3525 } catch (RemoteException e) {
3526 Slog.i(TAG, "Observer no longer exists.");
3527 }
3528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 return false;
3530 }
3531 if (uid == pkgUid || checkComponentPermission(
3532 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003533 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003535 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 } else {
3537 throw new SecurityException(pid+" does not have permission:"+
3538 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3539 "for process:"+packageName);
3540 }
3541 }
3542
3543 try {
3544 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003545 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3547 Uri.fromParts("package", packageName, null));
3548 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003549 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003550 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 } catch (RemoteException e) {
3552 }
3553 } finally {
3554 Binder.restoreCallingIdentity(callingId);
3555 }
3556 return true;
3557 }
3558
Dianne Hackborn1676c852012-09-10 14:52:30 -07003559 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003560 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3561 != PackageManager.PERMISSION_GRANTED &&
3562 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3563 != PackageManager.PERMISSION_GRANTED) {
3564 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 + Binder.getCallingPid()
3566 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003567 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003568 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 throw new SecurityException(msg);
3570 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003571
Dianne Hackborn139748f2012-09-24 11:36:57 -07003572 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003573 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 long callingId = Binder.clearCallingIdentity();
3575 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003576 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003577 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003578 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003580 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003581 } catch (RemoteException e) {
3582 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003583 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003584 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 return;
3586 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003587 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003588 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3589 }
3590 } finally {
3591 Binder.restoreCallingIdentity(callingId);
3592 }
3593 }
3594
3595 public void killAllBackgroundProcesses() {
3596 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3597 != PackageManager.PERMISSION_GRANTED) {
3598 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3599 + Binder.getCallingPid()
3600 + ", uid=" + Binder.getCallingUid()
3601 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3602 Slog.w(TAG, msg);
3603 throw new SecurityException(msg);
3604 }
3605
3606 long callingId = Binder.clearCallingIdentity();
3607 try {
3608 synchronized(this) {
3609 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3610 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3611 final int NA = apps.size();
3612 for (int ia=0; ia<NA; ia++) {
3613 ProcessRecord app = apps.valueAt(ia);
3614 if (app.persistent) {
3615 // we don't kill persistent processes
3616 continue;
3617 }
3618 if (app.removed) {
3619 procs.add(app);
3620 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3621 app.removed = true;
3622 procs.add(app);
3623 }
3624 }
3625 }
3626
3627 int N = procs.size();
3628 for (int i=0; i<N; i++) {
3629 removeProcessLocked(procs.get(i), false, true, "kill all background");
3630 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003631 }
3632 } finally {
3633 Binder.restoreCallingIdentity(callingId);
3634 }
3635 }
3636
Dianne Hackborn1676c852012-09-10 14:52:30 -07003637 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003638 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3639 != PackageManager.PERMISSION_GRANTED) {
3640 String msg = "Permission Denial: forceStopPackage() from pid="
3641 + Binder.getCallingPid()
3642 + ", uid=" + Binder.getCallingUid()
3643 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003644 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003645 throw new SecurityException(msg);
3646 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003647 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003648 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003649 long callingId = Binder.clearCallingIdentity();
3650 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003651 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003652 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003653 int[] users = userId == UserHandle.USER_ALL
3654 ? getUsersLocked() : new int[] { userId };
3655 for (int user : users) {
3656 int pkgUid = -1;
3657 try {
3658 pkgUid = pm.getPackageUid(packageName, user);
3659 } catch (RemoteException e) {
3660 }
3661 if (pkgUid == -1) {
3662 Slog.w(TAG, "Invalid packageName: " + packageName);
3663 continue;
3664 }
3665 try {
3666 pm.setPackageStoppedState(packageName, true, user);
3667 } catch (RemoteException e) {
3668 } catch (IllegalArgumentException e) {
3669 Slog.w(TAG, "Failed trying to unstop package "
3670 + packageName + ": " + e);
3671 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003672 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003673 forceStopPackageLocked(packageName, pkgUid);
3674 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 }
3677 } finally {
3678 Binder.restoreCallingIdentity(callingId);
3679 }
3680 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003681
3682 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003683 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003684 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003685 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003686 if (pkg == null) {
3687 return;
3688 }
3689 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003690 if (appid < 0) {
3691 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003692 return;
3693 }
3694 int callerUid = Binder.getCallingUid();
3695 // Only the system server can kill an application
3696 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003697 // Post an aysnc message to kill the application
3698 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003699 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003700 msg.arg2 = 0;
3701 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003702 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003703 } else {
3704 throw new SecurityException(callerUid + " cannot kill pkg: " +
3705 pkg);
3706 }
3707 }
3708
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003709 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003710 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003711
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003712 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003713 final int uid = Binder.getCallingUid();
3714 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003715 try {
3716 synchronized (this) {
3717 // Only allow this from foreground processes, so that background
3718 // applications can't abuse it to prevent system UI from being shown.
3719 if (uid >= Process.FIRST_APPLICATION_UID) {
3720 ProcessRecord proc;
3721 synchronized (mPidsSelfLocked) {
3722 proc = mPidsSelfLocked.get(pid);
3723 }
3724 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3725 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3726 + " from background process " + proc);
3727 return;
3728 }
3729 }
3730 closeSystemDialogsLocked(reason);
3731 }
3732 } finally {
3733 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003734 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003735 }
3736
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003737 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003738 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3740 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003741 if (reason != null) {
3742 intent.putExtra("reason", reason);
3743 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003744 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003745
Craig Mautner2ad92072013-02-25 16:19:24 -08003746 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3747 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
3748 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
3749 r.stack.finishActivityLocked(r, i,
3750 Activity.RESULT_CANCELED, null, "close-sys", true);
3751 }
3752 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003753
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003754 broadcastIntentLocked(null, null, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003755 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003756 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003757 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003758
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003759 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003760 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003761 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003762 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3763 for (int i=pids.length-1; i>=0; i--) {
3764 infos[i] = new Debug.MemoryInfo();
3765 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003766 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003767 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003768 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003769
Dianne Hackbornb437e092011-08-05 17:50:29 -07003770 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003771 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003772 long[] pss = new long[pids.length];
3773 for (int i=pids.length-1; i>=0; i--) {
3774 pss[i] = Debug.getPss(pids[i]);
3775 }
3776 return pss;
3777 }
3778
Christopher Tate5e1ab332009-09-01 20:32:49 -07003779 public void killApplicationProcess(String processName, int uid) {
3780 if (processName == null) {
3781 return;
3782 }
3783
3784 int callerUid = Binder.getCallingUid();
3785 // Only the system server can kill an application
3786 if (callerUid == Process.SYSTEM_UID) {
3787 synchronized (this) {
3788 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003789 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003790 try {
3791 app.thread.scheduleSuicide();
3792 } catch (RemoteException e) {
3793 // If the other end already died, then our work here is done.
3794 }
3795 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003796 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003797 + processName + " / " + uid);
3798 }
3799 }
3800 } else {
3801 throw new SecurityException(callerUid + " cannot kill app process: " +
3802 processName);
3803 }
3804 }
3805
Dianne Hackborn03abb812010-01-04 18:43:19 -08003806 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003807 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3808 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3810 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003811 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3813 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003816 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003818 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -07003819 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003820 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003822
3823 private void forceStopUserLocked(int userId) {
3824 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3825 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3827 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003828 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3829 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003830 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003831 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003832 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003833 }
3834
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003835 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003836 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3837 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003838 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839
Dianne Hackborn03abb812010-01-04 18:43:19 -08003840 // Remove all processes this package may have touched: all with the
3841 // same UID (except for the system or root user), and all whose name
3842 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003843 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003844 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3845 final int NA = apps.size();
3846 for (int ia=0; ia<NA; ia++) {
3847 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003848 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003849 // we don't kill persistent processes
3850 continue;
3851 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003852 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003853 if (doit) {
3854 procs.add(app);
3855 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003856 continue;
3857 }
3858
3859 // Skip process if it doesn't meet our oom adj requirement.
3860 if (app.setAdj < minOomAdj) {
3861 continue;
3862 }
3863
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003864 // If no package is specified, we call all processes under the
3865 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003866 if (packageName == null) {
3867 if (app.userId != userId) {
3868 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003869 }
Dianne Hackbornf1b78242013-04-08 22:28:59 -07003870 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) {
3871 continue;
3872 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003873 // Package has been specified, we want to hit all processes
3874 // that match it. We need to qualify this by the processes
3875 // that are running under the specified app and user ID.
3876 } else {
3877 if (UserHandle.getAppId(app.uid) != appId) {
3878 continue;
3879 }
3880 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3881 continue;
3882 }
3883 if (!app.pkgList.contains(packageName)) {
3884 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003885 }
3886 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003887
3888 // Process has passed all conditions, kill it!
3889 if (!doit) {
3890 return true;
3891 }
3892 app.removed = true;
3893 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003894 }
3895 }
3896
3897 int N = procs.size();
3898 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003899 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003900 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003901 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003902 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003903
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003904 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003905 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003906 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003907 int i;
3908 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003910 if (userId == UserHandle.USER_ALL && name == null) {
3911 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3912 }
3913
3914 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003916 appId = UserHandle.getAppId(
3917 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 } catch (RemoteException e) {
3919 }
3920 }
3921
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003922 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003923 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003924 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3925 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003926 } else {
3927 Slog.i(TAG, "Force stopping user " + userId);
3928 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003929
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003930 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3931 while (badApps.hasNext()) {
3932 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003933 for (i=ba.size()-1; i>=0; i--) {
3934 boolean remove = false;
3935 final int entUid = ba.keyAt(i);
3936 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003937 if (userId == UserHandle.USER_ALL) {
3938 if (UserHandle.getAppId(entUid) == appId) {
3939 remove = true;
3940 }
3941 } else {
3942 if (entUid == UserHandle.getUid(userId, appId)) {
3943 remove = true;
3944 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003945 }
3946 } else if (UserHandle.getUserId(entUid) == userId) {
3947 remove = true;
3948 }
3949 if (remove) {
3950 ba.removeAt(i);
3951 }
3952 }
3953 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003954 badApps.remove();
3955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
3957 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003958
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003959 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003960 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003961 name == null ? ("force stop user " + userId) : ("force stop " + name));
Craig Mautner2ad92072013-02-25 16:19:24 -08003962
3963 TaskRecord lastTask = null;
3964 for (i=0; i<mMainStack.mHistory.size(); i++) {
3965 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
3966 final boolean samePackage = r.packageName.equals(name)
3967 || (name == null && r.userId == userId);
3968 if ((userId == UserHandle.USER_ALL || r.userId == userId)
3969 && (samePackage || r.task == lastTask)
3970 && (r.app == null || evenPersistent || !r.app.persistent)) {
3971 if (!doit) {
3972 if (r.finishing) {
3973 // If this activity is just finishing, then it is not
3974 // interesting as far as something to stop.
3975 continue;
3976 }
3977 return true;
3978 }
3979 didSomething = true;
3980 Slog.i(TAG, " Force finishing activity " + r);
3981 if (samePackage) {
3982 if (r.app != null) {
3983 r.app.removed = true;
3984 }
3985 r.app = null;
3986 }
3987 lastTask = r.task;
3988 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
3989 null, "force-stop", true)) {
3990 i--;
3991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 }
3993 }
3994
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003995 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3996 if (!doit) {
3997 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003999 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004001
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07004002 if (name == null) {
4003 // Remove all sticky broadcasts from this user.
4004 mStickyBroadcasts.remove(userId);
4005 }
4006
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004007 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004008 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
4009 userId, providers)) {
4010 if (!doit) {
4011 return true;
4012 }
4013 didSomething = true;
4014 }
4015 N = providers.size();
4016 for (i=0; i<N; i++) {
4017 removeDyingProviderLocked(null, providers.get(i), true);
4018 }
4019
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004020 if (name == null) {
4021 // Remove pending intents. For now we only do this when force
4022 // stopping users, because we have some problems when doing this
4023 // for packages -- app widgets are not currently cleaned up for
4024 // such packages, so they can be left with bad pending intents.
4025 if (mIntentSenderRecords.size() > 0) {
4026 Iterator<WeakReference<PendingIntentRecord>> it
4027 = mIntentSenderRecords.values().iterator();
4028 while (it.hasNext()) {
4029 WeakReference<PendingIntentRecord> wpir = it.next();
4030 if (wpir == null) {
4031 it.remove();
4032 continue;
4033 }
4034 PendingIntentRecord pir = wpir.get();
4035 if (pir == null) {
4036 it.remove();
4037 continue;
4038 }
4039 if (name == null) {
4040 // Stopping user, remove all objects for the user.
4041 if (pir.key.userId != userId) {
4042 // Not the same user, skip it.
4043 continue;
4044 }
4045 } else {
4046 if (UserHandle.getAppId(pir.uid) != appId) {
4047 // Different app id, skip it.
4048 continue;
4049 }
4050 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
4051 // Different user, skip it.
4052 continue;
4053 }
4054 if (!pir.key.packageName.equals(name)) {
4055 // Different package, skip it.
4056 continue;
4057 }
4058 }
4059 if (!doit) {
4060 return true;
4061 }
4062 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004063 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004064 pir.canceled = true;
4065 if (pir.key.activity != null) {
4066 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004067 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004068 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004069 }
4070 }
4071
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004072 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004073 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004074 AttributeCache ac = AttributeCache.instance();
4075 if (ac != null) {
4076 ac.removePackage(name);
4077 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004078 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004079 if (mBooted) {
4080 mMainStack.resumeTopActivityLocked(null);
4081 mMainStack.scheduleIdleLocked();
4082 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004083 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004084
4085 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 }
4087
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004088 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004089 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004091 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004092 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004093 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 + "/" + uid + ")");
4095
4096 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004097 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004098 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004099 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4100 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004101 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 boolean needRestart = false;
4104 if (app.pid > 0 && app.pid != MY_PID) {
4105 int pid = app.pid;
4106 synchronized (mPidsSelfLocked) {
4107 mPidsSelfLocked.remove(pid);
4108 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4109 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004110 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004111 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004112 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004113 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004115 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004117 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 } else {
4119 needRestart = true;
4120 }
4121 }
4122 } else {
4123 mRemovedProcesses.add(app);
4124 }
4125
4126 return needRestart;
4127 }
4128
4129 private final void processStartTimedOutLocked(ProcessRecord app) {
4130 final int pid = app.pid;
4131 boolean gone = false;
4132 synchronized (mPidsSelfLocked) {
4133 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4134 if (knownApp != null && knownApp.thread == null) {
4135 mPidsSelfLocked.remove(pid);
4136 gone = true;
4137 }
4138 }
4139
4140 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004141 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004142 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4143 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004144 mProcessNames.remove(app.processName, app.uid);
4145 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004146 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004147 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4148 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004149 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004150 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004151 // Take care of any launching providers waiting for this process.
4152 checkAppInLaunchingProvidersLocked(app, true);
4153 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004154 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004155 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004156 app.processName, app.setAdj, "start timeout");
4157 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004158 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004159 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004160 try {
4161 IBackupManager bm = IBackupManager.Stub.asInterface(
4162 ServiceManager.getService(Context.BACKUP_SERVICE));
4163 bm.agentDisconnected(app.info.packageName);
4164 } catch (RemoteException e) {
4165 // Can't happen; the backup manager is local
4166 }
4167 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004168 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004169 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004170 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004173 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175 }
4176
4177 private final boolean attachApplicationLocked(IApplicationThread thread,
4178 int pid) {
4179
4180 // Find the application record that is being attached... either via
4181 // the pid if we are running in multiple processes, or just pull the
4182 // next app record if we are emulating process with anonymous threads.
4183 ProcessRecord app;
4184 if (pid != MY_PID && pid >= 0) {
4185 synchronized (mPidsSelfLocked) {
4186 app = mPidsSelfLocked.get(pid);
4187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 } else {
4189 app = null;
4190 }
4191
4192 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004193 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004195 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004197 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004198 } else {
4199 try {
4200 thread.scheduleExit();
4201 } catch (Exception e) {
4202 // Ignore exceptions.
4203 }
4204 }
4205 return false;
4206 }
4207
4208 // If this application record is still attached to a previous
4209 // process, clean it up now.
4210 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004211 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 }
4213
4214 // Tell the process all about itself.
4215
Joe Onorato8a9b2202010-02-26 18:56:32 -08004216 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 TAG, "Binding process pid " + pid + " to record " + app);
4218
4219 String processName = app.processName;
4220 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004221 AppDeathRecipient adr = new AppDeathRecipient(
4222 app, pid, thread);
4223 thread.asBinder().linkToDeath(adr, 0);
4224 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 } catch (RemoteException e) {
4226 app.resetPackageList();
4227 startProcessLocked(app, "link fail", processName);
4228 return false;
4229 }
4230
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004231 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232
4233 app.thread = thread;
4234 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004235 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4236 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 app.forcingToForeground = null;
4238 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004239 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 app.debugging = false;
4241
4242 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4243
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004244 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004245 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004247 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004248 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004249 }
4250
Joe Onorato8a9b2202010-02-26 18:56:32 -08004251 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 TAG, "New app record " + app
4253 + " thread=" + thread.asBinder() + " pid=" + pid);
4254 try {
4255 int testMode = IApplicationThread.DEBUG_OFF;
4256 if (mDebugApp != null && mDebugApp.equals(processName)) {
4257 testMode = mWaitForDebugger
4258 ? IApplicationThread.DEBUG_WAIT
4259 : IApplicationThread.DEBUG_ON;
4260 app.debugging = true;
4261 if (mDebugTransient) {
4262 mDebugApp = mOrigDebugApp;
4263 mWaitForDebugger = mOrigWaitForDebugger;
4264 }
4265 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004266 String profileFile = app.instrumentationProfileFile;
4267 ParcelFileDescriptor profileFd = null;
4268 boolean profileAutoStop = false;
4269 if (mProfileApp != null && mProfileApp.equals(processName)) {
4270 mProfileProc = app;
4271 profileFile = mProfileFile;
4272 profileFd = mProfileFd;
4273 profileAutoStop = mAutoStopProfiler;
4274 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004275 boolean enableOpenGlTrace = false;
4276 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4277 enableOpenGlTrace = true;
4278 mOpenGlTraceApp = null;
4279 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004280
Christopher Tate181fafa2009-05-14 11:12:14 -07004281 // If the app is being launched for restore or full backup, set it up specially
4282 boolean isRestrictedBackupMode = false;
4283 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4284 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004285 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004286 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4287 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004288
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004289 ensurePackageDexOpt(app.instrumentationInfo != null
4290 ? app.instrumentationInfo.packageName
4291 : app.info.packageName);
4292 if (app.instrumentationClass != null) {
4293 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004294 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004295 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004296 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004297 ApplicationInfo appInfo = app.instrumentationInfo != null
4298 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004299 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004300 if (profileFd != null) {
4301 profileFd = profileFd.dup();
4302 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004303 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004304 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08004305 app.instrumentationArguments, app.instrumentationWatcher,
4306 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
4307 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004308 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004309 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004310 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004311 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 } catch (Exception e) {
4313 // todo: Yikes! What should we do? For now we will try to
4314 // start another process, but that could easily get us in
4315 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317
4318 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004319 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 startProcessLocked(app, "bind fail", processName);
4321 return false;
4322 }
4323
4324 // Remove this record from the list of starting applications.
4325 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004326 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4327 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 mProcessesOnHold.remove(app);
4329
4330 boolean badApp = false;
4331 boolean didSomething = false;
4332
4333 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004334 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004335 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004336 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 && processName.equals(hr.processName)) {
4338 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004339 if (mHeadless) {
4340 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4341 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 didSomething = true;
4343 }
4344 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004345 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 + hr.intent.getComponent().flattenToShortString(), e);
4347 badApp = true;
4348 }
4349 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004350 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004351 }
4352 }
4353
4354 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004355 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004357 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 badApp = true;
4360 }
4361 }
4362
Christopher Tatef46723b2012-01-26 14:19:24 -08004363 // Check if a next-broadcast receiver is in this process...
4364 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004366 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004368 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 }
4371 }
4372
Christopher Tate181fafa2009-05-14 11:12:14 -07004373 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004374 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004375 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004376 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004377 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004378 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4379 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4380 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004381 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004382 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004383 e.printStackTrace();
4384 }
4385 }
4386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 if (badApp) {
4388 // todo: Also need to kill application to deal with all
4389 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004390 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 return false;
4392 }
4393
4394 if (!didSomething) {
4395 updateOomAdjLocked();
4396 }
4397
4398 return true;
4399 }
4400
4401 public final void attachApplication(IApplicationThread thread) {
4402 synchronized (this) {
4403 int callingPid = Binder.getCallingPid();
4404 final long origId = Binder.clearCallingIdentity();
4405 attachApplicationLocked(thread, callingPid);
4406 Binder.restoreCallingIdentity(origId);
4407 }
4408 }
4409
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004410 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004412 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4413 if (stopProfiling) {
4414 synchronized (this) {
4415 if (mProfileProc == r.app) {
4416 if (mProfileFd != null) {
4417 try {
4418 mProfileFd.close();
4419 } catch (IOException e) {
4420 }
4421 clearProfilerLocked();
4422 }
4423 }
4424 }
4425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004426 Binder.restoreCallingIdentity(origId);
4427 }
4428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004430 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004431 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004433
4434 synchronized (this) {
4435 updateEventDispatchingLocked();
4436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 }
4438
Dianne Hackborn661cd522011-08-22 00:26:20 -07004439 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004440 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004441 mWindowManager.showBootMessage(msg, always);
4442 }
4443
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004444 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004445 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004446 final long token = Binder.clearCallingIdentity();
4447 try {
4448 synchronized (this) {
4449 if (mLockScreenShown) {
4450 mLockScreenShown = false;
4451 comeOutOfSleepIfNeededLocked();
4452 }
4453 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004454 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004455 } finally {
4456 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004457 }
4458 }
4459
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004460 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004461 IntentFilter pkgFilter = new IntentFilter();
4462 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4463 pkgFilter.addDataScheme("package");
4464 mContext.registerReceiver(new BroadcastReceiver() {
4465 @Override
4466 public void onReceive(Context context, Intent intent) {
4467 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4468 if (pkgs != null) {
4469 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004470 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004471 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4472 setResultCode(Activity.RESULT_OK);
4473 return;
4474 }
4475 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004476 }
4477 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004478 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004479 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004480
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004481 synchronized (this) {
4482 // Ensure that any processes we had put on hold are now started
4483 // up.
4484 final int NP = mProcessesOnHold.size();
4485 if (NP > 0) {
4486 ArrayList<ProcessRecord> procs =
4487 new ArrayList<ProcessRecord>(mProcessesOnHold);
4488 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004489 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4490 + procs.get(ip));
4491 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004492 }
4493 }
4494
4495 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004496 // Start looking for apps that are abusing wake locks.
4497 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004498 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004499 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004500 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004501 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004502 for (int i=0; i<mStartedUsers.size(); i++) {
4503 UserStartedState uss = mStartedUsers.valueAt(i);
4504 if (uss.mState == UserStartedState.STATE_BOOTING) {
4505 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004506 final int userId = mStartedUsers.keyAt(i);
4507 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4508 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4509 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004510 null, null, 0, null, null,
4511 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08004512 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID,
4513 userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004514 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004515 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004516 }
4517 }
4518 }
4519
4520 final void ensureBootCompleted() {
4521 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004522 boolean enableScreen;
4523 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004524 booting = mBooting;
4525 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004526 enableScreen = !mBooted;
4527 mBooted = true;
4528 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004529
4530 if (booting) {
4531 finishBooting();
4532 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004533
4534 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004535 enableScreenAfterBoot();
4536 }
4537 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004538
4539 public final void activityResumed(IBinder token) {
4540 final long origId = Binder.clearCallingIdentity();
4541 mMainStack.activityResumed(token);
4542 Binder.restoreCallingIdentity(origId);
4543 }
4544
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004545 public final void activityPaused(IBinder token) {
4546 final long origId = Binder.clearCallingIdentity();
4547 mMainStack.activityPaused(token, false);
4548 Binder.restoreCallingIdentity(origId);
4549 }
4550
4551 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4552 CharSequence description) {
4553 if (localLOGV) Slog.v(
4554 TAG, "Activity stopped: token=" + token);
4555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 // Refuse possible leaked file descriptors
4557 if (icicle != null && icicle.hasFileDescriptors()) {
4558 throw new IllegalArgumentException("File descriptors passed in Bundle");
4559 }
4560
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004561 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562
4563 final long origId = Binder.clearCallingIdentity();
4564
4565 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004566 r = mMainStack.isInStackLocked(token);
4567 if (r != null) {
4568 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
4570 }
4571
4572 if (r != null) {
4573 sendPendingThumbnail(r, null, null, null, false);
4574 }
4575
4576 trimApplications();
4577
4578 Binder.restoreCallingIdentity(origId);
4579 }
4580
4581 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004582 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004583 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
4585
4586 public String getCallingPackage(IBinder token) {
4587 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004588 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn7b924672013-04-11 18:08:42 -07004589 return r != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 }
4591 }
4592
4593 public ComponentName getCallingActivity(IBinder token) {
4594 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004595 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 return r != null ? r.intent.getComponent() : null;
4597 }
4598 }
4599
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004600 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004601 ActivityRecord r = mMainStack.isInStackLocked(token);
4602 if (r == null) {
4603 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004605 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 }
4607
4608 public ComponentName getActivityClassForToken(IBinder token) {
4609 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004610 ActivityRecord r = mMainStack.isInStackLocked(token);
4611 if (r == null) {
4612 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004614 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 }
4616 }
4617
4618 public String getPackageForToken(IBinder token) {
4619 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004620 ActivityRecord r = mMainStack.isInStackLocked(token);
4621 if (r == null) {
4622 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004623 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004624 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004625 }
4626 }
4627
4628 public IIntentSender getIntentSender(int type,
4629 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004630 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004631 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004632 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004633 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004634 if (intents != null) {
4635 if (intents.length < 1) {
4636 throw new IllegalArgumentException("Intents array length must be >= 1");
4637 }
4638 for (int i=0; i<intents.length; i++) {
4639 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004640 if (intent != null) {
4641 if (intent.hasFileDescriptors()) {
4642 throw new IllegalArgumentException("File descriptors passed in Intent");
4643 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004644 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004645 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4646 throw new IllegalArgumentException(
4647 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4648 }
4649 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004650 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004651 }
4652 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004653 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004654 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004655 }
4656 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004657 if (options != null) {
4658 if (options.hasFileDescriptors()) {
4659 throw new IllegalArgumentException("File descriptors passed in options");
4660 }
4661 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 synchronized(this) {
4664 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004665 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004666 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004667 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004668 "getIntentSender", null);
4669 if (origUserId == UserHandle.USER_CURRENT) {
4670 // We don't want to evaluate this until the pending intent is
4671 // actually executed. However, we do want to always do the
4672 // security checking for it above.
4673 userId = UserHandle.USER_CURRENT;
4674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004676 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004677 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004678 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4679 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004680 String msg = "Permission Denial: getIntentSender() from pid="
4681 + Binder.getCallingPid()
4682 + ", uid=" + Binder.getCallingUid()
4683 + ", (need uid=" + uid + ")"
4684 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004685 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004686 throw new SecurityException(msg);
4687 }
4688 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004689
4690 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004691 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004693 } catch (RemoteException e) {
4694 throw new SecurityException(e);
4695 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004696 }
4697 }
4698
Dianne Hackborn41203752012-08-31 14:05:51 -07004699 IIntentSender getIntentSenderLocked(int type, String packageName,
4700 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004701 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4702 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004703 if (DEBUG_MU)
4704 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004705 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004706 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004707 activity = mMainStack.isInStackLocked(token);
4708 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004709 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004710 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004711 if (activity.finishing) {
4712 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004714 }
4715
4716 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4717 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4718 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4719 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4720 |PendingIntent.FLAG_UPDATE_CURRENT);
4721
4722 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4723 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004724 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004725 WeakReference<PendingIntentRecord> ref;
4726 ref = mIntentSenderRecords.get(key);
4727 PendingIntentRecord rec = ref != null ? ref.get() : null;
4728 if (rec != null) {
4729 if (!cancelCurrent) {
4730 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004731 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004732 rec.key.requestIntent.replaceExtras(intents != null ?
4733 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004734 }
4735 if (intents != null) {
4736 intents[intents.length-1] = rec.key.requestIntent;
4737 rec.key.allIntents = intents;
4738 rec.key.allResolvedTypes = resolvedTypes;
4739 } else {
4740 rec.key.allIntents = null;
4741 rec.key.allResolvedTypes = null;
4742 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004744 return rec;
4745 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004746 rec.canceled = true;
4747 mIntentSenderRecords.remove(key);
4748 }
4749 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 return rec;
4751 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004752 rec = new PendingIntentRecord(this, key, callingUid);
4753 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004754 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004755 if (activity.pendingResults == null) {
4756 activity.pendingResults
4757 = new HashSet<WeakReference<PendingIntentRecord>>();
4758 }
4759 activity.pendingResults.add(rec.ref);
4760 }
4761 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004762 }
4763
4764 public void cancelIntentSender(IIntentSender sender) {
4765 if (!(sender instanceof PendingIntentRecord)) {
4766 return;
4767 }
4768 synchronized(this) {
4769 PendingIntentRecord rec = (PendingIntentRecord)sender;
4770 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004771 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004772 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4773 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 String msg = "Permission Denial: cancelIntentSender() from pid="
4775 + Binder.getCallingPid()
4776 + ", uid=" + Binder.getCallingUid()
4777 + " is not allowed to cancel packges "
4778 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004779 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004780 throw new SecurityException(msg);
4781 }
4782 } catch (RemoteException e) {
4783 throw new SecurityException(e);
4784 }
4785 cancelIntentSenderLocked(rec, true);
4786 }
4787 }
4788
4789 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4790 rec.canceled = true;
4791 mIntentSenderRecords.remove(rec.key);
4792 if (cleanActivity && rec.key.activity != null) {
4793 rec.key.activity.pendingResults.remove(rec.ref);
4794 }
4795 }
4796
4797 public String getPackageForIntentSender(IIntentSender pendingResult) {
4798 if (!(pendingResult instanceof PendingIntentRecord)) {
4799 return null;
4800 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004801 try {
4802 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4803 return res.key.packageName;
4804 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 }
4806 return null;
4807 }
4808
Christopher Tatec4a07d12012-04-06 14:19:13 -07004809 public int getUidForIntentSender(IIntentSender sender) {
4810 if (sender instanceof PendingIntentRecord) {
4811 try {
4812 PendingIntentRecord res = (PendingIntentRecord)sender;
4813 return res.uid;
4814 } catch (ClassCastException e) {
4815 }
4816 }
4817 return -1;
4818 }
4819
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004820 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4821 if (!(pendingResult instanceof PendingIntentRecord)) {
4822 return false;
4823 }
4824 try {
4825 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4826 if (res.key.allIntents == null) {
4827 return false;
4828 }
4829 for (int i=0; i<res.key.allIntents.length; i++) {
4830 Intent intent = res.key.allIntents[i];
4831 if (intent.getPackage() != null && intent.getComponent() != null) {
4832 return false;
4833 }
4834 }
4835 return true;
4836 } catch (ClassCastException e) {
4837 }
4838 return false;
4839 }
4840
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004841 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4842 if (!(pendingResult instanceof PendingIntentRecord)) {
4843 return false;
4844 }
4845 try {
4846 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4847 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4848 return true;
4849 }
4850 return false;
4851 } catch (ClassCastException e) {
4852 }
4853 return false;
4854 }
4855
Dianne Hackborn81038902012-11-26 17:04:09 -08004856 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4857 if (!(pendingResult instanceof PendingIntentRecord)) {
4858 return null;
4859 }
4860 try {
4861 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4862 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4863 } catch (ClassCastException e) {
4864 }
4865 return null;
4866 }
4867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004868 public void setProcessLimit(int max) {
4869 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4870 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004871 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004872 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004873 mProcessLimitOverride = max;
4874 }
4875 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 }
4877
4878 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004879 synchronized (this) {
4880 return mProcessLimitOverride;
4881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004882 }
4883
4884 void foregroundTokenDied(ForegroundToken token) {
4885 synchronized (ActivityManagerService.this) {
4886 synchronized (mPidsSelfLocked) {
4887 ForegroundToken cur
4888 = mForegroundProcesses.get(token.pid);
4889 if (cur != token) {
4890 return;
4891 }
4892 mForegroundProcesses.remove(token.pid);
4893 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4894 if (pr == null) {
4895 return;
4896 }
4897 pr.forcingToForeground = null;
4898 pr.foregroundServices = false;
4899 }
4900 updateOomAdjLocked();
4901 }
4902 }
4903
4904 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4905 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4906 "setProcessForeground()");
4907 synchronized(this) {
4908 boolean changed = false;
4909
4910 synchronized (mPidsSelfLocked) {
4911 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004912 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004913 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914 return;
4915 }
4916 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4917 if (oldToken != null) {
4918 oldToken.token.unlinkToDeath(oldToken, 0);
4919 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004920 if (pr != null) {
4921 pr.forcingToForeground = null;
4922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 changed = true;
4924 }
4925 if (isForeground && token != null) {
4926 ForegroundToken newToken = new ForegroundToken() {
4927 public void binderDied() {
4928 foregroundTokenDied(this);
4929 }
4930 };
4931 newToken.pid = pid;
4932 newToken.token = token;
4933 try {
4934 token.linkToDeath(newToken, 0);
4935 mForegroundProcesses.put(pid, newToken);
4936 pr.forcingToForeground = token;
4937 changed = true;
4938 } catch (RemoteException e) {
4939 // If the process died while doing this, we will later
4940 // do the cleanup with the process death link.
4941 }
4942 }
4943 }
4944
4945 if (changed) {
4946 updateOomAdjLocked();
4947 }
4948 }
4949 }
4950
4951 // =========================================================
4952 // PERMISSIONS
4953 // =========================================================
4954
4955 static class PermissionController extends IPermissionController.Stub {
4956 ActivityManagerService mActivityManagerService;
4957 PermissionController(ActivityManagerService activityManagerService) {
4958 mActivityManagerService = activityManagerService;
4959 }
4960
4961 public boolean checkPermission(String permission, int pid, int uid) {
4962 return mActivityManagerService.checkPermission(permission, pid,
4963 uid) == PackageManager.PERMISSION_GRANTED;
4964 }
4965 }
4966
Ben Gruver4efe9402013-04-02 21:18:41 -07004967 class IntentFirewallInterface implements IntentFirewall.AMSInterface {
4968 public int checkComponentPermission(String permission, int pid, int uid,
4969 int owningUid, boolean exported) {
4970 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid,
4971 owningUid, exported);
4972 }
Ben Gruvera4879c32013-04-08 14:27:37 -07004973
4974 public Object getAMSLock() {
4975 return ActivityManagerService.this;
4976 }
Ben Gruver4efe9402013-04-02 21:18:41 -07004977 }
4978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 /**
4980 * This can be called with or without the global lock held.
4981 */
4982 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004983 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 // We might be performing an operation on behalf of an indirect binder
4985 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4986 // client identity accordingly before proceeding.
4987 Identity tlsIdentity = sCallerIdentity.get();
4988 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004989 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4991 uid = tlsIdentity.uid;
4992 pid = tlsIdentity.pid;
4993 }
4994
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004995 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004996 return PackageManager.PERMISSION_GRANTED;
4997 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004998
4999 return ActivityManager.checkComponentPermission(permission, uid,
5000 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 }
5002
5003 /**
5004 * As the only public entry point for permissions checking, this method
5005 * can enforce the semantic that requesting a check on a null global
5006 * permission is automatically denied. (Internally a null permission
5007 * string is used when calling {@link #checkComponentPermission} in cases
5008 * when only uid-based security is needed.)
5009 *
5010 * This can be called with or without the global lock held.
5011 */
5012 public int checkPermission(String permission, int pid, int uid) {
5013 if (permission == null) {
5014 return PackageManager.PERMISSION_DENIED;
5015 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005016 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 }
5018
5019 /**
5020 * Binder IPC calls go through the public entry point.
5021 * This can be called with or without the global lock held.
5022 */
5023 int checkCallingPermission(String permission) {
5024 return checkPermission(permission,
5025 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005026 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005027 }
5028
5029 /**
5030 * This can be called with or without the global lock held.
5031 */
5032 void enforceCallingPermission(String permission, String func) {
5033 if (checkCallingPermission(permission)
5034 == PackageManager.PERMISSION_GRANTED) {
5035 return;
5036 }
5037
5038 String msg = "Permission Denial: " + func + " from pid="
5039 + Binder.getCallingPid()
5040 + ", uid=" + Binder.getCallingUid()
5041 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005042 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005043 throw new SecurityException(msg);
5044 }
5045
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005046 /**
5047 * Determine if UID is holding permissions required to access {@link Uri} in
5048 * the given {@link ProviderInfo}. Final permission checking is always done
5049 * in {@link ContentProvider}.
5050 */
5051 private final boolean checkHoldingPermissionsLocked(
5052 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005053 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5054 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005055
5056 if (pi.applicationInfo.uid == uid) {
5057 return true;
5058 } else if (!pi.exported) {
5059 return false;
5060 }
5061
5062 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5063 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005065 // check if target holds top-level <provider> permissions
5066 if (!readMet && pi.readPermission != null
5067 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5068 readMet = true;
5069 }
5070 if (!writeMet && pi.writePermission != null
5071 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5072 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005073 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005074
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005075 // track if unprotected read/write is allowed; any denied
5076 // <path-permission> below removes this ability
5077 boolean allowDefaultRead = pi.readPermission == null;
5078 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005079
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005080 // check if target holds any <path-permission> that match uri
5081 final PathPermission[] pps = pi.pathPermissions;
5082 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005083 final String path = uri.getPath();
5084 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005085 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005086 i--;
5087 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005088 if (pp.match(path)) {
5089 if (!readMet) {
5090 final String pprperm = pp.getReadPermission();
5091 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5092 + pprperm + " for " + pp.getPath()
5093 + ": match=" + pp.match(path)
5094 + " check=" + pm.checkUidPermission(pprperm, uid));
5095 if (pprperm != null) {
5096 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5097 readMet = true;
5098 } else {
5099 allowDefaultRead = false;
5100 }
5101 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005102 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005103 if (!writeMet) {
5104 final String ppwperm = pp.getWritePermission();
5105 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5106 + ppwperm + " for " + pp.getPath()
5107 + ": match=" + pp.match(path)
5108 + " check=" + pm.checkUidPermission(ppwperm, uid));
5109 if (ppwperm != null) {
5110 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5111 writeMet = true;
5112 } else {
5113 allowDefaultWrite = false;
5114 }
5115 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005116 }
5117 }
5118 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005119 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005120
5121 // grant unprotected <provider> read/write, if not blocked by
5122 // <path-permission> above
5123 if (allowDefaultRead) readMet = true;
5124 if (allowDefaultWrite) writeMet = true;
5125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 } catch (RemoteException e) {
5127 return false;
5128 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005129
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005130 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 }
5132
5133 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5134 int modeFlags) {
5135 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005136 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 return true;
5138 }
5139 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5140 if (perms == null) return false;
5141 UriPermission perm = perms.get(uri);
5142 if (perm == null) return false;
5143 return (modeFlags&perm.modeFlags) == modeFlags;
5144 }
5145
5146 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005147 enforceNotIsolatedCaller("checkUriPermission");
5148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 // Another redirected-binder-call permissions check as in
5150 // {@link checkComponentPermission}.
5151 Identity tlsIdentity = sCallerIdentity.get();
5152 if (tlsIdentity != null) {
5153 uid = tlsIdentity.uid;
5154 pid = tlsIdentity.pid;
5155 }
5156
5157 // Our own process gets to do everything.
5158 if (pid == MY_PID) {
5159 return PackageManager.PERMISSION_GRANTED;
5160 }
5161 synchronized(this) {
5162 return checkUriPermissionLocked(uri, uid, modeFlags)
5163 ? PackageManager.PERMISSION_GRANTED
5164 : PackageManager.PERMISSION_DENIED;
5165 }
5166 }
5167
Dianne Hackborn39792d22010-08-19 18:01:52 -07005168 /**
5169 * Check if the targetPkg can be granted permission to access uri by
5170 * the callingUid using the given modeFlags. Throws a security exception
5171 * if callingUid is not allowed to do this. Returns the uid of the target
5172 * if the URI permission grant should be performed; returns -1 if it is not
5173 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005174 * If you already know the uid of the target, you can supply it in
5175 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005176 */
5177 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005178 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5180 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5181 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005182 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183 }
5184
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005185 if (targetPkg != null) {
5186 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5187 "Checking grant " + targetPkg + " permission to " + uri);
5188 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005189
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005190 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191
5192 // If this is not a content: uri, we can't do anything with it.
5193 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005194 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005195 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005196 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 }
5198
5199 String name = uri.getAuthority();
5200 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005201 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005202 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005203 if (cpr != null) {
5204 pi = cpr.info;
5205 } else {
5206 try {
5207 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005208 PackageManager.GET_URI_PERMISSION_PATTERNS,
5209 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 } catch (RemoteException ex) {
5211 }
5212 }
5213 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005214 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005215 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 }
5217
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005218 int targetUid = lastTargetUid;
5219 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005220 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005221 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005222 if (targetUid < 0) {
5223 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5224 "Can't grant URI permission no uid for: " + targetPkg);
5225 return -1;
5226 }
5227 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005228 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 }
5231
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005232 if (targetUid >= 0) {
5233 // First... does the target actually need this permission?
5234 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5235 // No need to grant the target this permission.
5236 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5237 "Target " + targetPkg + " already has full permission to " + uri);
5238 return -1;
5239 }
5240 } else {
5241 // First... there is no target package, so can anyone access it?
5242 boolean allowed = pi.exported;
5243 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5244 if (pi.readPermission != null) {
5245 allowed = false;
5246 }
5247 }
5248 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5249 if (pi.writePermission != null) {
5250 allowed = false;
5251 }
5252 }
5253 if (allowed) {
5254 return -1;
5255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256 }
5257
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005258 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005259 if (!pi.grantUriPermissions) {
5260 throw new SecurityException("Provider " + pi.packageName
5261 + "/" + pi.name
5262 + " does not allow granting of Uri permissions (uri "
5263 + uri + ")");
5264 }
5265 if (pi.uriPermissionPatterns != null) {
5266 final int N = pi.uriPermissionPatterns.length;
5267 boolean allowed = false;
5268 for (int i=0; i<N; i++) {
5269 if (pi.uriPermissionPatterns[i] != null
5270 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5271 allowed = true;
5272 break;
5273 }
5274 }
5275 if (!allowed) {
5276 throw new SecurityException("Provider " + pi.packageName
5277 + "/" + pi.name
5278 + " does not allow granting of permission to path of Uri "
5279 + uri);
5280 }
5281 }
5282
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005283 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005285 if (callingUid != Process.myUid()) {
5286 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5287 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5288 throw new SecurityException("Uid " + callingUid
5289 + " does not have permission to uri " + uri);
5290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 }
5292 }
5293
Dianne Hackborn39792d22010-08-19 18:01:52 -07005294 return targetUid;
5295 }
5296
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005297 public int checkGrantUriPermission(int callingUid, String targetPkg,
5298 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005299 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005300 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005301 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005302 }
5303 }
5304
Dianne Hackborn39792d22010-08-19 18:01:52 -07005305 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5306 Uri uri, int modeFlags, UriPermissionOwner owner) {
5307 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5308 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5309 if (modeFlags == 0) {
5310 return;
5311 }
5312
5313 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005314 // to the uri, and the target doesn't. Let's now give this to
5315 // the target.
5316
Joe Onorato8a9b2202010-02-26 18:56:32 -08005317 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005318 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005320 HashMap<Uri, UriPermission> targetUris
5321 = mGrantedUriPermissions.get(targetUid);
5322 if (targetUris == null) {
5323 targetUris = new HashMap<Uri, UriPermission>();
5324 mGrantedUriPermissions.put(targetUid, targetUris);
5325 }
5326
5327 UriPermission perm = targetUris.get(uri);
5328 if (perm == null) {
5329 perm = new UriPermission(targetUid, uri);
5330 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005334 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005335 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005336 } else {
5337 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5338 perm.readOwners.add(owner);
5339 owner.addReadPermission(perm);
5340 }
5341 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5342 perm.writeOwners.add(owner);
5343 owner.addWritePermission(perm);
5344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 }
5346 }
5347
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005348 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5349 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005350 if (targetPkg == null) {
5351 throw new NullPointerException("targetPkg");
5352 }
5353
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005354 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005355 if (targetUid < 0) {
5356 return;
5357 }
5358
5359 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5360 }
5361
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005362 static class NeededUriGrants extends ArrayList<Uri> {
5363 final String targetPkg;
5364 final int targetUid;
5365 final int flags;
5366
5367 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5368 targetPkg = _targetPkg;
5369 targetUid = _targetUid;
5370 flags = _flags;
5371 }
5372 }
5373
Dianne Hackborn39792d22010-08-19 18:01:52 -07005374 /**
5375 * Like checkGrantUriPermissionLocked, but takes an Intent.
5376 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005377 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5378 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005379 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005380 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5381 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005382 + " from " + intent + "; flags=0x"
5383 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5384
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005385 if (targetPkg == null) {
5386 throw new NullPointerException("targetPkg");
5387 }
5388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005390 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005391 }
5392 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005393 ClipData clip = intent.getClipData();
5394 if (data == null && clip == null) {
5395 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005396 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005397 if (data != null) {
5398 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5399 mode, needed != null ? needed.targetUid : -1);
5400 if (target > 0) {
5401 if (needed == null) {
5402 needed = new NeededUriGrants(targetPkg, target, mode);
5403 }
5404 needed.add(data);
5405 }
5406 }
5407 if (clip != null) {
5408 for (int i=0; i<clip.getItemCount(); i++) {
5409 Uri uri = clip.getItemAt(i).getUri();
5410 if (uri != null) {
5411 int target = -1;
5412 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5413 mode, needed != null ? needed.targetUid : -1);
5414 if (target > 0) {
5415 if (needed == null) {
5416 needed = new NeededUriGrants(targetPkg, target, mode);
5417 }
5418 needed.add(uri);
5419 }
5420 } else {
5421 Intent clipIntent = clip.getItemAt(i).getIntent();
5422 if (clipIntent != null) {
5423 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5424 callingUid, targetPkg, clipIntent, mode, needed);
5425 if (newNeeded != null) {
5426 needed = newNeeded;
5427 }
5428 }
5429 }
5430 }
5431 }
5432
5433 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005434 }
5435
5436 /**
5437 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5438 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005439 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5440 UriPermissionOwner owner) {
5441 if (needed != null) {
5442 for (int i=0; i<needed.size(); i++) {
5443 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5444 needed.get(i), needed.flags, owner);
5445 }
5446 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005447 }
5448
5449 void grantUriPermissionFromIntentLocked(int callingUid,
5450 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005451 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005452 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005453 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 return;
5455 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005456
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005457 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 }
5459
5460 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5461 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005462 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 synchronized(this) {
5464 final ProcessRecord r = getRecordForAppLocked(caller);
5465 if (r == null) {
5466 throw new SecurityException("Unable to find app for caller "
5467 + caller
5468 + " when granting permission to uri " + uri);
5469 }
5470 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005471 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 }
5473 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005474 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 }
5476
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005477 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 null);
5479 }
5480 }
5481
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005482 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5484 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5485 HashMap<Uri, UriPermission> perms
5486 = mGrantedUriPermissions.get(perm.uid);
5487 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005488 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005489 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 perms.remove(perm.uri);
5491 if (perms.size() == 0) {
5492 mGrantedUriPermissions.remove(perm.uid);
5493 }
5494 }
5495 }
5496 }
5497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5499 int modeFlags) {
5500 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5501 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5502 if (modeFlags == 0) {
5503 return;
5504 }
5505
Joe Onorato8a9b2202010-02-26 18:56:32 -08005506 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005507 "Revoking all granted permissions to " + uri);
5508
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005509 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510
5511 final String authority = uri.getAuthority();
5512 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005513 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005514 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 if (cpr != null) {
5516 pi = cpr.info;
5517 } else {
5518 try {
5519 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005520 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 } catch (RemoteException ex) {
5522 }
5523 }
5524 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005525 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 return;
5527 }
5528
5529 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005530 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005531 // Right now, if you are not the original owner of the permission,
5532 // you are not allowed to revoke it.
5533 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5534 throw new SecurityException("Uid " + callingUid
5535 + " does not have permission to uri " + uri);
5536 //}
5537 }
5538
5539 // Go through all of the permissions and remove any that match.
5540 final List<String> SEGMENTS = uri.getPathSegments();
5541 if (SEGMENTS != null) {
5542 final int NS = SEGMENTS.size();
5543 int N = mGrantedUriPermissions.size();
5544 for (int i=0; i<N; i++) {
5545 HashMap<Uri, UriPermission> perms
5546 = mGrantedUriPermissions.valueAt(i);
5547 Iterator<UriPermission> it = perms.values().iterator();
5548 toploop:
5549 while (it.hasNext()) {
5550 UriPermission perm = it.next();
5551 Uri targetUri = perm.uri;
5552 if (!authority.equals(targetUri.getAuthority())) {
5553 continue;
5554 }
5555 List<String> targetSegments = targetUri.getPathSegments();
5556 if (targetSegments == null) {
5557 continue;
5558 }
5559 if (targetSegments.size() < NS) {
5560 continue;
5561 }
5562 for (int j=0; j<NS; j++) {
5563 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5564 continue toploop;
5565 }
5566 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005567 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005568 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 perm.clearModes(modeFlags);
5570 if (perm.modeFlags == 0) {
5571 it.remove();
5572 }
5573 }
5574 if (perms.size() == 0) {
5575 mGrantedUriPermissions.remove(
5576 mGrantedUriPermissions.keyAt(i));
5577 N--;
5578 i--;
5579 }
5580 }
5581 }
5582 }
5583
5584 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5585 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005586 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 synchronized(this) {
5588 final ProcessRecord r = getRecordForAppLocked(caller);
5589 if (r == null) {
5590 throw new SecurityException("Unable to find app for caller "
5591 + caller
5592 + " when revoking permission to uri " + uri);
5593 }
5594 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005595 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 return;
5597 }
5598
5599 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5600 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5601 if (modeFlags == 0) {
5602 return;
5603 }
5604
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005605 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606
5607 final String authority = uri.getAuthority();
5608 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005609 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 if (cpr != null) {
5611 pi = cpr.info;
5612 } else {
5613 try {
5614 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005615 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 } catch (RemoteException ex) {
5617 }
5618 }
5619 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005620 Slog.w(TAG, "No content provider found for permission revoke: "
5621 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 return;
5623 }
5624
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005625 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 }
5627 }
5628
Dianne Hackborn7e269642010-08-25 19:50:20 -07005629 @Override
5630 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005631 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005632 synchronized(this) {
5633 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5634 return owner.getExternalTokenLocked();
5635 }
5636 }
5637
5638 @Override
5639 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5640 Uri uri, int modeFlags) {
5641 synchronized(this) {
5642 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5643 if (owner == null) {
5644 throw new IllegalArgumentException("Unknown owner: " + token);
5645 }
5646 if (fromUid != Binder.getCallingUid()) {
5647 if (Binder.getCallingUid() != Process.myUid()) {
5648 // Only system code can grant URI permissions on behalf
5649 // of other users.
5650 throw new SecurityException("nice try");
5651 }
5652 }
5653 if (targetPkg == null) {
5654 throw new IllegalArgumentException("null target");
5655 }
5656 if (uri == null) {
5657 throw new IllegalArgumentException("null uri");
5658 }
5659
5660 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5661 }
5662 }
5663
5664 @Override
5665 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5666 synchronized(this) {
5667 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5668 if (owner == null) {
5669 throw new IllegalArgumentException("Unknown owner: " + token);
5670 }
5671
5672 if (uri == null) {
5673 owner.removeUriPermissionsLocked(mode);
5674 } else {
5675 owner.removeUriPermissionLocked(uri, mode);
5676 }
5677 }
5678 }
5679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5681 synchronized (this) {
5682 ProcessRecord app =
5683 who != null ? getRecordForAppLocked(who) : null;
5684 if (app == null) return;
5685
5686 Message msg = Message.obtain();
5687 msg.what = WAIT_FOR_DEBUGGER_MSG;
5688 msg.obj = app;
5689 msg.arg1 = waiting ? 1 : 0;
5690 mHandler.sendMessage(msg);
5691 }
5692 }
5693
5694 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005695 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5696 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005698 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005699 outInfo.threshold = homeAppMem;
5700 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5701 outInfo.hiddenAppThreshold = hiddenAppMem;
5702 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005703 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005704 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5705 ProcessList.VISIBLE_APP_ADJ);
5706 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5707 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 }
5709
5710 // =========================================================
5711 // TASK MANAGEMENT
5712 // =========================================================
5713
Craig Mautner2ad92072013-02-25 16:19:24 -08005714 public List getTasks(int maxNum, int flags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 IThumbnailReceiver receiver) {
Craig Mautner2ad92072013-02-25 16:19:24 -08005716 ArrayList list = new ArrayList();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717
Craig Mautner2ad92072013-02-25 16:19:24 -08005718 PendingThumbnailsRecord pending = null;
5719 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005720 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721
5722 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005723 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5725 + ", receiver=" + receiver);
5726
5727 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5728 != PackageManager.PERMISSION_GRANTED) {
5729 if (receiver != null) {
5730 // If the caller wants to wait for pending thumbnails,
5731 // it ain't gonna get them.
5732 try {
5733 receiver.finished();
5734 } catch (RemoteException ex) {
5735 }
5736 }
5737 String msg = "Permission Denial: getTasks() from pid="
5738 + Binder.getCallingPid()
5739 + ", uid=" + Binder.getCallingUid()
5740 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005741 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 throw new SecurityException(msg);
5743 }
5744
Craig Mautner2ad92072013-02-25 16:19:24 -08005745 int pos = mMainStack.mHistory.size()-1;
5746 ActivityRecord next =
5747 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
5748 ActivityRecord top = null;
5749 TaskRecord curTask = null;
5750 int numActivities = 0;
5751 int numRunning = 0;
5752 while (pos >= 0 && maxNum > 0) {
5753 final ActivityRecord r = next;
5754 pos--;
5755 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756
Craig Mautner2ad92072013-02-25 16:19:24 -08005757 // Initialize state for next task if needed.
5758 if (top == null ||
5759 (top.state == ActivityState.INITIALIZING
5760 && top.task == r.task)) {
5761 top = r;
5762 curTask = r.task;
5763 numActivities = numRunning = 0;
5764 }
5765
5766 // Add 'r' into the current task.
5767 numActivities++;
5768 if (r.app != null && r.app.thread != null) {
5769 numRunning++;
5770 }
5771
5772 if (localLOGV) Slog.v(
5773 TAG, r.intent.getComponent().flattenToShortString()
5774 + ": task=" + r.task);
5775
5776 // If the next one is a different task, generate a new
5777 // TaskInfo entry for what we have.
5778 if (next == null || next.task != curTask) {
5779 ActivityManager.RunningTaskInfo ci
5780 = new ActivityManager.RunningTaskInfo();
5781 ci.id = curTask.taskId;
5782 ci.baseActivity = r.intent.getComponent();
5783 ci.topActivity = top.intent.getComponent();
5784 if (top.thumbHolder != null) {
5785 ci.description = top.thumbHolder.lastDescription;
5786 }
5787 ci.numActivities = numActivities;
5788 ci.numRunning = numRunning;
5789 //System.out.println(
5790 // "#" + maxNum + ": " + " descr=" + ci.description);
5791 if (ci.thumbnail == null && receiver != null) {
5792 if (localLOGV) Slog.v(
5793 TAG, "State=" + top.state + "Idle=" + top.idle
5794 + " app=" + top.app
5795 + " thr=" + (top.app != null ? top.app.thread : null));
5796 if (top.state == ActivityState.RESUMED
5797 || top.state == ActivityState.PAUSING) {
5798 if (top.idle && top.app != null
5799 && top.app.thread != null) {
5800 topRecord = top;
5801 topThumbnail = top.app.thread;
5802 } else {
5803 top.thumbnailNeeded = true;
5804 }
5805 }
5806 if (pending == null) {
5807 pending = new PendingThumbnailsRecord(receiver);
5808 }
5809 pending.pendingRecords.add(top);
5810 }
5811 list.add(ci);
5812 maxNum--;
5813 top = null;
5814 }
5815 }
5816
5817 if (pending != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 mPendingThumbnails.add(pending);
5819 }
5820 }
5821
Joe Onorato8a9b2202010-02-26 18:56:32 -08005822 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823
Craig Mautner2ad92072013-02-25 16:19:24 -08005824 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005825 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005827 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005829 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005830 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 }
5832 }
5833
5834 if (pending == null && receiver != null) {
5835 // In this case all thumbnails were available and the client
5836 // is being asked to be told when the remaining ones come in...
5837 // which is unusually, since the top-most currently running
5838 // activity should never have a canned thumbnail! Oh well.
5839 try {
5840 receiver.finished();
5841 } catch (RemoteException ex) {
5842 }
5843 }
5844
5845 return list;
5846 }
5847
5848 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005849 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005850 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5851 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 synchronized (this) {
5854 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5855 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005856 final boolean detailed = checkCallingPermission(
5857 android.Manifest.permission.GET_DETAILED_TASKS)
5858 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005860 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 final int N = mRecentTasks.size();
5863 ArrayList<ActivityManager.RecentTaskInfo> res
5864 = new ArrayList<ActivityManager.RecentTaskInfo>(
5865 maxNum < N ? maxNum : N);
5866 for (int i=0; i<N && maxNum > 0; i++) {
5867 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005868 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005869 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005870 // Return the entry if desired by the caller. We always return
5871 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005872 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005873 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5874 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005875
Dianne Hackborn905577f2011-09-07 18:31:28 -07005876 if (i == 0
5877 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 || (tr.intent == null)
5879 || ((tr.intent.getFlags()
5880 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5881 ActivityManager.RecentTaskInfo rti
5882 = new ActivityManager.RecentTaskInfo();
5883 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005884 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 rti.baseIntent = new Intent(
5886 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005887 if (!detailed) {
5888 rti.baseIntent.replaceExtras((Bundle)null);
5889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005891 rti.description = tr.lastDescription;
5892
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005893 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5894 // Check whether this activity is currently available.
5895 try {
5896 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005897 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005898 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005899 continue;
5900 }
5901 } else if (rti.baseIntent != null) {
5902 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005903 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005904 continue;
5905 }
5906 }
5907 } catch (RemoteException e) {
5908 // Will never happen.
5909 }
5910 }
5911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 res.add(rti);
5913 maxNum--;
5914 }
5915 }
5916 return res;
5917 }
5918 }
5919
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005920 private TaskRecord taskForIdLocked(int id) {
5921 final int N = mRecentTasks.size();
5922 for (int i=0; i<N; i++) {
5923 TaskRecord tr = mRecentTasks.get(i);
5924 if (tr.taskId == id) {
5925 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005926 }
5927 }
5928 return null;
5929 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005930
5931 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5932 synchronized (this) {
5933 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5934 "getTaskThumbnails()");
5935 TaskRecord tr = taskForIdLocked(id);
5936 if (tr != null) {
5937 return mMainStack.getTaskThumbnailsLocked(tr);
5938 }
5939 }
5940 return null;
5941 }
5942
Dianne Hackborn15491c62012-09-19 10:59:14 -07005943 public Bitmap getTaskTopThumbnail(int id) {
5944 synchronized (this) {
5945 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5946 "getTaskTopThumbnail()");
5947 TaskRecord tr = taskForIdLocked(id);
5948 if (tr != null) {
5949 return mMainStack.getTaskTopThumbnailLocked(tr);
5950 }
5951 }
5952 return null;
5953 }
5954
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005955 public boolean removeSubTask(int taskId, int subTaskIndex) {
5956 synchronized (this) {
5957 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5958 "removeSubTask()");
5959 long ident = Binder.clearCallingIdentity();
5960 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005961 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5962 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005963 } finally {
5964 Binder.restoreCallingIdentity(ident);
5965 }
5966 }
5967 }
5968
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005969 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5970 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005971 Intent baseIntent = new Intent(
5972 tr.intent != null ? tr.intent : tr.affinityIntent);
5973 ComponentName component = baseIntent.getComponent();
5974 if (component == null) {
5975 Slog.w(TAG, "Now component for base intent of task: " + tr);
5976 return;
5977 }
5978
5979 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005980 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005981
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005982 if (killProcesses) {
5983 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005984 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005985 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005986 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5987 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5988 for (int i=0; i<uids.size(); i++) {
5989 ProcessRecord proc = uids.valueAt(i);
5990 if (proc.userId != tr.userId) {
5991 continue;
5992 }
5993 if (!proc.pkgList.contains(pkg)) {
5994 continue;
5995 }
5996 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005997 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005998 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005999
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006000 // Kill the running processes.
6001 for (int i=0; i<procs.size(); i++) {
6002 ProcessRecord pr = procs.get(i);
6003 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
6004 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006005 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006006 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07006007 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07006008 Process.killProcessQuiet(pr.pid);
6009 } else {
6010 pr.waitingToKill = "remove task";
6011 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006012 }
6013 }
6014 }
6015
6016 public boolean removeTask(int taskId, int flags) {
6017 synchronized (this) {
6018 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
6019 "removeTask()");
6020 long ident = Binder.clearCallingIdentity();
6021 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006022 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
6023 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006024 if (r != null) {
6025 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006026 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006027 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006028 } else {
6029 TaskRecord tr = null;
6030 int i=0;
6031 while (i < mRecentTasks.size()) {
6032 TaskRecord t = mRecentTasks.get(i);
6033 if (t.taskId == taskId) {
6034 tr = t;
6035 break;
6036 }
6037 i++;
6038 }
6039 if (tr != null) {
6040 if (tr.numActivities <= 0) {
6041 // Caller is just removing a recent task that is
6042 // not actively running. That is easy!
6043 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006044 cleanUpRemovedTaskLocked(tr, flags);
6045 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006046 } else {
6047 Slog.w(TAG, "removeTask: task " + taskId
6048 + " does not have activities to remove, "
6049 + " but numActivities=" + tr.numActivities
6050 + ": " + tr);
6051 }
6052 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006053 }
6054 } finally {
6055 Binder.restoreCallingIdentity(ident);
6056 }
6057 }
6058 return false;
6059 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006060
Craig Mautner2ad92072013-02-25 16:19:24 -08006061 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6062 int j;
6063 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
6064 TaskRecord jt = startTask;
6065
6066 // First look backwards
6067 for (j=startIndex-1; j>=0; j--) {
6068 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
6069 if (r.task != jt) {
6070 jt = r.task;
6071 if (affinity.equals(jt.affinity)) {
6072 return j;
6073 }
6074 }
6075 }
6076
6077 // Now look forwards
6078 final int N = mMainStack.mHistory.size();
6079 jt = startTask;
6080 for (j=startIndex+1; j<N; j++) {
6081 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
6082 if (r.task != jt) {
6083 if (affinity.equals(jt.affinity)) {
6084 return j;
6085 }
6086 jt = r.task;
6087 }
6088 }
6089
6090 // Might it be at the top?
6091 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
6092 return N-1;
6093 }
6094
6095 return -1;
6096 }
6097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006099 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006101 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6103 "moveTaskToFront()");
6104
6105 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006106 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6107 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006108 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006109 return;
6110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 final long origId = Binder.clearCallingIdentity();
6112 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006113 TaskRecord tr = taskForIdLocked(task);
6114 if (tr != null) {
6115 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6116 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006118 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6119 // Caller wants the home activity moved with it. To accomplish this,
6120 // we'll just move the home task to the top first.
6121 mMainStack.moveHomeToFrontLocked();
6122 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006123 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006124 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
Craig Mautner2ad92072013-02-25 16:19:24 -08006126 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6127 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
6128 if (hr.task.taskId == task) {
6129 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6130 mMainStack.mUserLeaving = true;
6131 }
6132 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6133 // Caller wants the home activity moved with it. To accomplish this,
6134 // we'll just move the home task to the top first.
6135 mMainStack.moveHomeToFrontLocked();
6136 }
6137 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
6138 return;
6139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 }
6141 } finally {
6142 Binder.restoreCallingIdentity(origId);
6143 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006144 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 }
6146 }
6147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 public void moveTaskToBack(int task) {
6149 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6150 "moveTaskToBack()");
6151
6152 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006153 if (mMainStack.mResumedActivity != null
6154 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006155 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6156 Binder.getCallingUid(), "Task to back")) {
6157 return;
6158 }
6159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006161 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 Binder.restoreCallingIdentity(origId);
6163 }
6164 }
6165
6166 /**
6167 * Moves an activity, and all of the other activities within the same task, to the bottom
6168 * of the history stack. The activity's order within the task is unchanged.
6169 *
6170 * @param token A reference to the activity we wish to move
6171 * @param nonRoot If false then this only works if the activity is the root
6172 * of a task; if true it will work for any activity in a task.
6173 * @return Returns true if the move completed, false if not.
6174 */
6175 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006176 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 synchronized(this) {
6178 final long origId = Binder.clearCallingIdentity();
Craig Mautner2ad92072013-02-25 16:19:24 -08006179 int taskId = getTaskForActivityLocked(token, !nonRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006181 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 }
6183 Binder.restoreCallingIdentity(origId);
6184 }
6185 return false;
6186 }
6187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 public void moveTaskBackwards(int task) {
6189 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6190 "moveTaskBackwards()");
6191
6192 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006193 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6194 Binder.getCallingUid(), "Task backwards")) {
6195 return;
6196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 final long origId = Binder.clearCallingIdentity();
6198 moveTaskBackwardsLocked(task);
6199 Binder.restoreCallingIdentity(origId);
6200 }
6201 }
6202
6203 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006204 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 }
6206
6207 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6208 synchronized(this) {
Craig Mautner2ad92072013-02-25 16:19:24 -08006209 return getTaskForActivityLocked(token, onlyRoot);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211 }
6212
Craig Mautner2ad92072013-02-25 16:19:24 -08006213 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
6214 final int N = mMainStack.mHistory.size();
6215 TaskRecord lastTask = null;
6216 for (int i=0; i<N; i++) {
6217 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
6218 if (r.appToken == token) {
6219 if (!onlyRoot || lastTask != r.task) {
6220 return r.task.taskId;
6221 }
6222 return -1;
6223 }
6224 lastTask = r.task;
6225 }
6226
6227 return -1;
6228 }
6229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 // =========================================================
6231 // THUMBNAILS
6232 // =========================================================
6233
6234 public void reportThumbnail(IBinder token,
6235 Bitmap thumbnail, CharSequence description) {
6236 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6237 final long origId = Binder.clearCallingIdentity();
6238 sendPendingThumbnail(null, token, thumbnail, description, true);
6239 Binder.restoreCallingIdentity(origId);
6240 }
6241
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006242 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 Bitmap thumbnail, CharSequence description, boolean always) {
6244 TaskRecord task = null;
6245 ArrayList receivers = null;
6246
6247 //System.out.println("Send pending thumbnail: " + r);
6248
6249 synchronized(this) {
6250 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006251 r = mMainStack.isInStackLocked(token);
6252 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return;
6254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006256 if (thumbnail == null && r.thumbHolder != null) {
6257 thumbnail = r.thumbHolder.lastThumbnail;
6258 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 }
6260 if (thumbnail == null && !always) {
6261 // If there is no thumbnail, and this entry is not actually
6262 // going away, then abort for now and pick up the next
6263 // thumbnail we get.
6264 return;
6265 }
6266 task = r.task;
6267
6268 int N = mPendingThumbnails.size();
6269 int i=0;
6270 while (i<N) {
6271 PendingThumbnailsRecord pr =
6272 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6273 //System.out.println("Looking in " + pr.pendingRecords);
6274 if (pr.pendingRecords.remove(r)) {
6275 if (receivers == null) {
6276 receivers = new ArrayList();
6277 }
6278 receivers.add(pr);
6279 if (pr.pendingRecords.size() == 0) {
6280 pr.finished = true;
6281 mPendingThumbnails.remove(i);
6282 N--;
6283 continue;
6284 }
6285 }
6286 i++;
6287 }
6288 }
6289
6290 if (receivers != null) {
6291 final int N = receivers.size();
6292 for (int i=0; i<N; i++) {
6293 try {
6294 PendingThumbnailsRecord pr =
6295 (PendingThumbnailsRecord)receivers.get(i);
6296 pr.receiver.newThumbnail(
6297 task != null ? task.taskId : -1, thumbnail, description);
6298 if (pr.finished) {
6299 pr.receiver.finished();
6300 }
6301 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006302 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 }
6304 }
6305 }
6306 }
6307
6308 // =========================================================
6309 // CONTENT PROVIDERS
6310 // =========================================================
6311
Jeff Brown10e89712011-07-08 18:52:57 -07006312 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6313 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006315 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006316 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006317 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 } catch (RemoteException ex) {
6319 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006320 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006321 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6322 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006324 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 for (int i=0; i<N; i++) {
6326 ProviderInfo cpi =
6327 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006328 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6329 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006330 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006331 // This is a singleton provider, but a user besides the
6332 // default user is asking to initialize a process it runs
6333 // in... well, no, it doesn't actually run in this process,
6334 // it runs in the process of the default user. Get rid of it.
6335 providers.remove(i);
6336 N--;
Jun Succa09652013-05-21 17:24:32 +08006337 i--;
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006338 continue;
6339 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006340
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006341 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006342 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006344 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006345 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006347 if (DEBUG_MU)
6348 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 app.pubProviders.put(cpi.name, cpr);
6350 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006351 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 }
6353 }
6354 return providers;
6355 }
6356
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006357 /**
6358 * Check if {@link ProcessRecord} has a possible chance at accessing the
6359 * given {@link ProviderInfo}. Final permission checking is always done
6360 * in {@link ContentProvider}.
6361 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006363 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006365 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006367 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006368 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 return null;
6370 }
6371 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006372 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 == PackageManager.PERMISSION_GRANTED) {
6374 return null;
6375 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006376
6377 PathPermission[] pps = cpi.pathPermissions;
6378 if (pps != null) {
6379 int i = pps.length;
6380 while (i > 0) {
6381 i--;
6382 PathPermission pp = pps[i];
6383 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006384 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006385 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006386 return null;
6387 }
6388 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006389 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006390 == PackageManager.PERMISSION_GRANTED) {
6391 return null;
6392 }
6393 }
6394 }
6395
Dianne Hackbornb424b632010-08-18 15:59:05 -07006396 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6397 if (perms != null) {
6398 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6399 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6400 return null;
6401 }
6402 }
6403 }
6404
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006405 String msg;
6406 if (!cpi.exported) {
6407 msg = "Permission Denial: opening provider " + cpi.name
6408 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6409 + ", uid=" + callingUid + ") that is not exported from uid "
6410 + cpi.applicationInfo.uid;
6411 } else {
6412 msg = "Permission Denial: opening provider " + cpi.name
6413 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6414 + ", uid=" + callingUid + ") requires "
6415 + cpi.readPermission + " or " + cpi.writePermission;
6416 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006417 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 return msg;
6419 }
6420
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006421 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6422 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006423 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 for (int i=0; i<r.conProviders.size(); i++) {
6425 ContentProviderConnection conn = r.conProviders.get(i);
6426 if (conn.provider == cpr) {
6427 if (DEBUG_PROVIDER) Slog.v(TAG,
6428 "Adding provider requested by "
6429 + r.processName + " from process "
6430 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6431 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6432 if (stable) {
6433 conn.stableCount++;
6434 conn.numStableIncs++;
6435 } else {
6436 conn.unstableCount++;
6437 conn.numUnstableIncs++;
6438 }
6439 return conn;
6440 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006441 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006442 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6443 if (stable) {
6444 conn.stableCount = 1;
6445 conn.numStableIncs = 1;
6446 } else {
6447 conn.unstableCount = 1;
6448 conn.numUnstableIncs = 1;
6449 }
6450 cpr.connections.add(conn);
6451 r.conProviders.add(conn);
6452 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006453 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006454 cpr.addExternalProcessHandleLocked(externalProcessToken);
6455 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006456 }
6457
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006458 boolean decProviderCountLocked(ContentProviderConnection conn,
6459 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6460 if (conn != null) {
6461 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006462 if (DEBUG_PROVIDER) Slog.v(TAG,
6463 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006464 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006465 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006466 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6467 if (stable) {
6468 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006469 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006470 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006471 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006472 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6473 cpr.connections.remove(conn);
6474 conn.client.conProviders.remove(conn);
6475 return true;
6476 }
6477 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006478 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006479 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006480 return false;
6481 }
6482
Amith Yamasani742a6712011-05-04 14:49:28 -07006483 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006484 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006486 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 ProviderInfo cpi = null;
6488
6489 synchronized(this) {
6490 ProcessRecord r = null;
6491 if (caller != null) {
6492 r = getRecordForAppLocked(caller);
6493 if (r == null) {
6494 throw new SecurityException(
6495 "Unable to find app for caller " + caller
6496 + " (pid=" + Binder.getCallingPid()
6497 + ") when getting content provider " + name);
6498 }
6499 }
6500
6501 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006502 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006503 boolean providerRunning = cpr != null;
6504 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006506 String msg;
6507 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6508 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 }
6510
6511 if (r != null && cpr.canRunHere(r)) {
6512 // This provider has been published or is in the process
6513 // of being published... but it is also allowed to run
6514 // in the caller's process, so don't make a connection
6515 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006516 ContentProviderHolder holder = cpr.newHolder(null);
6517 // don't give caller the provider object, it needs
6518 // to make its own.
6519 holder.provider = null;
6520 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 }
6522
6523 final long origId = Binder.clearCallingIdentity();
6524
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006525 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006527 conn = incProviderCountLocked(r, cpr, token, stable);
6528 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006529 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006530 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006531 // make sure to count it as being accessed and thus
6532 // back up on the LRU list. This is good because
6533 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006534 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006535 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006536 }
6537
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006538 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006539 if (false) {
6540 if (cpr.name.flattenToShortString().equals(
6541 "com.android.providers.calendar/.CalendarProvider2")) {
6542 Slog.v(TAG, "****************** KILLING "
6543 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006544 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006545 }
6546 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006547 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006548 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6549 // NOTE: there is still a race here where a signal could be
6550 // pending on the process even though we managed to update its
6551 // adj level. Not sure what to do about this, but at least
6552 // the race is now smaller.
6553 if (!success) {
6554 // Uh oh... it looks like the provider's process
6555 // has been killed on us. We need to wait for a new
6556 // process to be started, and make sure its death
6557 // doesn't kill our process.
6558 Slog.i(TAG,
6559 "Existing provider " + cpr.name.flattenToShortString()
6560 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006561 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006562 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006563 if (!lastRef) {
6564 // This wasn't the last ref our process had on
6565 // the provider... we have now been killed, bail.
6566 return null;
6567 }
6568 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006569 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 }
6572
6573 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006576 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006577 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006579 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006580 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006581 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 } catch (RemoteException ex) {
6583 }
6584 if (cpi == null) {
6585 return null;
6586 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006587 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6588 cpi.name, cpi.flags);
6589 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006590 userId = 0;
6591 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006592 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006593
Dianne Hackbornb424b632010-08-18 15:59:05 -07006594 String msg;
6595 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6596 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 }
6598
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006599 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006600 && !cpi.processName.equals("system")) {
6601 // If this content provider does not run in the system
6602 // process, and the system is not yet ready to run other
6603 // processes, then fail fast instead of hanging.
6604 throw new IllegalArgumentException(
6605 "Attempt to launch content provider before system ready");
6606 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006607
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006608 // Make sure that the user who owns this provider is started. If not,
6609 // we don't want to allow it to run.
6610 if (mStartedUsers.get(userId) == null) {
6611 Slog.w(TAG, "Unable to launch app "
6612 + cpi.applicationInfo.packageName + "/"
6613 + cpi.applicationInfo.uid + " for provider "
6614 + name + ": user " + userId + " is stopped");
6615 return null;
6616 }
6617
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006618 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006619 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 final boolean firstClass = cpr == null;
6621 if (firstClass) {
6622 try {
6623 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006624 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 getApplicationInfo(
6626 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006627 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006629 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 + cpi.name);
6631 return null;
6632 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006633 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006634 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 } catch (RemoteException ex) {
6636 // pm is in same process, this will never happen.
6637 }
6638 }
6639
6640 if (r != null && cpr.canRunHere(r)) {
6641 // If this is a multiprocess provider, then just return its
6642 // info and allow the caller to instantiate it. Only do
6643 // this if the provider is the same user as the caller's
6644 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006645 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 }
6647
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006648 if (DEBUG_PROVIDER) {
6649 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006650 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006651 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 }
6653
6654 // This is single process, and our app is now connecting to it.
6655 // See if we are already in the process of launching this
6656 // provider.
6657 final int N = mLaunchingProviders.size();
6658 int i;
6659 for (i=0; i<N; i++) {
6660 if (mLaunchingProviders.get(i) == cpr) {
6661 break;
6662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664
6665 // If the provider is not already being launched, then get it
6666 // started.
6667 if (i >= N) {
6668 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006669
6670 try {
6671 // Content provider is now in use, its package can't be stopped.
6672 try {
6673 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006674 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006675 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006676 } catch (IllegalArgumentException e) {
6677 Slog.w(TAG, "Failed trying to unstop package "
6678 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006679 }
6680
6681 ProcessRecord proc = startProcessLocked(cpi.processName,
6682 cpr.appInfo, false, 0, "content provider",
6683 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006684 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006685 if (proc == null) {
6686 Slog.w(TAG, "Unable to launch app "
6687 + cpi.applicationInfo.packageName + "/"
6688 + cpi.applicationInfo.uid + " for provider "
6689 + name + ": process is bad");
6690 return null;
6691 }
6692 cpr.launchingApp = proc;
6693 mLaunchingProviders.add(cpr);
6694 } finally {
6695 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 }
6698
6699 // Make sure the provider is published (the same provider class
6700 // may be published under multiple names).
6701 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006702 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006704
Amith Yamasani742a6712011-05-04 14:49:28 -07006705 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006706 conn = incProviderCountLocked(r, cpr, token, stable);
6707 if (conn != null) {
6708 conn.waiting = true;
6709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 }
6711 }
6712
6713 // Wait for the provider to be published...
6714 synchronized (cpr) {
6715 while (cpr.provider == null) {
6716 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006717 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 + cpi.applicationInfo.packageName + "/"
6719 + cpi.applicationInfo.uid + " for provider "
6720 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006721 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006722 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 cpi.applicationInfo.packageName,
6724 cpi.applicationInfo.uid, name);
6725 return null;
6726 }
6727 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006728 if (DEBUG_MU) {
6729 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6730 + cpr.launchingApp);
6731 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006732 if (conn != null) {
6733 conn.waiting = true;
6734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006735 cpr.wait();
6736 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006737 } finally {
6738 if (conn != null) {
6739 conn.waiting = false;
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 }
6742 }
6743 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006744 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 }
6746
6747 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006748 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006749 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 if (caller == null) {
6751 String msg = "null IApplicationThread when getting content provider "
6752 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006753 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 throw new SecurityException(msg);
6755 }
6756
Dianne Hackborn139748f2012-09-24 11:36:57 -07006757 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006758 false, true, "getContentProvider", null);
6759 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 }
6761
Jeff Sharkey6d515712012-09-20 16:06:08 -07006762 public ContentProviderHolder getContentProviderExternal(
6763 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006764 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6765 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006766 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006767 false, true, "getContentProvider", null);
6768 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006769 }
6770
Dianne Hackborn41203752012-08-31 14:05:51 -07006771 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6772 IBinder token, int userId) {
6773 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 }
6775
6776 /**
6777 * Drop a content provider from a ProcessRecord's bookkeeping
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006779 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006780 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006782 ContentProviderConnection conn;
6783 try {
6784 conn = (ContentProviderConnection)connection;
6785 } catch (ClassCastException e) {
6786 String msg ="removeContentProvider: " + connection
6787 + " not a ContentProviderConnection";
6788 Slog.w(TAG, msg);
6789 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006790 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006791 if (conn == null) {
6792 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006794 if (decProviderCountLocked(conn, null, null, stable)) {
6795 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 }
6798 }
6799
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006800 public void removeContentProviderExternal(String name, IBinder token) {
6801 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6802 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006803 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006804 }
6805
Dianne Hackborn41203752012-08-31 14:05:51 -07006806 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006808 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 if(cpr == null) {
6810 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006811 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006812 return;
6813 }
6814
6815 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006816 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006817 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006818 if (localCpr.hasExternalProcessHandles()) {
6819 if (localCpr.removeExternalProcessHandleLocked(token)) {
6820 updateOomAdjLocked();
6821 } else {
6822 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6823 + " with no external reference for token: "
6824 + token + ".");
6825 }
6826 } else {
6827 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6828 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 }
6831 }
6832
6833 public final void publishContentProviders(IApplicationThread caller,
6834 List<ContentProviderHolder> providers) {
6835 if (providers == null) {
6836 return;
6837 }
6838
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006839 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006840 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006842 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006843 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 if (r == null) {
6845 throw new SecurityException(
6846 "Unable to find app for caller " + caller
6847 + " (pid=" + Binder.getCallingPid()
6848 + ") when publishing content providers");
6849 }
6850
6851 final long origId = Binder.clearCallingIdentity();
6852
6853 final int N = providers.size();
6854 for (int i=0; i<N; i++) {
6855 ContentProviderHolder src = providers.get(i);
6856 if (src == null || src.info == null || src.provider == null) {
6857 continue;
6858 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006859 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006860 if (DEBUG_MU)
6861 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006863 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006864 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 String names[] = dst.info.authority.split(";");
6866 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006867 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 }
6869
6870 int NL = mLaunchingProviders.size();
6871 int j;
6872 for (j=0; j<NL; j++) {
6873 if (mLaunchingProviders.get(j) == dst) {
6874 mLaunchingProviders.remove(j);
6875 j--;
6876 NL--;
6877 }
6878 }
6879 synchronized (dst) {
6880 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006881 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 dst.notifyAll();
6883 }
6884 updateOomAdjLocked(r);
6885 }
6886 }
6887
6888 Binder.restoreCallingIdentity(origId);
6889 }
6890 }
6891
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006892 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6893 ContentProviderConnection conn;
6894 try {
6895 conn = (ContentProviderConnection)connection;
6896 } catch (ClassCastException e) {
6897 String msg ="refContentProvider: " + connection
6898 + " not a ContentProviderConnection";
6899 Slog.w(TAG, msg);
6900 throw new IllegalArgumentException(msg);
6901 }
6902 if (conn == null) {
6903 throw new NullPointerException("connection is null");
6904 }
6905
6906 synchronized (this) {
6907 if (stable > 0) {
6908 conn.numStableIncs += stable;
6909 }
6910 stable = conn.stableCount + stable;
6911 if (stable < 0) {
6912 throw new IllegalStateException("stableCount < 0: " + stable);
6913 }
6914
6915 if (unstable > 0) {
6916 conn.numUnstableIncs += unstable;
6917 }
6918 unstable = conn.unstableCount + unstable;
6919 if (unstable < 0) {
6920 throw new IllegalStateException("unstableCount < 0: " + unstable);
6921 }
6922
6923 if ((stable+unstable) <= 0) {
6924 throw new IllegalStateException("ref counts can't go to zero here: stable="
6925 + stable + " unstable=" + unstable);
6926 }
6927 conn.stableCount = stable;
6928 conn.unstableCount = unstable;
6929 return !conn.dead;
6930 }
6931 }
6932
6933 public void unstableProviderDied(IBinder connection) {
6934 ContentProviderConnection conn;
6935 try {
6936 conn = (ContentProviderConnection)connection;
6937 } catch (ClassCastException e) {
6938 String msg ="refContentProvider: " + connection
6939 + " not a ContentProviderConnection";
6940 Slog.w(TAG, msg);
6941 throw new IllegalArgumentException(msg);
6942 }
6943 if (conn == null) {
6944 throw new NullPointerException("connection is null");
6945 }
6946
6947 // Safely retrieve the content provider associated with the connection.
6948 IContentProvider provider;
6949 synchronized (this) {
6950 provider = conn.provider.provider;
6951 }
6952
6953 if (provider == null) {
6954 // Um, yeah, we're way ahead of you.
6955 return;
6956 }
6957
6958 // Make sure the caller is being honest with us.
6959 if (provider.asBinder().pingBinder()) {
6960 // Er, no, still looks good to us.
6961 synchronized (this) {
6962 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6963 + " says " + conn + " died, but we don't agree");
6964 return;
6965 }
6966 }
6967
6968 // Well look at that! It's dead!
6969 synchronized (this) {
6970 if (conn.provider.provider != provider) {
6971 // But something changed... good enough.
6972 return;
6973 }
6974
6975 ProcessRecord proc = conn.provider.proc;
6976 if (proc == null || proc.thread == null) {
6977 // Seems like the process is already cleaned up.
6978 return;
6979 }
6980
6981 // As far as we're concerned, this is just like receiving a
6982 // death notification... just a bit prematurely.
6983 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6984 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006985 final long ident = Binder.clearCallingIdentity();
6986 try {
6987 appDiedLocked(proc, proc.pid, proc.thread);
6988 } finally {
6989 Binder.restoreCallingIdentity(ident);
6990 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006991 }
6992 }
6993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006994 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006995 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006996 synchronized (mSelf) {
6997 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6998 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006999 if (providers != null) {
7000 for (int i=providers.size()-1; i>=0; i--) {
7001 ProviderInfo pi = (ProviderInfo)providers.get(i);
7002 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7003 Slog.w(TAG, "Not installing system proc provider " + pi.name
7004 + ": not system .apk");
7005 providers.remove(i);
7006 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08007007 }
7008 }
7009 }
Josh Bartel2ecce342010-02-25 10:55:48 -06007010 if (providers != null) {
7011 mSystemThread.installSystemProviders(providers);
7012 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08007013
7014 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01007015
7016 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 }
7018
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007019 /**
7020 * Allows app to retrieve the MIME type of a URI without having permission
7021 * to access its content provider.
7022 *
7023 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
7024 *
7025 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
7026 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
7027 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007028 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007029 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07007030 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007031 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007032 final String name = uri.getAuthority();
7033 final long ident = Binder.clearCallingIdentity();
7034 ContentProviderHolder holder = null;
7035
7036 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07007037 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007038 if (holder != null) {
7039 return holder.provider.getType(uri);
7040 }
7041 } catch (RemoteException e) {
7042 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7043 return null;
7044 } finally {
7045 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07007046 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007047 }
7048 Binder.restoreCallingIdentity(ident);
7049 }
7050
7051 return null;
7052 }
7053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 // =========================================================
7055 // GLOBAL MANAGEMENT
7056 // =========================================================
7057
7058 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007059 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 String proc = customProcess != null ? customProcess : info.processName;
7061 BatteryStatsImpl.Uid.Proc ps = null;
7062 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007063 int uid = info.uid;
7064 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007065 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007066 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7067 uid = 0;
7068 while (true) {
7069 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7070 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7071 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7072 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007073 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007074 mNextIsolatedProcessUid++;
7075 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7076 // No process for this uid, use it.
7077 break;
7078 }
7079 stepsLeft--;
7080 if (stepsLeft <= 0) {
7081 return null;
7082 }
7083 }
7084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007085 synchronized (stats) {
7086 ps = stats.getProcessStatsLocked(info.uid, proc);
7087 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007088 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007089 }
7090
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007091 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7092 ProcessRecord app;
7093 if (!isolated) {
7094 app = getProcessRecordLocked(info.processName, info.uid);
7095 } else {
7096 app = null;
7097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098
7099 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007100 app = newProcessRecordLocked(null, info, null, isolated);
7101 mProcessNames.put(info.processName, app.uid, app);
7102 if (isolated) {
7103 mIsolatedProcesses.put(app.uid, app);
7104 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007105 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 }
7107
Dianne Hackborne7f97212011-02-24 14:40:20 -08007108 // This package really, really can not be stopped.
7109 try {
7110 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007111 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007112 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007113 } catch (IllegalArgumentException e) {
7114 Slog.w(TAG, "Failed trying to unstop package "
7115 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007116 }
7117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7119 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7120 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007121 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 }
7123 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7124 mPersistentStartingProcesses.add(app);
7125 startProcessLocked(app, "added application", app.processName);
7126 }
7127
7128 return app;
7129 }
7130
7131 public void unhandledBack() {
7132 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7133 "unhandledBack()");
7134
7135 synchronized(this) {
Craig Mautner2ad92072013-02-25 16:19:24 -08007136 int count = mMainStack.mHistory.size();
7137 if (DEBUG_SWITCH) Slog.d(
7138 TAG, "Performing unhandledBack(): stack size = " + count);
7139 if (count > 1) {
7140 final long origId = Binder.clearCallingIdentity();
7141 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
7142 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 Binder.restoreCallingIdentity(origId);
7144 }
7145 }
7146 }
7147
7148 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007149 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007150 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007152 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 ParcelFileDescriptor pfd = null;
7154 if (cph != null) {
7155 // We record the binder invoker's uid in thread-local storage before
7156 // going to the content provider to open the file. Later, in the code
7157 // that handles all permissions checks, we look for this uid and use
7158 // that rather than the Activity Manager's own uid. The effect is that
7159 // we do the check against the caller's permissions even though it looks
7160 // to the content provider like the Activity Manager itself is making
7161 // the request.
7162 sCallerIdentity.set(new Identity(
7163 Binder.getCallingPid(), Binder.getCallingUid()));
7164 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08007165 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 } catch (FileNotFoundException e) {
7167 // do nothing; pfd will be returned null
7168 } finally {
7169 // Ensure that whatever happens, we clean up the identity state
7170 sCallerIdentity.remove();
7171 }
7172
7173 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007174 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007175 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007176 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 }
7178 return pfd;
7179 }
7180
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007181 // Actually is sleeping or shutting down or whatever else in the future
7182 // is an inactive state.
7183 public boolean isSleeping() {
7184 return mSleeping || mShuttingDown;
7185 }
7186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007188 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7189 != PackageManager.PERMISSION_GRANTED) {
7190 throw new SecurityException("Requires permission "
7191 + android.Manifest.permission.DEVICE_POWER);
7192 }
7193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007195 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007196 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007198 if (!mSleeping) {
7199 mSleeping = true;
7200 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007201
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007202 // Initialize the wake times of all processes.
7203 checkExcessivePowerUsageLocked(false);
7204 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7205 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7206 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 }
7209 }
7210
Dianne Hackborn55280a92009-05-07 15:53:46 -07007211 public boolean shutdown(int timeout) {
7212 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7213 != PackageManager.PERMISSION_GRANTED) {
7214 throw new SecurityException("Requires permission "
7215 + android.Manifest.permission.SHUTDOWN);
7216 }
7217
7218 boolean timedout = false;
7219
7220 synchronized(this) {
7221 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007222 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007223
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007224 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007225 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007226 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007227 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007228 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007229 long delay = endTime - System.currentTimeMillis();
7230 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007231 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007232 timedout = true;
7233 break;
7234 }
7235 try {
7236 this.wait();
7237 } catch (InterruptedException e) {
7238 }
7239 }
7240 }
7241 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007242
7243 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007244 mUsageStatsService.shutdown();
7245 mBatteryStatsService.shutdown();
7246
7247 return timedout;
7248 }
7249
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007250 public final void activitySlept(IBinder token) {
7251 if (localLOGV) Slog.v(
7252 TAG, "Activity slept: token=" + token);
7253
7254 ActivityRecord r = null;
7255
7256 final long origId = Binder.clearCallingIdentity();
7257
7258 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007259 r = mMainStack.isInStackLocked(token);
7260 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007261 mMainStack.activitySleptLocked(r);
7262 }
7263 }
7264
7265 Binder.restoreCallingIdentity(origId);
7266 }
7267
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007268 private void comeOutOfSleepIfNeededLocked() {
7269 if (!mWentToSleep && !mLockScreenShown) {
7270 if (mSleeping) {
7271 mSleeping = false;
7272 mMainStack.awakeFromSleepingLocked();
7273 mMainStack.resumeTopActivityLocked(null);
7274 }
7275 }
7276 }
7277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007279 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7280 != PackageManager.PERMISSION_GRANTED) {
7281 throw new SecurityException("Requires permission "
7282 + android.Manifest.permission.DEVICE_POWER);
7283 }
7284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007285 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007286 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007287 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007288 comeOutOfSleepIfNeededLocked();
7289 }
7290 }
7291
Jeff Brownc042ee22012-05-08 13:03:42 -07007292 private void updateEventDispatchingLocked() {
7293 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7294 }
7295
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007296 public void setLockScreenShown(boolean shown) {
7297 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7298 != PackageManager.PERMISSION_GRANTED) {
7299 throw new SecurityException("Requires permission "
7300 + android.Manifest.permission.DEVICE_POWER);
7301 }
7302
7303 synchronized(this) {
7304 mLockScreenShown = shown;
7305 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007306 }
7307 }
7308
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007309 public void stopAppSwitches() {
7310 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7311 != PackageManager.PERMISSION_GRANTED) {
7312 throw new SecurityException("Requires permission "
7313 + android.Manifest.permission.STOP_APP_SWITCHES);
7314 }
7315
7316 synchronized(this) {
7317 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7318 + APP_SWITCH_DELAY_TIME;
7319 mDidAppSwitch = false;
7320 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7321 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7322 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7323 }
7324 }
7325
7326 public void resumeAppSwitches() {
7327 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7328 != PackageManager.PERMISSION_GRANTED) {
7329 throw new SecurityException("Requires permission "
7330 + android.Manifest.permission.STOP_APP_SWITCHES);
7331 }
7332
7333 synchronized(this) {
7334 // Note that we don't execute any pending app switches... we will
7335 // let those wait until either the timeout, or the next start
7336 // activity request.
7337 mAppSwitchesAllowedTime = 0;
7338 }
7339 }
7340
7341 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7342 String name) {
7343 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7344 return true;
7345 }
7346
7347 final int perm = checkComponentPermission(
7348 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007349 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007350 if (perm == PackageManager.PERMISSION_GRANTED) {
7351 return true;
7352 }
7353
Joe Onorato8a9b2202010-02-26 18:56:32 -08007354 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007355 return false;
7356 }
7357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 public void setDebugApp(String packageName, boolean waitForDebugger,
7359 boolean persistent) {
7360 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7361 "setDebugApp()");
7362
7363 // Note that this is not really thread safe if there are multiple
7364 // callers into it at the same time, but that's not a situation we
7365 // care about.
7366 if (persistent) {
7367 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007368 Settings.Global.putString(
7369 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007370 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007371 Settings.Global.putInt(
7372 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 waitForDebugger ? 1 : 0);
7374 }
7375
7376 synchronized (this) {
7377 if (!persistent) {
7378 mOrigDebugApp = mDebugApp;
7379 mOrigWaitForDebugger = mWaitForDebugger;
7380 }
7381 mDebugApp = packageName;
7382 mWaitForDebugger = waitForDebugger;
7383 mDebugTransient = !persistent;
7384 if (packageName != null) {
7385 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007386 forceStopPackageLocked(packageName, -1, false, false, true, true,
7387 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 Binder.restoreCallingIdentity(origId);
7389 }
7390 }
7391 }
7392
Siva Velusamy92a8b222012-03-09 16:24:04 -08007393 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7394 synchronized (this) {
7395 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7396 if (!isDebuggable) {
7397 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7398 throw new SecurityException("Process not debuggable: " + app.packageName);
7399 }
7400 }
7401
7402 mOpenGlTraceApp = processName;
7403 }
7404 }
7405
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007406 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7407 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7408 synchronized (this) {
7409 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7410 if (!isDebuggable) {
7411 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7412 throw new SecurityException("Process not debuggable: " + app.packageName);
7413 }
7414 }
7415 mProfileApp = processName;
7416 mProfileFile = profileFile;
7417 if (mProfileFd != null) {
7418 try {
7419 mProfileFd.close();
7420 } catch (IOException e) {
7421 }
7422 mProfileFd = null;
7423 }
7424 mProfileFd = profileFd;
7425 mProfileType = 0;
7426 mAutoStopProfiler = autoStopProfiler;
7427 }
7428 }
7429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007430 public void setAlwaysFinish(boolean enabled) {
7431 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7432 "setAlwaysFinish()");
7433
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007434 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007436 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007437
7438 synchronized (this) {
7439 mAlwaysFinishActivities = enabled;
7440 }
7441 }
7442
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007443 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007444 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007445 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007446 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007447 mController = controller;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -07007448 Watchdog.getInstance().setActivityController(controller);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007449 }
7450 }
7451
Adam Momtaz8f6f1f42013-04-10 12:42:58 -07007452 public void setUserIsMonkey(boolean userIsMonkey) {
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007453 synchronized (this) {
Adam Momtaz8f6f1f42013-04-10 12:42:58 -07007454 synchronized (mPidsSelfLocked) {
7455 final int callingPid = Binder.getCallingPid();
7456 ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid);
7457 if (precessRecord == null) {
7458 throw new SecurityException("Unknown process: " + callingPid);
7459 }
7460 if (precessRecord.instrumentationUiAutomationConnection == null) {
7461 throw new SecurityException("Only an instrumentation process "
7462 + "with a UiAutomation can call setUserIsMonkey");
7463 }
7464 }
7465 mUserIsMonkey = userIsMonkey;
7466 }
7467 }
7468
7469 public boolean isUserAMonkey() {
7470 synchronized (this) {
7471 // If there is a controller also implies the user is a monkey.
7472 return (mUserIsMonkey || mController != null);
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007473 }
7474 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007475
7476 public void requestBugReport() {
Jeff Sharkeyb9323192013-02-05 13:32:18 -08007477 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007478 SystemProperties.set("ctl.start", "bugreport");
7479 }
7480
Michael Wright7dd5bb12013-02-27 17:07:29 -08007481 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) {
7482 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT;
7483 }
7484
7485 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) {
7486 if (r != null && (r.instrumentationClass != null || r.usingWrapper)) {
7487 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7488 }
7489 return KEY_DISPATCHING_TIMEOUT;
7490 }
7491
7492
Michael Wright5633e232013-02-25 17:52:37 -08007493 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem) {
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007494 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7495 != PackageManager.PERMISSION_GRANTED) {
7496 throw new SecurityException("Requires permission "
7497 + android.Manifest.permission.FILTER_EVENTS);
7498 }
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007499 ProcessRecord proc;
Michael Wright7dd5bb12013-02-27 17:07:29 -08007500 long timeout;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007501 synchronized (this) {
7502 synchronized (mPidsSelfLocked) {
7503 proc = mPidsSelfLocked.get(pid);
7504 }
Michael Wright7dd5bb12013-02-27 17:07:29 -08007505 timeout = getInputDispatchingTimeoutLocked(proc);
7506 }
7507
7508 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem)) {
7509 return -1;
7510 }
7511
7512 return timeout;
7513 }
7514
7515 /**
7516 * Handle input dispatching timeouts.
7517 * Returns whether input dispatching should be aborted or not.
7518 */
7519 public boolean inputDispatchingTimedOut(final ProcessRecord proc,
7520 final ActivityRecord activity, final ActivityRecord parent,
7521 final boolean aboveSystem) {
7522 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7523 != PackageManager.PERMISSION_GRANTED) {
7524 throw new SecurityException("Requires permission "
7525 + android.Manifest.permission.FILTER_EVENTS);
7526 }
7527
7528 if (proc != null) {
7529 synchronized (this) {
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007530 if (proc.debugging) {
Michael Wright7dd5bb12013-02-27 17:07:29 -08007531 return false;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007532 }
7533
7534 if (mDidDexOpt) {
7535 // Give more time since we were dexopting.
7536 mDidDexOpt = false;
Michael Wright7dd5bb12013-02-27 17:07:29 -08007537 return false;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007538 }
7539
7540 if (proc.instrumentationClass != null) {
7541 Bundle info = new Bundle();
7542 info.putString("shortMsg", "keyDispatchingTimedOut");
7543 info.putString("longMsg", "Timed out while dispatching key event");
7544 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
Michael Wright7dd5bb12013-02-27 17:07:29 -08007545 return true;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007546 }
7547 }
Michael Wright5633e232013-02-25 17:52:37 -08007548 mHandler.post(new Runnable() {
7549 @Override
7550 public void run() {
Michael Wright7dd5bb12013-02-27 17:07:29 -08007551 appNotResponding(proc, activity, parent, aboveSystem, "keyDispatchingTimedOut");
Michael Wright5633e232013-02-25 17:52:37 -08007552 }
7553 });
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007554 }
7555
Michael Wright7dd5bb12013-02-27 17:07:29 -08007556 return true;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007557 }
7558
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007559 public Bundle getTopActivityExtras(int requestType) {
7560 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7561 "getTopActivityExtras()");
7562 PendingActivityExtras pae;
7563 Bundle extras = new Bundle();
7564 synchronized (this) {
7565 ActivityRecord activity = mMainStack.mResumedActivity;
7566 if (activity == null) {
7567 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7568 return null;
7569 }
7570 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7571 if (activity.app == null || activity.app.thread == null) {
7572 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7573 return extras;
7574 }
7575 if (activity.app.pid == Binder.getCallingPid()) {
7576 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7577 return extras;
7578 }
7579 pae = new PendingActivityExtras(activity);
7580 try {
7581 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7582 mPendingActivityExtras.add(pae);
7583 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7584 } catch (RemoteException e) {
7585 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7586 return extras;
7587 }
7588 }
7589 synchronized (pae) {
7590 while (!pae.haveResult) {
7591 try {
7592 pae.wait();
7593 } catch (InterruptedException e) {
7594 }
7595 }
7596 if (pae.result != null) {
7597 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7598 }
7599 }
7600 synchronized (this) {
7601 mPendingActivityExtras.remove(pae);
7602 mHandler.removeCallbacks(pae);
7603 }
7604 return extras;
7605 }
7606
7607 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7608 PendingActivityExtras pae = (PendingActivityExtras)token;
7609 synchronized (pae) {
7610 pae.result = extras;
7611 pae.haveResult = true;
7612 pae.notifyAll();
7613 }
7614 }
7615
Jeff Sharkeya4620792011-05-20 15:29:23 -07007616 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007617 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7618 "registerProcessObserver()");
7619 synchronized (this) {
7620 mProcessObservers.register(observer);
7621 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007622 }
7623
7624 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007625 synchronized (this) {
7626 mProcessObservers.unregister(observer);
7627 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007628 }
7629
Daniel Sandler69a48172010-06-23 16:29:36 -04007630 public void setImmersive(IBinder token, boolean immersive) {
7631 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007632 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007633 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007634 throw new IllegalArgumentException();
7635 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007636 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007637
7638 // update associated state if we're frontmost
7639 if (r == mFocusedActivity) {
7640 if (DEBUG_IMMERSIVE) {
7641 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7642 }
7643 applyUpdateLockStateLocked(r);
7644 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007645 }
7646 }
7647
7648 public boolean isImmersive(IBinder token) {
7649 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007650 ActivityRecord r = mMainStack.isInStackLocked(token);
7651 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007652 throw new IllegalArgumentException();
7653 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007654 return r.immersive;
7655 }
7656 }
7657
7658 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007659 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007660 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007661 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007662 return (r != null) ? r.immersive : false;
7663 }
7664 }
7665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 public final void enterSafeMode() {
7667 synchronized(this) {
7668 // It only makes sense to do this before the system is ready
7669 // and started launching other packages.
7670 if (!mSystemReady) {
7671 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007672 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 } catch (RemoteException e) {
7674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 }
7676 }
7677 }
7678
Jeff Brownb09abc12011-01-13 21:08:27 -08007679 public final void showSafeModeOverlay() {
7680 View v = LayoutInflater.from(mContext).inflate(
7681 com.android.internal.R.layout.safe_mode, null);
7682 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7683 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7684 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7685 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007686 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007687 lp.format = v.getBackground().getOpacity();
7688 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7689 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007690 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007691 ((WindowManager)mContext.getSystemService(
7692 Context.WINDOW_SERVICE)).addView(v, lp);
7693 }
7694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 public void noteWakeupAlarm(IIntentSender sender) {
7696 if (!(sender instanceof PendingIntentRecord)) {
7697 return;
7698 }
7699 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7700 synchronized (stats) {
7701 if (mBatteryStatsService.isOnBattery()) {
7702 mBatteryStatsService.enforceCallingPermission();
7703 PendingIntentRecord rec = (PendingIntentRecord)sender;
7704 int MY_UID = Binder.getCallingUid();
7705 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7706 BatteryStatsImpl.Uid.Pkg pkg =
7707 stats.getPackageStatsLocked(uid, rec.key.packageName);
7708 pkg.incWakeupsLocked();
7709 }
7710 }
7711 }
7712
Dianne Hackborn64825172011-03-02 21:32:58 -08007713 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007715 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007717 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 // XXX Note: don't acquire main activity lock here, because the window
7719 // manager calls in with its locks held.
7720
7721 boolean killed = false;
7722 synchronized (mPidsSelfLocked) {
7723 int[] types = new int[pids.length];
7724 int worstType = 0;
7725 for (int i=0; i<pids.length; i++) {
7726 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7727 if (proc != null) {
7728 int type = proc.setAdj;
7729 types[i] = type;
7730 if (type > worstType) {
7731 worstType = type;
7732 }
7733 }
7734 }
7735
Dianne Hackborn64825172011-03-02 21:32:58 -08007736 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007738 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7739 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007740 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007742
7743 // If this is not a secure call, don't let it kill processes that
7744 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007745 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7746 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007747 }
7748
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007749 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 for (int i=0; i<pids.length; i++) {
7751 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7752 if (proc == null) {
7753 continue;
7754 }
7755 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007756 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007757 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007758 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007759 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007760 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007761 proc.killedBackground = true;
7762 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 }
7764 }
7765 }
7766 return killed;
7767 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007768
7769 @Override
Dianne Hackbornf1b78242013-04-08 22:28:59 -07007770 public void killUid(int uid, String reason) {
7771 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7772 throw new SecurityException("killUid only available to the system");
7773 }
7774 synchronized (this) {
7775 killPackageProcessesLocked(null, UserHandle.getAppId(uid), UserHandle.getUserId(uid),
7776 ProcessList.FOREGROUND_APP_ADJ-1, false, true, true, false,
7777 reason != null ? reason : "kill uid");
7778 }
7779 }
7780
7781 @Override
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007782 public boolean killProcessesBelowForeground(String reason) {
7783 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7784 throw new SecurityException("killProcessesBelowForeground() only available to system");
7785 }
7786
7787 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7788 }
7789
7790 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7791 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7792 throw new SecurityException("killProcessesBelowAdj() only available to system");
7793 }
7794
7795 boolean killed = false;
7796 synchronized (mPidsSelfLocked) {
7797 final int size = mPidsSelfLocked.size();
7798 for (int i = 0; i < size; i++) {
7799 final int pid = mPidsSelfLocked.keyAt(i);
7800 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7801 if (proc == null) continue;
7802
7803 final int adj = proc.setAdj;
7804 if (adj > belowAdj && !proc.killedBackground) {
7805 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007806 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7807 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007808 killed = true;
7809 proc.killedBackground = true;
7810 Process.killProcessQuiet(pid);
7811 }
7812 }
7813 }
7814 return killed;
7815 }
7816
Dianne Hackborn8bd64df2013-05-06 16:07:26 -07007817 @Override
7818 public void hang(final IBinder who, boolean allowRestart) {
7819 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
7820 != PackageManager.PERMISSION_GRANTED) {
7821 throw new SecurityException("Requires permission "
7822 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
7823 }
7824
7825 final IBinder.DeathRecipient death = new DeathRecipient() {
7826 @Override
7827 public void binderDied() {
7828 synchronized (this) {
7829 notifyAll();
7830 }
7831 }
7832 };
7833
7834 try {
7835 who.linkToDeath(death, 0);
7836 } catch (RemoteException e) {
7837 Slog.w(TAG, "hang: given caller IBinder is already dead.");
7838 return;
7839 }
7840
7841 synchronized (this) {
7842 Watchdog.getInstance().setAllowRestart(allowRestart);
7843 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid());
7844 synchronized (death) {
7845 while (who.isBinderAlive()) {
7846 try {
7847 death.wait();
7848 } catch (InterruptedException e) {
7849 }
7850 }
7851 }
7852 Watchdog.getInstance().setAllowRestart(true);
7853 }
7854 }
7855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 public final void startRunning(String pkg, String cls, String action,
7857 String data) {
7858 synchronized(this) {
7859 if (mStartRunning) {
7860 return;
7861 }
7862 mStartRunning = true;
7863 mTopComponent = pkg != null && cls != null
7864 ? new ComponentName(pkg, cls) : null;
7865 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7866 mTopData = data;
7867 if (!mSystemReady) {
7868 return;
7869 }
7870 }
7871
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007872 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 }
7874
7875 private void retrieveSettings() {
7876 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007877 String debugApp = Settings.Global.getString(
7878 resolver, Settings.Global.DEBUG_APP);
7879 boolean waitForDebugger = Settings.Global.getInt(
7880 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7881 boolean alwaysFinishActivities = Settings.Global.getInt(
7882 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883
7884 Configuration configuration = new Configuration();
7885 Settings.System.getConfiguration(resolver, configuration);
7886
7887 synchronized (this) {
7888 mDebugApp = mOrigDebugApp = debugApp;
7889 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7890 mAlwaysFinishActivities = alwaysFinishActivities;
7891 // This happens before any activities are started, so we can
7892 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007893 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007894 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
7896 }
7897
7898 public boolean testIsSystemReady() {
7899 // no need to synchronize(this) just to read & return the value
7900 return mSystemReady;
7901 }
7902
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007903 private static File getCalledPreBootReceiversFile() {
7904 File dataDir = Environment.getDataDirectory();
7905 File systemDir = new File(dataDir, "system");
7906 File fname = new File(systemDir, "called_pre_boots.dat");
7907 return fname;
7908 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007909
7910 static final int LAST_DONE_VERSION = 10000;
7911
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007912 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7913 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7914 File file = getCalledPreBootReceiversFile();
7915 FileInputStream fis = null;
7916 try {
7917 fis = new FileInputStream(file);
7918 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007919 int fvers = dis.readInt();
7920 if (fvers == LAST_DONE_VERSION) {
7921 String vers = dis.readUTF();
7922 String codename = dis.readUTF();
7923 String build = dis.readUTF();
7924 if (android.os.Build.VERSION.RELEASE.equals(vers)
7925 && android.os.Build.VERSION.CODENAME.equals(codename)
7926 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7927 int num = dis.readInt();
7928 while (num > 0) {
7929 num--;
7930 String pkg = dis.readUTF();
7931 String cls = dis.readUTF();
7932 lastDoneReceivers.add(new ComponentName(pkg, cls));
7933 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007934 }
7935 }
7936 } catch (FileNotFoundException e) {
7937 } catch (IOException e) {
7938 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7939 } finally {
7940 if (fis != null) {
7941 try {
7942 fis.close();
7943 } catch (IOException e) {
7944 }
7945 }
7946 }
7947 return lastDoneReceivers;
7948 }
7949
7950 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7951 File file = getCalledPreBootReceiversFile();
7952 FileOutputStream fos = null;
7953 DataOutputStream dos = null;
7954 try {
7955 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7956 fos = new FileOutputStream(file);
7957 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007958 dos.writeInt(LAST_DONE_VERSION);
7959 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007960 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007961 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007962 dos.writeInt(list.size());
7963 for (int i=0; i<list.size(); i++) {
7964 dos.writeUTF(list.get(i).getPackageName());
7965 dos.writeUTF(list.get(i).getClassName());
7966 }
7967 } catch (IOException e) {
7968 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7969 file.delete();
7970 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007971 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007972 if (dos != null) {
7973 try {
7974 dos.close();
7975 } catch (IOException e) {
7976 // TODO Auto-generated catch block
7977 e.printStackTrace();
7978 }
7979 }
7980 }
7981 }
7982
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007983 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 synchronized(this) {
7985 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007986 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 return;
7988 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007989
7990 // Check to see if there are any update receivers to run.
7991 if (!mDidUpdate) {
7992 if (mWaitingUpdate) {
7993 return;
7994 }
7995 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7996 List<ResolveInfo> ris = null;
7997 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007998 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007999 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008000 } catch (RemoteException e) {
8001 }
8002 if (ris != null) {
8003 for (int i=ris.size()-1; i>=0; i--) {
8004 if ((ris.get(i).activityInfo.applicationInfo.flags
8005 &ApplicationInfo.FLAG_SYSTEM) == 0) {
8006 ris.remove(i);
8007 }
8008 }
8009 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008010
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008011 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008012
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008013 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008014 for (int i=0; i<ris.size(); i++) {
8015 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008016 ComponentName comp = new ComponentName(ai.packageName, ai.name);
8017 if (lastDoneReceivers.contains(comp)) {
8018 ris.remove(i);
8019 i--;
8020 }
8021 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07008022
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008023 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008024 for (int i=0; i<ris.size(); i++) {
8025 ActivityInfo ai = ris.get(i).activityInfo;
8026 ComponentName comp = new ComponentName(ai.packageName, ai.name);
8027 doneReceivers.add(comp);
8028 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008029 for (int j=0; j<users.length; j++) {
8030 IIntentReceiver finisher = null;
8031 if (i == ris.size()-1 && j == users.length-1) {
8032 finisher = new IIntentReceiver.Stub() {
8033 public void performReceive(Intent intent, int resultCode,
8034 String data, Bundle extras, boolean ordered,
8035 boolean sticky, int sendingUser) {
8036 // The raw IIntentReceiver interface is called
8037 // with the AM lock held, so redispatch to
8038 // execute our code without the lock.
8039 mHandler.post(new Runnable() {
8040 public void run() {
8041 synchronized (ActivityManagerService.this) {
8042 mDidUpdate = true;
8043 }
8044 writeLastDonePreBootReceivers(doneReceivers);
8045 showBootMessage(mContext.getText(
8046 R.string.android_upgrading_complete),
8047 false);
8048 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07008049 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008050 });
8051 }
8052 };
8053 }
8054 Slog.i(TAG, "Sending system update to " + intent.getComponent()
8055 + " for user " + users[j]);
8056 broadcastIntentLocked(null, null, intent, null, finisher,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008057 0, null, null, null, AppOpsManager.OP_NONE,
8058 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008059 users[j]);
8060 if (finisher != null) {
8061 mWaitingUpdate = true;
8062 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008063 }
8064 }
8065 }
8066 if (mWaitingUpdate) {
8067 return;
8068 }
8069 mDidUpdate = true;
8070 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08008071
8072 mAppOpsService.systemReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 mSystemReady = true;
8074 if (!mStartRunning) {
8075 return;
8076 }
8077 }
8078
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008079 ArrayList<ProcessRecord> procsToKill = null;
8080 synchronized(mPidsSelfLocked) {
8081 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
8082 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
8083 if (!isAllowedWhileBooting(proc.info)){
8084 if (procsToKill == null) {
8085 procsToKill = new ArrayList<ProcessRecord>();
8086 }
8087 procsToKill.add(proc);
8088 }
8089 }
8090 }
8091
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008092 synchronized(this) {
8093 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008094 for (int i=procsToKill.size()-1; i>=0; i--) {
8095 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08008096 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008097 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008098 }
8099 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07008100
8101 // Now that we have cleaned up any update processes, we
8102 // are ready to start launching real processes and know that
8103 // we won't trample on them any more.
8104 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008105 }
8106
Joe Onorato8a9b2202010-02-26 18:56:32 -08008107 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008108 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 SystemClock.uptimeMillis());
8110
8111 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008112 // Make sure we have no pre-ready processes sitting around.
8113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
8115 ResolveInfo ri = mContext.getPackageManager()
8116 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07008117 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 CharSequence errorMsg = null;
8119 if (ri != null) {
8120 ActivityInfo ai = ri.activityInfo;
8121 ApplicationInfo app = ai.applicationInfo;
8122 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8123 mTopAction = Intent.ACTION_FACTORY_TEST;
8124 mTopData = null;
8125 mTopComponent = new ComponentName(app.packageName,
8126 ai.name);
8127 } else {
8128 errorMsg = mContext.getResources().getText(
8129 com.android.internal.R.string.factorytest_not_system);
8130 }
8131 } else {
8132 errorMsg = mContext.getResources().getText(
8133 com.android.internal.R.string.factorytest_no_action);
8134 }
8135 if (errorMsg != null) {
8136 mTopAction = null;
8137 mTopData = null;
8138 mTopComponent = null;
8139 Message msg = Message.obtain();
8140 msg.what = SHOW_FACTORY_ERROR_MSG;
8141 msg.getData().putCharSequence("msg", errorMsg);
8142 mHandler.sendMessage(msg);
8143 }
8144 }
8145 }
8146
8147 retrieveSettings();
8148
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008149 if (goingCallback != null) goingCallback.run();
8150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 synchronized (this) {
8152 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8153 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008154 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008155 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008156 if (apps != null) {
8157 int N = apps.size();
8158 int i;
8159 for (i=0; i<N; i++) {
8160 ApplicationInfo info
8161 = (ApplicationInfo)apps.get(i);
8162 if (info != null &&
8163 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008164 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 }
8166 }
8167 }
8168 } catch (RemoteException ex) {
8169 // pm is in same process, this will never happen.
8170 }
8171 }
8172
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008173 // Start up initial activity.
8174 mBooting = true;
8175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008177 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 Message msg = Message.obtain();
8179 msg.what = SHOW_UID_ERROR_MSG;
8180 mHandler.sendMessage(msg);
8181 }
8182 } catch (RemoteException e) {
8183 }
8184
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008185 long ident = Binder.clearCallingIdentity();
8186 try {
8187 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008188 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
8189 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008190 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8191 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008192 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008193 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008194 intent = new Intent(Intent.ACTION_USER_STARTING);
8195 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8196 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8197 broadcastIntentLocked(null, null, intent,
8198 null, new IIntentReceiver.Stub() {
8199 @Override
8200 public void performReceive(Intent intent, int resultCode, String data,
8201 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
8202 throws RemoteException {
8203 }
8204 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008205 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08008206 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008207 } finally {
8208 Binder.restoreCallingIdentity(ident);
8209 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008210 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008211 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 }
8213 }
8214
Dan Egnorb7f03672009-12-09 16:22:32 -08008215 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008216 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008218 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008219 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 startAppProblemLocked(app);
8221 app.stopFreezingAllLocked();
8222 return handleAppCrashLocked(app);
8223 }
8224
Dan Egnorb7f03672009-12-09 16:22:32 -08008225 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008226 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008228 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008229 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8230 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 startAppProblemLocked(app);
8232 app.stopFreezingAllLocked();
8233 }
8234
8235 /**
8236 * Generate a process error record, suitable for attachment to a ProcessRecord.
8237 *
8238 * @param app The ProcessRecord in which the error occurred.
8239 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8240 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008241 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008242 * @param shortMsg Short message describing the crash.
8243 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008244 * @param stackTrace Full crash stack trace, may be null.
8245 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 * @return Returns a fully-formed AppErrorStateInfo record.
8247 */
8248 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008249 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008252 report.condition = condition;
8253 report.processName = app.processName;
8254 report.pid = app.pid;
8255 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008256 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008257 report.shortMsg = shortMsg;
8258 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008259 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260
8261 return report;
8262 }
8263
Dan Egnor42471dd2010-01-07 17:25:22 -08008264 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008265 synchronized (this) {
8266 app.crashing = false;
8267 app.crashingReport = null;
8268 app.notResponding = false;
8269 app.notRespondingReport = null;
8270 if (app.anrDialog == fromDialog) {
8271 app.anrDialog = null;
8272 }
8273 if (app.waitDialog == fromDialog) {
8274 app.waitDialog = null;
8275 }
8276 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008277 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008278 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008279 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008280 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008281 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 }
8284 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008285
Dan Egnorb7f03672009-12-09 16:22:32 -08008286 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008287 if (mHeadless) {
8288 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8289 return false;
8290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 long now = SystemClock.uptimeMillis();
8292
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008293 Long crashTime;
8294 if (!app.isolated) {
8295 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8296 } else {
8297 crashTime = null;
8298 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008299 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008300 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008301 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008303 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008304 app.userId, app.info.processName, app.uid);
Craig Mautner2ad92072013-02-25 16:19:24 -08008305 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8306 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
8307 if (r.app == app) {
8308 Slog.w(TAG, " Force finishing activity "
8309 + r.intent.getComponent().flattenToShortString());
8310 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8311 null, "crashed", false);
8312 }
8313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 if (!app.persistent) {
8315 // We don't want to start this process again until the user
8316 // explicitly does so... but for persistent process, we really
8317 // need to keep it running. If a persistent process is actually
8318 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008319 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008321 if (!app.isolated) {
8322 // XXX We don't have a way to mark isolated processes
8323 // as bad, since they don't have a peristent identity.
8324 mBadProcesses.put(app.info.processName, app.uid, now);
8325 mProcessCrashTimes.remove(app.info.processName, app.uid);
8326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008327 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008328 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008329 // Don't let services in this process be restarted and potentially
8330 // annoy the user repeatedly. Unless it is persistent, since those
8331 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008332 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008333 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 return false;
8335 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008336 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008337 } else {
Craig Mautner2ad92072013-02-25 16:19:24 -08008338 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
8339 if (r != null && r.app == app) {
8340 // If the top running activity is from this crashing
8341 // process, then terminate it to avoid getting in a loop.
8342 Slog.w(TAG, " Force finishing activity "
8343 + r.intent.getComponent().flattenToShortString());
8344 int index = mMainStack.indexOfActivityLocked(r);
8345 r.stack.finishActivityLocked(r, index,
8346 Activity.RESULT_CANCELED, null, "crashed", false);
8347 // Also terminate any activities below it that aren't yet
8348 // stopped, to avoid a situation where one will get
8349 // re-start our crashing activity once it gets resumed again.
8350 index--;
8351 if (index >= 0) {
8352 r = (ActivityRecord)mMainStack.mHistory.get(index);
8353 if (r.state == ActivityState.RESUMED
8354 || r.state == ActivityState.PAUSING
8355 || r.state == ActivityState.PAUSED) {
8356 if (!r.isHomeActivity || mHomeProcess != r.app) {
8357 Slog.w(TAG, " Force finishing activity "
8358 + r.intent.getComponent().flattenToShortString());
8359 r.stack.finishActivityLocked(r, index,
8360 Activity.RESULT_CANCELED, null, "crashed", false);
8361 }
8362 }
8363 }
8364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 }
8366
8367 // Bump up the crash count of any services currently running in the proc.
8368 if (app.services.size() != 0) {
8369 // Any services running in the application need to be placed
8370 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008371 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008373 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 sr.crashCount++;
8375 }
8376 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008377
8378 // If the crashing process is what we consider to be the "home process" and it has been
8379 // replaced by a third-party app, clear the package preferred activities from packages
8380 // with a home activity running in the process to prevent a repeatedly crashing app
8381 // from blocking the user to manually clear the list.
8382 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8383 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8384 Iterator it = mHomeProcess.activities.iterator();
8385 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008386 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008387 if (r.isHomeActivity) {
8388 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8389 try {
8390 ActivityThread.getPackageManager()
8391 .clearPackagePreferredActivities(r.packageName);
8392 } catch (RemoteException c) {
8393 // pm is in same process, this will never happen.
8394 }
8395 }
8396 }
8397 }
8398
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008399 if (!app.isolated) {
8400 // XXX Can't keep track of crash times for isolated processes,
8401 // because they don't have a perisistent identity.
8402 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8403 }
8404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 return true;
8406 }
8407
8408 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008409 if (app.userId == mCurrentUserId) {
8410 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8411 mContext, app.info.packageName, app.info.flags);
8412 } else {
8413 // If this app is not running under the current user, then we
8414 // can't give it a report button because that would require
8415 // launching the report UI under a different user.
8416 app.errorReportReceiver = null;
8417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008418 skipCurrentReceiverLocked(app);
8419 }
8420
8421 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008422 for (BroadcastQueue queue : mBroadcastQueues) {
8423 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424 }
8425 }
8426
Dan Egnor60d87622009-12-16 16:32:58 -08008427 /**
8428 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8429 * The application process will exit immediately after this call returns.
8430 * @param app object of the crashing app, null for the system server
8431 * @param crashInfo describing the exception
8432 */
8433 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008434 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008435 final String processName = app == null ? "system_server"
8436 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008437
Eric Rowe88d842c2013-04-08 15:00:27 -07008438 handleApplicationCrashInner("crash", r, processName, crashInfo);
Christopher Tate58d380d2013-03-19 13:10:03 -07008439 }
8440
8441 /* Native crash reporting uses this inner version because it needs to be somewhat
8442 * decoupled from the AM-managed cleanup lifecycle
8443 */
Eric Rowe88d842c2013-04-08 15:00:27 -07008444 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName,
Christopher Tate58d380d2013-03-19 13:10:03 -07008445 ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnor60d87622009-12-16 16:32:58 -08008446 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008447 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008448 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008449 crashInfo.exceptionClassName,
8450 crashInfo.exceptionMessage,
8451 crashInfo.throwFileName,
8452 crashInfo.throwLineNumber);
8453
Eric Rowe88d842c2013-04-08 15:00:27 -07008454 addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008455
8456 crashApplication(r, crashInfo);
8457 }
8458
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008459 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008460 IBinder app,
8461 int violationMask,
8462 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008463 ProcessRecord r = findAppProcess(app, "StrictMode");
8464 if (r == null) {
8465 return;
8466 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008467
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008468 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008469 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008470 boolean logIt = true;
8471 synchronized (mAlreadyLoggedViolatedStacks) {
8472 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8473 logIt = false;
8474 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008475 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008476 // the relative pain numbers, without logging all
8477 // the stack traces repeatedly. We'd want to do
8478 // likewise in the client code, which also does
8479 // dup suppression, before the Binder call.
8480 } else {
8481 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8482 mAlreadyLoggedViolatedStacks.clear();
8483 }
8484 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8485 }
8486 }
8487 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008488 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008489 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008490 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008491
8492 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8493 AppErrorResult result = new AppErrorResult();
8494 synchronized (this) {
8495 final long origId = Binder.clearCallingIdentity();
8496
8497 Message msg = Message.obtain();
8498 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8499 HashMap<String, Object> data = new HashMap<String, Object>();
8500 data.put("result", result);
8501 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008502 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008503 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008504 msg.obj = data;
8505 mHandler.sendMessage(msg);
8506
8507 Binder.restoreCallingIdentity(origId);
8508 }
8509 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008510 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008511 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008512 }
8513
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008514 // Depending on the policy in effect, there could be a bunch of
8515 // these in quick succession so we try to batch these together to
8516 // minimize disk writes, number of dropbox entries, and maximize
8517 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008518 private void logStrictModeViolationToDropBox(
8519 ProcessRecord process,
8520 StrictMode.ViolationInfo info) {
8521 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008522 return;
8523 }
8524 final boolean isSystemApp = process == null ||
8525 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8526 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008527 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008528 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8529 final DropBoxManager dbox = (DropBoxManager)
8530 mContext.getSystemService(Context.DROPBOX_SERVICE);
8531
8532 // Exit early if the dropbox isn't configured to accept this report type.
8533 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8534
8535 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008536 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008537 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8538 synchronized (sb) {
8539 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008540 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008541 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8542 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008543 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8544 if (info.violationNumThisLoop != 0) {
8545 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8546 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008547 if (info.numAnimationsRunning != 0) {
8548 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8549 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008550 if (info.broadcastIntentAction != null) {
8551 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8552 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008553 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008554 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008555 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008556 if (info.numInstances != -1) {
8557 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8558 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008559 if (info.tags != null) {
8560 for (String tag : info.tags) {
8561 sb.append("Span-Tag: ").append(tag).append("\n");
8562 }
8563 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008564 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008565 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8566 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008567 }
8568 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008569
8570 // Only buffer up to ~64k. Various logging bits truncate
8571 // things at 128k.
8572 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008573 }
8574
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008575 // Flush immediately if the buffer's grown too large, or this
8576 // is a non-system app. Non-system apps are isolated with a
8577 // different tag & policy and not batched.
8578 //
8579 // Batching is useful during internal testing with
8580 // StrictMode settings turned up high. Without batching,
8581 // thousands of separate files could be created on boot.
8582 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008583 new Thread("Error dump: " + dropboxTag) {
8584 @Override
8585 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008586 String report;
8587 synchronized (sb) {
8588 report = sb.toString();
8589 sb.delete(0, sb.length());
8590 sb.trimToSize();
8591 }
8592 if (report.length() != 0) {
8593 dbox.addText(dropboxTag, report);
8594 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008595 }
8596 }.start();
8597 return;
8598 }
8599
8600 // System app batching:
8601 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008602 // An existing dropbox-writing thread is outstanding, so
8603 // we don't need to start it up. The existing thread will
8604 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008605 return;
8606 }
8607
8608 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8609 // (After this point, we shouldn't access AMS internal data structures.)
8610 new Thread("Error dump: " + dropboxTag) {
8611 @Override
8612 public void run() {
8613 // 5 second sleep to let stacks arrive and be batched together
8614 try {
8615 Thread.sleep(5000); // 5 seconds
8616 } catch (InterruptedException e) {}
8617
8618 String errorReport;
8619 synchronized (mStrictModeBuffer) {
8620 errorReport = mStrictModeBuffer.toString();
8621 if (errorReport.length() == 0) {
8622 return;
8623 }
8624 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8625 mStrictModeBuffer.trimToSize();
8626 }
8627 dbox.addText(dropboxTag, errorReport);
8628 }
8629 }.start();
8630 }
8631
Dan Egnor60d87622009-12-16 16:32:58 -08008632 /**
8633 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8634 * @param app object of the crashing app, null for the system server
8635 * @param tag reported by the caller
8636 * @param crashInfo describing the context of the error
8637 * @return true if the process should exit immediately (WTF is fatal)
8638 */
8639 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008640 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008641 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008642 final String processName = app == null ? "system_server"
8643 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008644
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008645 EventLog.writeEvent(EventLogTags.AM_WTF,
8646 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008647 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008648 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008649 tag, crashInfo.exceptionMessage);
8650
Jeff Sharkeya353d262011-10-28 11:12:06 -07008651 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008652
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008653 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008654 Settings.Global.getInt(mContext.getContentResolver(),
8655 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008656 crashApplication(r, crashInfo);
8657 return true;
8658 } else {
8659 return false;
8660 }
8661 }
8662
8663 /**
8664 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8665 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8666 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008667 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008668 if (app == null) {
8669 return null;
8670 }
8671
8672 synchronized (this) {
8673 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8674 final int NA = apps.size();
8675 for (int ia=0; ia<NA; ia++) {
8676 ProcessRecord p = apps.valueAt(ia);
8677 if (p.thread != null && p.thread.asBinder() == app) {
8678 return p;
8679 }
8680 }
8681 }
8682
Dianne Hackborncb44d962011-03-10 17:02:27 -08008683 Slog.w(TAG, "Can't find mystery application for " + reason
8684 + " from pid=" + Binder.getCallingPid()
8685 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008686 return null;
8687 }
8688 }
8689
8690 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008691 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8692 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008693 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008694 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8695 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008696 // Watchdog thread ends up invoking this function (with
8697 // a null ProcessRecord) to add the stack file to dropbox.
8698 // Do not acquire a lock on this (am) in such cases, as it
8699 // could cause a potential deadlock, if and when watchdog
8700 // is invoked due to unavailability of lock on am and it
8701 // would prevent watchdog from killing system_server.
8702 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008703 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008704 return;
8705 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008706 // Note: ProcessRecord 'process' is guarded by the service
8707 // instance. (notably process.pkgList, which could otherwise change
8708 // concurrently during execution of this method)
8709 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008710 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008711 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008712 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008713 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8714 for (String pkg : process.pkgList) {
8715 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008716 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008717 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008718 if (pi != null) {
8719 sb.append(" v").append(pi.versionCode);
8720 if (pi.versionName != null) {
8721 sb.append(" (").append(pi.versionName).append(")");
8722 }
8723 }
8724 } catch (RemoteException e) {
8725 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008726 }
Dan Egnora455d192010-03-12 08:52:28 -08008727 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008728 }
Dan Egnora455d192010-03-12 08:52:28 -08008729 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008730 }
8731
8732 private static String processClass(ProcessRecord process) {
8733 if (process == null || process.pid == MY_PID) {
8734 return "system_server";
8735 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8736 return "system_app";
8737 } else {
8738 return "data_app";
8739 }
8740 }
8741
8742 /**
8743 * Write a description of an error (crash, WTF, ANR) to the drop box.
8744 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8745 * @param process which caused the error, null means the system server
8746 * @param activity which triggered the error, null if unknown
8747 * @param parent activity related to the error, null if unknown
8748 * @param subject line related to the error, null if absent
8749 * @param report in long form describing the error, null if absent
8750 * @param logFile to include in the report, null if none
8751 * @param crashInfo giving an application stack trace, null if absent
8752 */
8753 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008754 ProcessRecord process, String processName, ActivityRecord activity,
8755 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008756 final String report, final File logFile,
8757 final ApplicationErrorReport.CrashInfo crashInfo) {
8758 // NOTE -- this must never acquire the ActivityManagerService lock,
8759 // otherwise the watchdog may be prevented from resetting the system.
8760
8761 final String dropboxTag = processClass(process) + "_" + eventType;
8762 final DropBoxManager dbox = (DropBoxManager)
8763 mContext.getSystemService(Context.DROPBOX_SERVICE);
8764
8765 // Exit early if the dropbox isn't configured to accept this report type.
8766 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8767
8768 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008769 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008770 if (activity != null) {
8771 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8772 }
8773 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8774 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8775 }
8776 if (parent != null && parent != activity) {
8777 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8778 }
8779 if (subject != null) {
8780 sb.append("Subject: ").append(subject).append("\n");
8781 }
8782 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008783 if (Debug.isDebuggerConnected()) {
8784 sb.append("Debugger: Connected\n");
8785 }
Dan Egnora455d192010-03-12 08:52:28 -08008786 sb.append("\n");
8787
8788 // Do the rest in a worker thread to avoid blocking the caller on I/O
8789 // (After this point, we shouldn't access AMS internal data structures.)
8790 Thread worker = new Thread("Error dump: " + dropboxTag) {
8791 @Override
8792 public void run() {
8793 if (report != null) {
8794 sb.append(report);
8795 }
8796 if (logFile != null) {
8797 try {
8798 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8799 } catch (IOException e) {
8800 Slog.e(TAG, "Error reading " + logFile, e);
8801 }
8802 }
8803 if (crashInfo != null && crashInfo.stackTrace != null) {
8804 sb.append(crashInfo.stackTrace);
8805 }
8806
Jeff Sharkey625239a2012-09-26 22:03:49 -07008807 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8808 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008809 if (lines > 0) {
8810 sb.append("\n");
8811
8812 // Merge several logcat streams, and take the last N lines
8813 InputStreamReader input = null;
8814 try {
8815 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8816 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8817 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8818
8819 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8820 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8821 input = new InputStreamReader(logcat.getInputStream());
8822
8823 int num;
8824 char[] buf = new char[8192];
8825 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8826 } catch (IOException e) {
8827 Slog.e(TAG, "Error running logcat", e);
8828 } finally {
8829 if (input != null) try { input.close(); } catch (IOException e) {}
8830 }
8831 }
8832
8833 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008834 }
Dan Egnora455d192010-03-12 08:52:28 -08008835 };
8836
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008837 if (process == null) {
8838 // If process is null, we are being called from some internal code
8839 // and may be about to die -- run this synchronously.
8840 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008841 } else {
8842 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008843 }
8844 }
8845
8846 /**
8847 * Bring up the "unexpected error" dialog box for a crashing app.
8848 * Deal with edge cases (intercepts from instrumented applications,
8849 * ActivityController, error intent receivers, that sort of thing).
8850 * @param r the application crashing
8851 * @param crashInfo describing the failure
8852 */
8853 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008854 long timeMillis = System.currentTimeMillis();
8855 String shortMsg = crashInfo.exceptionClassName;
8856 String longMsg = crashInfo.exceptionMessage;
8857 String stackTrace = crashInfo.stackTrace;
8858 if (shortMsg != null && longMsg != null) {
8859 longMsg = shortMsg + ": " + longMsg;
8860 } else if (shortMsg != null) {
8861 longMsg = shortMsg;
8862 }
8863
Dan Egnor60d87622009-12-16 16:32:58 -08008864 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008866 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 try {
8868 String name = r != null ? r.processName : null;
8869 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008870 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008871 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008872 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008873 + " at watcher's request");
8874 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008875 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 }
8877 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008878 mController = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -07008879 Watchdog.getInstance().setActivityController(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 }
8881 }
8882
8883 final long origId = Binder.clearCallingIdentity();
8884
8885 // If this process is running instrumentation, finish it.
8886 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008887 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008889 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8890 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 Bundle info = new Bundle();
8892 info.putString("shortMsg", shortMsg);
8893 info.putString("longMsg", longMsg);
8894 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8895 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008896 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008897 }
8898
Dan Egnor60d87622009-12-16 16:32:58 -08008899 // If we can't identify the process or it's already exceeded its crash quota,
8900 // quit right away without showing a crash dialog.
8901 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008903 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 }
8905
8906 Message msg = Message.obtain();
8907 msg.what = SHOW_ERROR_MSG;
8908 HashMap data = new HashMap();
8909 data.put("result", result);
8910 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008911 msg.obj = data;
8912 mHandler.sendMessage(msg);
8913
8914 Binder.restoreCallingIdentity(origId);
8915 }
8916
8917 int res = result.get();
8918
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008919 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008921 if (r != null && !r.isolated) {
8922 // XXX Can't keep track of crash time for isolated processes,
8923 // since they don't have a persistent identity.
8924 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 SystemClock.uptimeMillis());
8926 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008927 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008928 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008929 }
8930 }
8931
8932 if (appErrorIntent != null) {
8933 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008934 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008935 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008936 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008940
8941 Intent createAppErrorIntentLocked(ProcessRecord r,
8942 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8943 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008944 if (report == null) {
8945 return null;
8946 }
8947 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8948 result.setComponent(r.errorReportReceiver);
8949 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8950 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8951 return result;
8952 }
8953
Dan Egnorb7f03672009-12-09 16:22:32 -08008954 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8955 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008956 if (r.errorReportReceiver == null) {
8957 return null;
8958 }
8959
Christopher Tate58d380d2013-03-19 13:10:03 -07008960 if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008961 return null;
8962 }
8963
Dan Egnorb7f03672009-12-09 16:22:32 -08008964 ApplicationErrorReport report = new ApplicationErrorReport();
8965 report.packageName = r.info.packageName;
8966 report.installerPackageName = r.errorReportReceiver.getPackageName();
8967 report.processName = r.processName;
8968 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008969 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008970
Christopher Tate58d380d2013-03-19 13:10:03 -07008971 if (r.crashing || r.forceCrashReport) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008972 report.type = ApplicationErrorReport.TYPE_CRASH;
8973 report.crashInfo = crashInfo;
8974 } else if (r.notResponding) {
8975 report.type = ApplicationErrorReport.TYPE_ANR;
8976 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008977
Dan Egnorb7f03672009-12-09 16:22:32 -08008978 report.anrInfo.activity = r.notRespondingReport.tag;
8979 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8980 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008981 }
8982
Dan Egnorb7f03672009-12-09 16:22:32 -08008983 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008984 }
8985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008986 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008987 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 // assume our apps are happy - lazy create the list
8989 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8990
Dianne Hackborn0c380492012-08-20 17:23:30 -07008991 final boolean allUsers = ActivityManager.checkUidPermission(
8992 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8993 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8994 int userId = UserHandle.getUserId(Binder.getCallingUid());
8995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 synchronized (this) {
8997
8998 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008999 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9000 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07009001 if (!allUsers && app.userId != userId) {
9002 continue;
9003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 if ((app.thread != null) && (app.crashing || app.notResponding)) {
9005 // This one's in trouble, so we'll generate a report for it
9006 // crashes are higher priority (in case there's a crash *and* an anr)
9007 ActivityManager.ProcessErrorStateInfo report = null;
9008 if (app.crashing) {
9009 report = app.crashingReport;
9010 } else if (app.notResponding) {
9011 report = app.notRespondingReport;
9012 }
9013
9014 if (report != null) {
9015 if (errList == null) {
9016 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
9017 }
9018 errList.add(report);
9019 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08009020 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009021 " crashing = " + app.crashing +
9022 " notResponding = " + app.notResponding);
9023 }
9024 }
9025 }
9026 }
9027
9028 return errList;
9029 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009030
9031 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009032 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009033 if (currApp != null) {
9034 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
9035 }
9036 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009037 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
9038 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009039 } else if (adj >= ProcessList.HOME_APP_ADJ) {
9040 if (currApp != null) {
9041 currApp.lru = 0;
9042 }
9043 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009044 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009045 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
9046 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9047 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
9048 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9049 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
9050 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
9051 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
9052 } else {
9053 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
9054 }
9055 }
9056
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009057 private void fillInProcMemInfo(ProcessRecord app,
9058 ActivityManager.RunningAppProcessInfo outInfo) {
9059 outInfo.pid = app.pid;
9060 outInfo.uid = app.info.uid;
9061 if (mHeavyWeightProcess == app) {
9062 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
9063 }
9064 if (app.persistent) {
9065 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
9066 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07009067 if (app.hasActivities) {
9068 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
9069 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009070 outInfo.lastTrimLevel = app.trimMemoryLevel;
9071 int adj = app.curAdj;
9072 outInfo.importance = oomAdjToImportance(adj, outInfo);
9073 outInfo.importanceReasonCode = app.adjTypeCode;
9074 }
9075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08009077 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 // Lazy instantiation of list
9079 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07009080 final boolean allUsers = ActivityManager.checkUidPermission(
9081 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
9082 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
9083 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 synchronized (this) {
9085 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08009086 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9087 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07009088 if (!allUsers && app.userId != userId) {
9089 continue;
9090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
9092 // Generate process state info for running application
9093 ActivityManager.RunningAppProcessInfo currApp =
9094 new ActivityManager.RunningAppProcessInfo(app.processName,
9095 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009096 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009097 if (app.adjSource instanceof ProcessRecord) {
9098 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009099 currApp.importanceReasonImportance = oomAdjToImportance(
9100 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009101 } else if (app.adjSource instanceof ActivityRecord) {
9102 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07009103 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
9104 }
9105 if (app.adjTarget instanceof ComponentName) {
9106 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
9107 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08009108 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 // + " lru=" + currApp.lru);
9110 if (runList == null) {
9111 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
9112 }
9113 runList.add(currApp);
9114 }
9115 }
9116 }
9117 return runList;
9118 }
9119
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009120 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08009121 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009122 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
9123 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
9124 if (runningApps != null && runningApps.size() > 0) {
9125 Set<String> extList = new HashSet<String>();
9126 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
9127 if (app.pkgList != null) {
9128 for (String pkg : app.pkgList) {
9129 extList.add(pkg);
9130 }
9131 }
9132 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07009133 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009134 for (String pkg : extList) {
9135 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07009136 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07009137 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
9138 retList.add(info);
9139 }
9140 } catch (RemoteException e) {
9141 }
9142 }
9143 }
9144 return retList;
9145 }
9146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009148 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
9149 enforceNotIsolatedCaller("getMyMemoryState");
9150 synchronized (this) {
9151 ProcessRecord proc;
9152 synchronized (mPidsSelfLocked) {
9153 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9154 }
9155 fillInProcMemInfo(proc, outInfo);
9156 }
9157 }
9158
9159 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009160 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009161 if (checkCallingPermission(android.Manifest.permission.DUMP)
9162 != PackageManager.PERMISSION_GRANTED) {
9163 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9164 + Binder.getCallingPid()
9165 + ", uid=" + Binder.getCallingUid()
9166 + " without permission "
9167 + android.Manifest.permission.DUMP);
9168 return;
9169 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009170
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009172 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009173 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174
9175 int opti = 0;
9176 while (opti < args.length) {
9177 String opt = args[opti];
9178 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9179 break;
9180 }
9181 opti++;
9182 if ("-a".equals(opt)) {
9183 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009184 } else if ("-c".equals(opt)) {
9185 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009186 } else if ("-h".equals(opt)) {
9187 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009188 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009190 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009191 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009192 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
9193 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009194 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009195 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08009196 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009197 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009198 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009200 pw.println(" all: dump all activities");
9201 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009202 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009203 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
9204 pw.println(" a partial substring in a component name, a");
9205 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009206 pw.println(" -a: include all available server state.");
9207 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 } else {
9210 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009213
9214 long origId = Binder.clearCallingIdentity();
9215 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 // Is the caller requesting to dump a particular piece of data?
9217 if (opti < args.length) {
9218 String cmd = args[opti];
9219 opti++;
9220 if ("activities".equals(cmd) || "a".equals(cmd)) {
9221 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009222 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009223 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009225 String[] newArgs;
9226 String name;
9227 if (opti >= args.length) {
9228 name = null;
9229 newArgs = EMPTY_STRING_ARRAY;
9230 } else {
9231 name = args[opti];
9232 opti++;
9233 newArgs = new String[args.length - opti];
9234 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9235 args.length - opti);
9236 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009239 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009241 String[] newArgs;
9242 String name;
9243 if (opti >= args.length) {
9244 name = null;
9245 newArgs = EMPTY_STRING_ARRAY;
9246 } else {
9247 name = args[opti];
9248 opti++;
9249 newArgs = new String[args.length - opti];
9250 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9251 args.length - opti);
9252 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009254 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009256 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009257 String[] newArgs;
9258 String name;
9259 if (opti >= args.length) {
9260 name = null;
9261 newArgs = EMPTY_STRING_ARRAY;
9262 } else {
9263 name = args[opti];
9264 opti++;
9265 newArgs = new String[args.length - opti];
9266 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9267 args.length - opti);
9268 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009270 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009272 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9273 synchronized (this) {
9274 dumpOomLocked(fd, pw, args, opti, true);
9275 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009276 } else if ("provider".equals(cmd)) {
9277 String[] newArgs;
9278 String name;
9279 if (opti >= args.length) {
9280 name = null;
9281 newArgs = EMPTY_STRING_ARRAY;
9282 } else {
9283 name = args[opti];
9284 opti++;
9285 newArgs = new String[args.length - opti];
9286 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9287 }
9288 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9289 pw.println("No providers match: " + name);
9290 pw.println("Use -h for help.");
9291 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009292 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9293 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009294 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009295 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009296 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009297 String[] newArgs;
9298 String name;
9299 if (opti >= args.length) {
9300 name = null;
9301 newArgs = EMPTY_STRING_ARRAY;
9302 } else {
9303 name = args[opti];
9304 opti++;
9305 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009306 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9307 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009308 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009309 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009310 pw.println("No services match: " + name);
9311 pw.println("Use -h for help.");
9312 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009313 } else if ("package".equals(cmd)) {
9314 String[] newArgs;
9315 if (opti >= args.length) {
9316 pw.println("package: no package name specified");
9317 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009318 } else {
9319 dumpPackage = args[opti];
9320 opti++;
9321 newArgs = new String[args.length - opti];
9322 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9323 args.length - opti);
9324 args = newArgs;
9325 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009326 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009327 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009328 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9329 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009330 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009331 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009332 } else {
9333 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009334 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9335 pw.println("Bad activity command, or no activities match: " + cmd);
9336 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009337 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009338 }
9339 if (!more) {
9340 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009341 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009342 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009343 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009344
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009345 // No piece of data specified, dump everything.
9346 synchronized (this) {
9347 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009348 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009349 if (needSep) {
9350 pw.println(" ");
9351 }
9352 if (dumpAll) {
9353 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009354 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009355 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009356 if (needSep) {
9357 pw.println(" ");
9358 }
9359 if (dumpAll) {
9360 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009362 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 if (needSep) {
9364 pw.println(" ");
9365 }
9366 if (dumpAll) {
9367 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009368 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009369 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009370 if (needSep) {
9371 pw.println(" ");
9372 }
9373 if (dumpAll) {
9374 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009375 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009376 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 if (needSep) {
9378 pw.println(" ");
9379 }
9380 if (dumpAll) {
9381 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009382 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009383 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009384 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009385 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009386 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009387
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009388 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009389 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009390 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9391 pw.println(" Main stack:");
Craig Mautner2ad92072013-02-25 16:19:24 -08009392 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9393 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009394 pw.println(" ");
9395 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009396 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9397 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009398 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009399 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009400 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009402 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009403 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009404 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009406 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009407 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009408 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009409 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009410 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9411 pw.println(" ");
9412 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009413 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009414 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009415 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009416 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009417 pw.println(" ");
9418 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009420 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009423 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009424 if (mMainStack.mPausingActivity != null) {
9425 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009426 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009427 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009428 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009429 if (dumpAll) {
9430 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9431 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009432 pw.println(" mDismissKeyguardOnNextActivity: "
9433 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009436 if (mRecentTasks.size() > 0) {
9437 pw.println();
9438 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009439
9440 final int N = mRecentTasks.size();
9441 for (int i=0; i<N; i++) {
9442 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009443 if (dumpPackage != null) {
9444 if (tr.realActivity == null ||
9445 !dumpPackage.equals(tr.realActivity)) {
9446 continue;
9447 }
9448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009449 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9450 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009451 if (dumpAll) {
9452 mRecentTasks.get(i).dump(pw, " ");
9453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009454 }
9455 }
9456
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009457 if (dumpAll) {
9458 pw.println(" ");
9459 pw.println(" mCurTask: " + mCurTask);
9460 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009461
9462 return true;
9463 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009464
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009467 boolean needSep = false;
9468 int numPers = 0;
9469
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009470 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9471
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009472 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009473 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9474 final int NA = procs.size();
9475 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009476 ProcessRecord r = procs.valueAt(ia);
9477 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9478 continue;
9479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009480 if (!needSep) {
9481 pw.println(" All known processes:");
9482 needSep = true;
9483 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009484 pw.print(r.persistent ? " *PERS*" : " *APP*");
9485 pw.print(" UID "); pw.print(procs.keyAt(ia));
9486 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 r.dump(pw, " ");
9488 if (r.persistent) {
9489 numPers++;
9490 }
9491 }
9492 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009493 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009494
9495 if (mIsolatedProcesses.size() > 0) {
9496 if (needSep) pw.println(" ");
9497 needSep = true;
9498 pw.println(" Isolated process list (sorted by uid):");
9499 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9500 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9501 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9502 continue;
9503 }
9504 pw.println(String.format("%sIsolated #%2d: %s",
9505 " ", i, r.toString()));
9506 }
9507 }
9508
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509 if (mLruProcesses.size() > 0) {
9510 if (needSep) pw.println(" ");
9511 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009512 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009513 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 needSep = true;
9516 }
9517
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009518 if (dumpAll) {
9519 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009520 boolean printed = false;
9521 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9522 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9523 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9524 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009526 if (!printed) {
9527 if (needSep) pw.println(" ");
9528 needSep = true;
9529 pw.println(" PID mappings:");
9530 printed = true;
9531 }
9532 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9533 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534 }
9535 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009536 }
9537
9538 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009539 synchronized (mPidsSelfLocked) {
9540 boolean printed = false;
9541 for (int i=0; i<mForegroundProcesses.size(); i++) {
9542 ProcessRecord r = mPidsSelfLocked.get(
9543 mForegroundProcesses.valueAt(i).pid);
9544 if (dumpPackage != null && (r == null
9545 || !dumpPackage.equals(r.info.packageName))) {
9546 continue;
9547 }
9548 if (!printed) {
9549 if (needSep) pw.println(" ");
9550 needSep = true;
9551 pw.println(" Foreground Processes:");
9552 printed = true;
9553 }
9554 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9555 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009557 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009558 }
9559
9560 if (mPersistentStartingProcesses.size() > 0) {
9561 if (needSep) pw.println(" ");
9562 needSep = true;
9563 pw.println(" Persisent processes that are starting:");
9564 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009565 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009567
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 if (mRemovedProcesses.size() > 0) {
9569 if (needSep) pw.println(" ");
9570 needSep = true;
9571 pw.println(" Processes that are being removed:");
9572 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009573 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009574 }
9575
9576 if (mProcessesOnHold.size() > 0) {
9577 if (needSep) pw.println(" ");
9578 needSep = true;
9579 pw.println(" Processes that are on old until the system is ready:");
9580 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009581 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009584 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009585
9586 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009587 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009588 long now = SystemClock.uptimeMillis();
9589 for (Map.Entry<String, SparseArray<Long>> procs
9590 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009591 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009592 SparseArray<Long> uids = procs.getValue();
9593 final int N = uids.size();
9594 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009595 int puid = uids.keyAt(i);
9596 ProcessRecord r = mProcessNames.get(pname, puid);
9597 if (dumpPackage != null && (r == null
9598 || !dumpPackage.equals(r.info.packageName))) {
9599 continue;
9600 }
9601 if (!printed) {
9602 if (needSep) pw.println(" ");
9603 needSep = true;
9604 pw.println(" Time since processes crashed:");
9605 printed = true;
9606 }
9607 pw.print(" Process "); pw.print(pname);
9608 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009609 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009610 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9611 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009612 }
9613 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009615
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009616 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009617 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009618 for (Map.Entry<String, SparseArray<Long>> procs
9619 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009620 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009621 SparseArray<Long> uids = procs.getValue();
9622 final int N = uids.size();
9623 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009624 int puid = uids.keyAt(i);
9625 ProcessRecord r = mProcessNames.get(pname, puid);
9626 if (dumpPackage != null && (r == null
9627 || !dumpPackage.equals(r.info.packageName))) {
9628 continue;
9629 }
9630 if (!printed) {
9631 if (needSep) pw.println(" ");
9632 needSep = true;
9633 pw.println(" Bad processes:");
9634 }
9635 pw.print(" Bad process "); pw.print(pname);
9636 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009637 pw.print(": crashed at time ");
9638 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009639 }
9640 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009643 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009644 pw.println(" mStartedUsers:");
9645 for (int i=0; i<mStartedUsers.size(); i++) {
9646 UserStartedState uss = mStartedUsers.valueAt(i);
9647 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009648 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009649 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009650 pw.print(" mStartedUserArray: [");
9651 for (int i=0; i<mStartedUserArray.length; i++) {
9652 if (i > 0) pw.print(", ");
9653 pw.print(mStartedUserArray[i]);
9654 }
9655 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009656 pw.print(" mUserLru: [");
9657 for (int i=0; i<mUserLru.size(); i++) {
9658 if (i > 0) pw.print(", ");
9659 pw.print(mUserLru.get(i));
9660 }
9661 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009662 if (dumpAll) {
9663 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9664 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009665 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009666 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009667 if (dumpAll) {
9668 StringBuilder sb = new StringBuilder(128);
9669 sb.append(" mPreviousProcessVisibleTime: ");
9670 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9671 pw.println(sb);
9672 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009673 if (mHeavyWeightProcess != null) {
9674 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9675 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009676 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009677 if (dumpAll) {
9678 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009679 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009681 for (Map.Entry<String, Integer> entry
9682 : mCompatModePackages.getPackages().entrySet()) {
9683 String pkg = entry.getKey();
9684 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9686 continue;
9687 }
9688 if (!printed) {
9689 pw.println(" mScreenCompatPackages:");
9690 printed = true;
9691 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009692 pw.print(" "); pw.print(pkg); pw.print(": ");
9693 pw.print(mode); pw.println();
9694 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009695 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009696 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009697 if (mSleeping || mWentToSleep || mLockScreenShown) {
9698 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9699 + " mLockScreenShown " + mLockScreenShown);
9700 }
9701 if (mShuttingDown) {
9702 pw.println(" mShuttingDown=" + mShuttingDown);
9703 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009704 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9705 || mOrigWaitForDebugger) {
9706 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9707 + " mDebugTransient=" + mDebugTransient
9708 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9709 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009710 if (mOpenGlTraceApp != null) {
9711 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9712 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009713 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9714 || mProfileFd != null) {
9715 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9716 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9717 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9718 + mAutoStopProfiler);
9719 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009720 if (mAlwaysFinishActivities || mController != null) {
9721 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9722 + " mController=" + mController);
9723 }
9724 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009725 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009726 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009727 + " mProcessesReady=" + mProcessesReady
9728 + " mSystemReady=" + mSystemReady);
9729 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009730 + " mBooted=" + mBooted
9731 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009732 pw.print(" mLastPowerCheckRealtime=");
9733 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9734 pw.println("");
9735 pw.print(" mLastPowerCheckUptime=");
9736 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9737 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009738 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9739 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009740 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009741 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9742 + " mNumHiddenProcs=" + mNumHiddenProcs
9743 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009744 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009745 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009746
9747 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 }
9749
Dianne Hackborn287952c2010-09-22 22:34:31 -07009750 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009751 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009752 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009753 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009754 long now = SystemClock.uptimeMillis();
9755 for (int i=0; i<mProcessesToGc.size(); i++) {
9756 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009757 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9758 continue;
9759 }
9760 if (!printed) {
9761 if (needSep) pw.println(" ");
9762 needSep = true;
9763 pw.println(" Processes that are waiting to GC:");
9764 printed = true;
9765 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009766 pw.print(" Process "); pw.println(proc);
9767 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9768 pw.print(", last gced=");
9769 pw.print(now-proc.lastRequestedGc);
9770 pw.print(" ms ago, last lowMem=");
9771 pw.print(now-proc.lastLowMemory);
9772 pw.println(" ms ago");
9773
9774 }
9775 }
9776 return needSep;
9777 }
9778
9779 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9780 int opti, boolean dumpAll) {
9781 boolean needSep = false;
9782
9783 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009784 if (needSep) pw.println(" ");
9785 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009786 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009787 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009788 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009789 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9790 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9791 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9792 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9793 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009794 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009795 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009796 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009797 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009798 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009799 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009800
9801 if (needSep) pw.println(" ");
9802 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009803 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009804 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009805 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009806 needSep = true;
9807 }
9808
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009809 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009810
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009811 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009812 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009813 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009814 if (mHeavyWeightProcess != null) {
9815 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9816 }
9817
9818 return true;
9819 }
9820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009821 /**
9822 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009823 * - no provider specified: dump all the providers
9824 * - a flattened component name that matched an existing provider was specified as the
9825 * first arg: dump that one provider
9826 * - the first arg isn't the flattened component name of an existing provider:
9827 * dump all providers whose component contains the first arg as a substring
9828 */
9829 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9830 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009831 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009832 }
9833
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009834 static class ItemMatcher {
9835 ArrayList<ComponentName> components;
9836 ArrayList<String> strings;
9837 ArrayList<Integer> objects;
9838 boolean all;
9839
9840 ItemMatcher() {
9841 all = true;
9842 }
9843
9844 void build(String name) {
9845 ComponentName componentName = ComponentName.unflattenFromString(name);
9846 if (componentName != null) {
9847 if (components == null) {
9848 components = new ArrayList<ComponentName>();
9849 }
9850 components.add(componentName);
9851 all = false;
9852 } else {
9853 int objectId = 0;
9854 // Not a '/' separated full component name; maybe an object ID?
9855 try {
9856 objectId = Integer.parseInt(name, 16);
9857 if (objects == null) {
9858 objects = new ArrayList<Integer>();
9859 }
9860 objects.add(objectId);
9861 all = false;
9862 } catch (RuntimeException e) {
9863 // Not an integer; just do string match.
9864 if (strings == null) {
9865 strings = new ArrayList<String>();
9866 }
9867 strings.add(name);
9868 all = false;
9869 }
9870 }
9871 }
9872
9873 int build(String[] args, int opti) {
9874 for (; opti<args.length; opti++) {
9875 String name = args[opti];
9876 if ("--".equals(name)) {
9877 return opti+1;
9878 }
9879 build(name);
9880 }
9881 return opti;
9882 }
9883
9884 boolean match(Object object, ComponentName comp) {
9885 if (all) {
9886 return true;
9887 }
9888 if (components != null) {
9889 for (int i=0; i<components.size(); i++) {
9890 if (components.get(i).equals(comp)) {
9891 return true;
9892 }
9893 }
9894 }
9895 if (objects != null) {
9896 for (int i=0; i<objects.size(); i++) {
9897 if (System.identityHashCode(object) == objects.get(i)) {
9898 return true;
9899 }
9900 }
9901 }
9902 if (strings != null) {
9903 String flat = comp.flattenToString();
9904 for (int i=0; i<strings.size(); i++) {
9905 if (flat.contains(strings.get(i))) {
9906 return true;
9907 }
9908 }
9909 }
9910 return false;
9911 }
9912 }
9913
Dianne Hackborn625ac272010-09-17 18:29:22 -07009914 /**
9915 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009916 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009917 * - the cmd arg isn't the flattened component name of an existing activity:
9918 * dump all activity whose component contains the cmd as a substring
9919 * - A hex number of the ActivityRecord object instance.
9920 */
9921 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9922 int opti, boolean dumpAll) {
Craig Mautner2ad92072013-02-25 16:19:24 -08009923 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
9924
9925 if ("all".equals(name)) {
9926 synchronized (this) {
9927 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
9928 activities.add(r1);
9929 }
9930 }
9931 } else if ("top".equals(name)) {
9932 synchronized (this) {
9933 final int N = mMainStack.mHistory.size();
9934 if (N > 0) {
9935 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9936 }
9937 }
9938 } else {
9939 ItemMatcher matcher = new ItemMatcher();
9940 matcher.build(name);
9941
9942 synchronized (this) {
9943 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
9944 if (matcher.match(r1, r1.intent.getComponent())) {
9945 activities.add(r1);
9946 }
9947 }
9948 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009949 }
9950
9951 if (activities.size() <= 0) {
9952 return false;
9953 }
9954
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009955 String[] newArgs = new String[args.length - opti];
9956 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9957
Dianne Hackborn30d71892010-12-11 10:37:55 -08009958 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009959 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009960 for (int i=activities.size()-1; i>=0; i--) {
9961 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009962 if (needSep) {
9963 pw.println();
9964 }
9965 needSep = true;
9966 synchronized (this) {
9967 if (lastTask != r.task) {
9968 lastTask = r.task;
9969 pw.print("TASK "); pw.print(lastTask.affinity);
9970 pw.print(" id="); pw.println(lastTask.taskId);
9971 if (dumpAll) {
9972 lastTask.dump(pw, " ");
9973 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009974 }
9975 }
9976 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009977 }
9978 return true;
9979 }
9980
9981 /**
9982 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9983 * there is a thread associated with the activity.
9984 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009985 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009986 final ActivityRecord r, String[] args, boolean dumpAll) {
9987 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009988 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009989 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9990 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9991 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009992 if (r.app != null) pw.println(r.app.pid);
9993 else pw.println("(not running)");
9994 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009995 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009996 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009997 }
9998 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 // flush anything that is already in the PrintWriter since the thread is going
10000 // to write to the file descriptor directly
10001 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -070010002 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010003 TransferPipe tp = new TransferPipe();
10004 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010005 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10006 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010007 tp.go(fd);
10008 } finally {
10009 tp.kill();
10010 }
10011 } catch (IOException e) {
10012 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -070010013 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010014 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -070010015 }
10016 }
10017 }
10018
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010019 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010020 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010021 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -070010022 boolean onlyHistory = false;
10023
10024 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070010025 if (opti < args.length && "-s".equals(args[opti])) {
10026 dumpAll = false;
10027 }
Dianne Hackborn786b4402012-08-27 15:14:02 -070010028 onlyHistory = true;
10029 dumpPackage = null;
10030 }
10031
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010032 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -070010033 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010034 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010035 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010036 Iterator it = mRegisteredReceivers.values().iterator();
10037 while (it.hasNext()) {
10038 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010039 if (dumpPackage != null && (r.app == null ||
10040 !dumpPackage.equals(r.app.info.packageName))) {
10041 continue;
10042 }
10043 if (!printed) {
10044 pw.println(" Registered Receivers:");
10045 needSep = true;
10046 printed = true;
10047 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010048 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010049 r.dump(pw, " ");
10050 }
10051 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010052
10053 if (mReceiverResolver.dump(pw, needSep ?
10054 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
10055 " ", dumpPackage, false)) {
10056 needSep = true;
10057 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010058 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010059
10060 for (BroadcastQueue q : mBroadcastQueues) {
10061 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010063
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010064 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010065
Dianne Hackborn786b4402012-08-27 15:14:02 -070010066 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010067 for (int user=0; user<mStickyBroadcasts.size(); user++) {
10068 if (needSep) {
10069 pw.println();
10070 }
10071 needSep = true;
10072 pw.print(" Sticky broadcasts for user ");
10073 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
10074 StringBuilder sb = new StringBuilder(128);
10075 for (Map.Entry<String, ArrayList<Intent>> ent
10076 : mStickyBroadcasts.valueAt(user).entrySet()) {
10077 pw.print(" * Sticky action "); pw.print(ent.getKey());
10078 if (dumpAll) {
10079 pw.println(":");
10080 ArrayList<Intent> intents = ent.getValue();
10081 final int N = intents.size();
10082 for (int i=0; i<N; i++) {
10083 sb.setLength(0);
10084 sb.append(" Intent: ");
10085 intents.get(i).toShortString(sb, false, true, false, false);
10086 pw.println(sb.toString());
10087 Bundle bundle = intents.get(i).getExtras();
10088 if (bundle != null) {
10089 pw.print(" ");
10090 pw.println(bundle.toString());
10091 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010092 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010093 } else {
10094 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010095 }
10096 }
10097 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010098 }
10099
Dianne Hackborn786b4402012-08-27 15:14:02 -070010100 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010101 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -080010102 for (BroadcastQueue queue : mBroadcastQueues) {
10103 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
10104 + queue.mBroadcastsScheduled);
10105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010106 pw.println(" mHandler:");
10107 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010108 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010110
10111 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010112 }
10113
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010114 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010115 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -070010116 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010117
Dianne Hackborn1c9b2602011-08-19 14:08:43 -070010118 ItemMatcher matcher = new ItemMatcher();
10119 matcher.build(args, opti);
10120
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010121 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -070010122
10123 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010124
10125 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010126 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010127 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010128 ContentProviderRecord r = mLaunchingProviders.get(i);
10129 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
10130 continue;
10131 }
10132 if (!printed) {
10133 if (needSep) pw.println(" ");
10134 needSep = true;
10135 pw.println(" Launching content providers:");
10136 printed = true;
10137 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010138 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010139 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010140 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010141 }
10142
10143 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010144 if (needSep) pw.println();
10145 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010146 pw.println("Granted Uri Permissions:");
10147 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
10148 int uid = mGrantedUriPermissions.keyAt(i);
10149 HashMap<Uri, UriPermission> perms
10150 = mGrantedUriPermissions.valueAt(i);
10151 pw.print(" * UID "); pw.print(uid);
10152 pw.println(" holds:");
10153 for (UriPermission perm : perms.values()) {
10154 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010155 if (dumpAll) {
10156 perm.dump(pw, " ");
10157 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010158 }
10159 }
10160 needSep = true;
10161 }
10162
10163 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010164 }
10165
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010166 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010167 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010168 boolean needSep = false;
10169
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010170 if (mIntentSenderRecords.size() > 0) {
10171 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010172 Iterator<WeakReference<PendingIntentRecord>> it
10173 = mIntentSenderRecords.values().iterator();
10174 while (it.hasNext()) {
10175 WeakReference<PendingIntentRecord> ref = it.next();
10176 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010177 if (dumpPackage != null && (rec == null
10178 || !dumpPackage.equals(rec.key.packageName))) {
10179 continue;
10180 }
10181 if (!printed) {
10182 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10183 printed = true;
10184 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010185 needSep = true;
10186 if (rec != null) {
10187 pw.print(" * "); pw.println(rec);
10188 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010190 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010191 } else {
10192 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 }
10194 }
10195 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010196
10197 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010198 }
10199
Craig Mautner2ad92072013-02-25 16:19:24 -080010200 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010201 String prefix, String label, boolean complete, boolean brief, boolean client,
10202 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010203 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010204 boolean needNL = false;
10205 final String innerPrefix = prefix + " ";
10206 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010207 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010208 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010209 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10210 continue;
10211 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010212 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010213 if (needNL) {
10214 pw.println(" ");
10215 needNL = false;
10216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010217 if (lastTask != r.task) {
10218 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010219 pw.print(prefix);
10220 pw.print(full ? "* " : " ");
10221 pw.println(lastTask);
10222 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010223 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010224 } else if (complete) {
10225 // Complete + brief == give a summary. Isn't that obvious?!?
10226 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010227 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010228 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010229 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010232 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10233 pw.print(" #"); pw.print(i); pw.print(": ");
10234 pw.println(r);
10235 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010236 r.dump(pw, innerPrefix);
10237 } else if (complete) {
10238 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010239 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010240 if (r.app != null) {
10241 pw.print(innerPrefix); pw.println(r.app);
10242 }
10243 }
10244 if (client && r.app != null && r.app.thread != null) {
10245 // flush anything that is already in the PrintWriter since the thread is going
10246 // to write to the file descriptor directly
10247 pw.flush();
10248 try {
10249 TransferPipe tp = new TransferPipe();
10250 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010251 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10252 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010253 // Short timeout, since blocking here can
10254 // deadlock with the application.
10255 tp.go(fd, 2000);
10256 } finally {
10257 tp.kill();
10258 }
10259 } catch (IOException e) {
10260 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10261 } catch (RemoteException e) {
10262 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10263 }
10264 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010266 }
10267 }
10268
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010269 private static String buildOomTag(String prefix, String space, int val, int base) {
10270 if (val == base) {
10271 if (space == null) return prefix;
10272 return prefix + " ";
10273 }
10274 return prefix + "+" + Integer.toString(val-base);
10275 }
10276
10277 private static final int dumpProcessList(PrintWriter pw,
10278 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010279 String prefix, String normalLabel, String persistentLabel,
10280 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010282 final int N = list.size()-1;
10283 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010284 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010285 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10286 continue;
10287 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010288 pw.println(String.format("%s%s #%2d: %s",
10289 prefix, (r.persistent ? persistentLabel : normalLabel),
10290 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 if (r.persistent) {
10292 numPers++;
10293 }
10294 }
10295 return numPers;
10296 }
10297
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010298 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010299 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010300 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010301 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010302
Dianne Hackborn905577f2011-09-07 18:31:28 -070010303 ArrayList<Pair<ProcessRecord, Integer>> list
10304 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10305 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010306 ProcessRecord r = origList.get(i);
10307 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10308 continue;
10309 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010310 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10311 }
10312
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010313 if (list.size() <= 0) {
10314 return false;
10315 }
10316
Dianne Hackborn905577f2011-09-07 18:31:28 -070010317 Comparator<Pair<ProcessRecord, Integer>> comparator
10318 = new Comparator<Pair<ProcessRecord, Integer>>() {
10319 @Override
10320 public int compare(Pair<ProcessRecord, Integer> object1,
10321 Pair<ProcessRecord, Integer> object2) {
10322 if (object1.first.setAdj != object2.first.setAdj) {
10323 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10324 }
10325 if (object1.second.intValue() != object2.second.intValue()) {
10326 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10327 }
10328 return 0;
10329 }
10330 };
10331
10332 Collections.sort(list, comparator);
10333
Dianne Hackborn287952c2010-09-22 22:34:31 -070010334 final long curRealtime = SystemClock.elapsedRealtime();
10335 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10336 final long curUptime = SystemClock.uptimeMillis();
10337 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10338
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010339 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010340 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010341 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010342 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010343 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010344 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10345 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010346 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10347 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010348 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10349 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010350 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10351 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010352 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010353 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010354 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10355 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10356 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10357 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10358 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10359 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10360 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10361 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010362 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10363 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010364 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10365 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010366 } else {
10367 oomAdj = Integer.toString(r.setAdj);
10368 }
10369 String schedGroup;
10370 switch (r.setSchedGroup) {
10371 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10372 schedGroup = "B";
10373 break;
10374 case Process.THREAD_GROUP_DEFAULT:
10375 schedGroup = "F";
10376 break;
10377 default:
10378 schedGroup = Integer.toString(r.setSchedGroup);
10379 break;
10380 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010381 String foreground;
10382 if (r.foregroundActivities) {
10383 foreground = "A";
10384 } else if (r.foregroundServices) {
10385 foreground = "S";
10386 } else {
10387 foreground = " ";
10388 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010389 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010390 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010391 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10392 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010393 if (r.adjSource != null || r.adjTarget != null) {
10394 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010395 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010396 if (r.adjTarget instanceof ComponentName) {
10397 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10398 } else if (r.adjTarget != null) {
10399 pw.print(r.adjTarget.toString());
10400 } else {
10401 pw.print("{null}");
10402 }
10403 pw.print("<=");
10404 if (r.adjSource instanceof ProcessRecord) {
10405 pw.print("Proc{");
10406 pw.print(((ProcessRecord)r.adjSource).toShortString());
10407 pw.println("}");
10408 } else if (r.adjSource != null) {
10409 pw.println(r.adjSource.toString());
10410 } else {
10411 pw.println("{null}");
10412 }
10413 }
10414 if (inclDetails) {
10415 pw.print(prefix);
10416 pw.print(" ");
10417 pw.print("oom: max="); pw.print(r.maxAdj);
10418 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010419 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010420 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010421 pw.print(" curRaw="); pw.print(r.curRawAdj);
10422 pw.print(" setRaw="); pw.print(r.setRawAdj);
10423 pw.print(" cur="); pw.print(r.curAdj);
10424 pw.print(" set="); pw.println(r.setAdj);
10425 pw.print(prefix);
10426 pw.print(" ");
10427 pw.print("keeping="); pw.print(r.keeping);
10428 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010429 pw.print(" empty="); pw.print(r.empty);
10430 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010431
10432 if (!r.keeping) {
10433 if (r.lastWakeTime != 0) {
10434 long wtime;
10435 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10436 synchronized (stats) {
10437 wtime = stats.getProcessWakeTime(r.info.uid,
10438 r.pid, curRealtime);
10439 }
10440 long timeUsed = wtime - r.lastWakeTime;
10441 pw.print(prefix);
10442 pw.print(" ");
10443 pw.print("keep awake over ");
10444 TimeUtils.formatDuration(realtimeSince, pw);
10445 pw.print(" used ");
10446 TimeUtils.formatDuration(timeUsed, pw);
10447 pw.print(" (");
10448 pw.print((timeUsed*100)/realtimeSince);
10449 pw.println("%)");
10450 }
10451 if (r.lastCpuTime != 0) {
10452 long timeUsed = r.curCpuTime - r.lastCpuTime;
10453 pw.print(prefix);
10454 pw.print(" ");
10455 pw.print("run cpu over ");
10456 TimeUtils.formatDuration(uptimeSince, pw);
10457 pw.print(" used ");
10458 TimeUtils.formatDuration(timeUsed, pw);
10459 pw.print(" (");
10460 pw.print((timeUsed*100)/uptimeSince);
10461 pw.println("%)");
10462 }
10463 }
10464 }
10465 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010466 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010467 }
10468
Dianne Hackbornb437e092011-08-05 17:50:29 -070010469 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010470 ArrayList<ProcessRecord> procs;
10471 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010472 if (args != null && args.length > start
10473 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010474 procs = new ArrayList<ProcessRecord>();
10475 int pid = -1;
10476 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010477 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010478 } catch (NumberFormatException e) {
10479
10480 }
10481 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10482 ProcessRecord proc = mLruProcesses.get(i);
10483 if (proc.pid == pid) {
10484 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010485 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010486 procs.add(proc);
10487 }
10488 }
10489 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010490 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010491 return null;
10492 }
10493 } else {
10494 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10495 }
10496 }
10497 return procs;
10498 }
10499
10500 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10501 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010502 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010503 if (procs == null) {
10504 return;
10505 }
10506
10507 long uptime = SystemClock.uptimeMillis();
10508 long realtime = SystemClock.elapsedRealtime();
10509 pw.println("Applications Graphics Acceleration Info:");
10510 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10511
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010512 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10513 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010514 if (r.thread != null) {
10515 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10516 pw.flush();
10517 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010518 TransferPipe tp = new TransferPipe();
10519 try {
10520 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10521 tp.go(fd);
10522 } finally {
10523 tp.kill();
10524 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010525 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010526 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010527 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010528 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010529 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010530 pw.flush();
10531 }
10532 }
10533 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010534 }
10535
Jeff Brown6754ba22011-12-14 20:20:01 -080010536 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10537 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10538 if (procs == null) {
10539 return;
10540 }
10541
10542 pw.println("Applications Database Info:");
10543
10544 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10545 ProcessRecord r = procs.get(i);
10546 if (r.thread != null) {
10547 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10548 pw.flush();
10549 try {
10550 TransferPipe tp = new TransferPipe();
10551 try {
10552 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10553 tp.go(fd);
10554 } finally {
10555 tp.kill();
10556 }
10557 } catch (IOException e) {
10558 pw.println("Failure while dumping the app: " + r);
10559 pw.flush();
10560 } catch (RemoteException e) {
10561 pw.println("Got a RemoteException while dumping the app " + r);
10562 pw.flush();
10563 }
10564 }
10565 }
10566 }
10567
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010568 final static class MemItem {
10569 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010570 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010571 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010572 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010573 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010574
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010575 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010576 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010577 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010578 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010579 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010580 }
10581 }
10582
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010583 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010584 boolean sort) {
10585 if (sort) {
10586 Collections.sort(items, new Comparator<MemItem>() {
10587 @Override
10588 public int compare(MemItem lhs, MemItem rhs) {
10589 if (lhs.pss < rhs.pss) {
10590 return 1;
10591 } else if (lhs.pss > rhs.pss) {
10592 return -1;
10593 }
10594 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010595 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010596 });
10597 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010598
10599 for (int i=0; i<items.size(); i++) {
10600 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010601 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010602 if (mi.subitems != null) {
10603 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10604 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010605 }
10606 }
10607
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010608 // These are in KB.
10609 static final long[] DUMP_MEM_BUCKETS = new long[] {
10610 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10611 120*1024, 160*1024, 200*1024,
10612 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10613 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10614 };
10615
Dianne Hackborn672342c2011-11-29 11:29:02 -080010616 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10617 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010618 int start = label.lastIndexOf('.');
10619 if (start >= 0) start++;
10620 else start = 0;
10621 int end = label.length();
10622 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10623 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10624 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10625 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010626 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010627 out.append(label, start, end);
10628 return;
10629 }
10630 }
10631 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010632 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010633 out.append(label, start, end);
10634 }
10635
10636 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10637 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10638 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10639 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10640 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10641 };
10642 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10643 "System", "Persistent", "Foreground",
10644 "Visible", "Perceptible", "Heavy Weight",
10645 "Backup", "A Services", "Home", "Previous",
10646 "B Services", "Background"
10647 };
10648
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010649 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010650 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010651 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010652 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010653 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010654
10655 int opti = 0;
10656 while (opti < args.length) {
10657 String opt = args[opti];
10658 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10659 break;
10660 }
10661 opti++;
10662 if ("-a".equals(opt)) {
10663 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010664 } else if ("--oom".equals(opt)) {
10665 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010666 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010667 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010668 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010669 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010670 pw.println("If [process] is specified it can be the name or ");
10671 pw.println("pid of a specific process to dump.");
10672 return;
10673 } else {
10674 pw.println("Unknown argument: " + opt + "; use -h for help");
10675 }
10676 }
10677
10678 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010679 if (procs == null) {
10680 return;
10681 }
10682
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010683 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 long uptime = SystemClock.uptimeMillis();
10685 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010686
10687 if (procs.size() == 1 || isCheckinRequest) {
10688 dumpAll = true;
10689 }
10690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 if (isCheckinRequest) {
10692 // short checkin version
10693 pw.println(uptime + "," + realtime);
10694 pw.flush();
10695 } else {
10696 pw.println("Applications Memory Usage (kB):");
10697 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10698 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010699
Dianne Hackbornb437e092011-08-05 17:50:29 -070010700 String[] innerArgs = new String[args.length-opti];
10701 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10702
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010703 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10704 long nativePss=0, dalvikPss=0, otherPss=0;
10705 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10706
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010707 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10708 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10709 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010710
10711 long totalPss = 0;
10712
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010713 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10714 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010715 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010716 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010717 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10718 pw.flush();
10719 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010720 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010721 if (dumpAll) {
10722 try {
10723 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10724 } catch (RemoteException e) {
10725 if (!isCheckinRequest) {
10726 pw.println("Got RemoteException!");
10727 pw.flush();
10728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010730 } else {
10731 mi = new Debug.MemoryInfo();
10732 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010734
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010735 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010736 long myTotalPss = mi.getTotalPss();
10737 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010738 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010739 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010740 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010741
10742 nativePss += mi.nativePss;
10743 dalvikPss += mi.dalvikPss;
10744 otherPss += mi.otherPss;
10745 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10746 long mem = mi.getOtherPss(j);
10747 miscPss[j] += mem;
10748 otherPss -= mem;
10749 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010750
10751 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010752 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10753 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010754 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010755 if (oomProcs[oomIndex] == null) {
10756 oomProcs[oomIndex] = new ArrayList<MemItem>();
10757 }
10758 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010759 break;
10760 }
10761 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 }
10764 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010765
10766 if (!isCheckinRequest && procs.size() > 1) {
10767 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10768
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010769 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10770 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10771 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010772 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010773 String label = Debug.MemoryInfo.getOtherLabel(j);
10774 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010775 }
10776
Dianne Hackbornb437e092011-08-05 17:50:29 -070010777 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10778 for (int j=0; j<oomPss.length; j++) {
10779 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010780 String label = DUMP_MEM_OOM_LABEL[j];
10781 MemItem item = new MemItem(label, label, oomPss[j],
10782 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010783 item.subitems = oomProcs[j];
10784 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010785 }
10786 }
10787
Dianne Hackborn672342c2011-11-29 11:29:02 -080010788 if (outTag != null || outStack != null) {
10789 if (outTag != null) {
10790 appendMemBucket(outTag, totalPss, "total", false);
10791 }
10792 if (outStack != null) {
10793 appendMemBucket(outStack, totalPss, "total", true);
10794 }
10795 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010796 for (int i=0; i<oomMems.size(); i++) {
10797 MemItem miCat = oomMems.get(i);
10798 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10799 continue;
10800 }
10801 if (miCat.id < ProcessList.SERVICE_ADJ
10802 || miCat.id == ProcessList.HOME_APP_ADJ
10803 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010804 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10805 outTag.append(" / ");
10806 }
10807 if (outStack != null) {
10808 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10809 if (firstLine) {
10810 outStack.append(":");
10811 firstLine = false;
10812 }
10813 outStack.append("\n\t at ");
10814 } else {
10815 outStack.append("$");
10816 }
10817 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010818 for (int j=0; j<miCat.subitems.size(); j++) {
10819 MemItem mi = miCat.subitems.get(j);
10820 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010821 if (outTag != null) {
10822 outTag.append(" ");
10823 }
10824 if (outStack != null) {
10825 outStack.append("$");
10826 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010827 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010828 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10829 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10830 }
10831 if (outStack != null) {
10832 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10833 }
10834 }
10835 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10836 outStack.append("(");
10837 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10838 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10839 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10840 outStack.append(":");
10841 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10842 }
10843 }
10844 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010845 }
10846 }
10847 }
10848 }
10849
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010850 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010851 pw.println();
10852 pw.println("Total PSS by process:");
10853 dumpMemItems(pw, " ", procMems, true);
10854 pw.println();
10855 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010856 pw.println("Total PSS by OOM adjustment:");
10857 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010858 if (!oomOnly) {
10859 PrintWriter out = categoryPw != null ? categoryPw : pw;
10860 out.println();
10861 out.println("Total PSS by category:");
10862 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010863 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010864 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010865 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010866 final int[] SINGLE_LONG_FORMAT = new int[] {
10867 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10868 };
10869 long[] longOut = new long[1];
10870 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10871 SINGLE_LONG_FORMAT, null, longOut, null);
10872 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10873 longOut[0] = 0;
10874 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10875 SINGLE_LONG_FORMAT, null, longOut, null);
10876 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10877 longOut[0] = 0;
10878 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10879 SINGLE_LONG_FORMAT, null, longOut, null);
10880 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10881 longOut[0] = 0;
10882 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10883 SINGLE_LONG_FORMAT, null, longOut, null);
10884 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10885 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10886 pw.print(shared); pw.println(" kB");
10887 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10888 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 }
10891
10892 /**
10893 * Searches array of arguments for the specified string
10894 * @param args array of argument strings
10895 * @param value value to search for
10896 * @return true if the value is contained in the array
10897 */
10898 private static boolean scanArgs(String[] args, String value) {
10899 if (args != null) {
10900 for (String arg : args) {
10901 if (value.equals(arg)) {
10902 return true;
10903 }
10904 }
10905 }
10906 return false;
10907 }
10908
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010909 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10910 ContentProviderRecord cpr, boolean always) {
10911 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10912
10913 if (!inLaunching || always) {
10914 synchronized (cpr) {
10915 cpr.launchingApp = null;
10916 cpr.notifyAll();
10917 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010918 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010919 String names[] = cpr.info.authority.split(";");
10920 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010921 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 }
10923 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010924
10925 for (int i=0; i<cpr.connections.size(); i++) {
10926 ContentProviderConnection conn = cpr.connections.get(i);
10927 if (conn.waiting) {
10928 // If this connection is waiting for the provider, then we don't
10929 // need to mess with its process unless we are always removing
10930 // or for some reason the provider is not currently launching.
10931 if (inLaunching && !always) {
10932 continue;
10933 }
10934 }
10935 ProcessRecord capp = conn.client;
10936 conn.dead = true;
10937 if (conn.stableCount > 0) {
10938 if (!capp.persistent && capp.thread != null
10939 && capp.pid != 0
10940 && capp.pid != MY_PID) {
10941 Slog.i(TAG, "Kill " + capp.processName
10942 + " (pid " + capp.pid + "): provider " + cpr.info.name
10943 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010944 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010945 capp.processName, capp.setAdj, "dying provider "
10946 + cpr.name.toShortString());
10947 Process.killProcessQuiet(capp.pid);
10948 }
10949 } else if (capp.thread != null && conn.provider.provider != null) {
10950 try {
10951 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10952 } catch (RemoteException e) {
10953 }
10954 // In the protocol here, we don't expect the client to correctly
10955 // clean up this connection, we'll just remove it.
10956 cpr.connections.remove(i);
10957 conn.client.conProviders.remove(conn);
10958 }
10959 }
10960
10961 if (inLaunching && always) {
10962 mLaunchingProviders.remove(cpr);
10963 }
10964 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 }
10966
10967 /**
10968 * Main code for cleaning up a process when it has gone away. This is
10969 * called both as a result of the process dying, or directly when stopping
10970 * a process when running in single process mode.
10971 */
10972 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010973 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010974 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010975 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 }
10977
Dianne Hackborn36124872009-10-08 16:22:03 -070010978 mProcessesToGc.remove(app);
10979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 // Dismiss any open dialogs.
Christopher Tate58d380d2013-03-19 13:10:03 -070010981 if (app.crashDialog != null && !app.forceCrashReport) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 app.crashDialog.dismiss();
10983 app.crashDialog = null;
10984 }
10985 if (app.anrDialog != null) {
10986 app.anrDialog.dismiss();
10987 app.anrDialog = null;
10988 }
10989 if (app.waitDialog != null) {
10990 app.waitDialog.dismiss();
10991 app.waitDialog = null;
10992 }
10993
10994 app.crashing = false;
10995 app.notResponding = false;
10996
10997 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010998 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010999 app.thread = null;
11000 app.forcingToForeground = null;
11001 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011002 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070011003 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011004 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011005
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011006 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011007
11008 boolean restart = false;
11009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 // Remove published content providers.
11011 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011012 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011014 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011015
11016 final boolean always = app.bad || !allowRestart;
11017 if (removeDyingProviderLocked(app, cpr, always) || always) {
11018 // We left the provider in the launching list, need to
11019 // restart it.
11020 restart = true;
11021 }
11022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070011024 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 app.pubProviders.clear();
11027 }
11028
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011029 // Take care of any launching providers waiting for this process.
11030 if (checkAppInLaunchingProvidersLocked(app, false)) {
11031 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 // Unregister from connected content providers.
11035 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011036 for (int i=0; i<app.conProviders.size(); i++) {
11037 ContentProviderConnection conn = app.conProviders.get(i);
11038 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 }
11040 app.conProviders.clear();
11041 }
11042
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011043 // At this point there may be remaining entries in mLaunchingProviders
11044 // where we were the only one waiting, so they are no longer of use.
11045 // Look for these and clean up if found.
11046 // XXX Commented out for now. Trying to figure out a way to reproduce
11047 // the actual situation to identify what is actually going on.
11048 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011049 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011050 ContentProviderRecord cpr = (ContentProviderRecord)
11051 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011052 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011053 synchronized (cpr) {
11054 cpr.launchingApp = null;
11055 cpr.notifyAll();
11056 }
11057 }
11058 }
11059 }
11060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 skipCurrentReceiverLocked(app);
11062
11063 // Unregister any receivers.
11064 if (app.receivers.size() > 0) {
11065 Iterator<ReceiverList> it = app.receivers.iterator();
11066 while (it.hasNext()) {
11067 removeReceiverLocked(it.next());
11068 }
11069 app.receivers.clear();
11070 }
11071
Christopher Tate181fafa2009-05-14 11:12:14 -070011072 // If the app is undergoing backup, tell the backup manager about it
11073 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070011074 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
11075 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070011076 try {
11077 IBackupManager bm = IBackupManager.Stub.asInterface(
11078 ServiceManager.getService(Context.BACKUP_SERVICE));
11079 bm.agentDisconnected(app.info.packageName);
11080 } catch (RemoteException e) {
11081 // can't happen; backup manager is local
11082 }
11083 }
11084
Dianne Hackborna93c2c12012-05-31 15:29:36 -070011085 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
11086 ProcessChangeItem item = mPendingProcessChanges.get(i);
11087 if (item.pid == app.pid) {
11088 mPendingProcessChanges.remove(i);
11089 mAvailProcessChanges.add(item);
11090 }
11091 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070011092 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070011093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011094 // If the caller is restarting this app, then leave it in its
11095 // current lists and let the caller take care of it.
11096 if (restarting) {
11097 return;
11098 }
11099
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011100 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070011101 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011103 mProcessNames.remove(app.processName, app.uid);
11104 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070011105 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070011106 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
11107 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070011108 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 } else if (!app.removed) {
11111 // This app is persistent, so we need to keep its record around.
11112 // If it is not already on the pending app list, add it there
11113 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 if (mPersistentStartingProcesses.indexOf(app) < 0) {
11115 mPersistentStartingProcesses.add(app);
11116 restart = true;
11117 }
11118 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070011119 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011120 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 mProcessesOnHold.remove(app);
11122
The Android Open Source Project4df24232009-03-05 14:34:35 -080011123 if (app == mHomeProcess) {
11124 mHomeProcess = null;
11125 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070011126 if (app == mPreviousProcess) {
11127 mPreviousProcess = null;
11128 }
11129
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011130 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011131 // We have components that still need to be running in the
11132 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011133 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011134 startProcessLocked(app, "restart", app.processName);
11135 } else if (app.pid > 0 && app.pid != MY_PID) {
11136 // Goodbye!
11137 synchronized (mPidsSelfLocked) {
11138 mPidsSelfLocked.remove(app.pid);
11139 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
11140 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070011141 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 }
11143 }
11144
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011145 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
11146 // Look through the content providers we are waiting to have launched,
11147 // and if any run in this process then either schedule a restart of
11148 // the process or kill the client waiting for it if this process has
11149 // gone bad.
11150 int NL = mLaunchingProviders.size();
11151 boolean restart = false;
11152 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011153 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011154 if (cpr.launchingApp == app) {
11155 if (!alwaysBad && !app.bad) {
11156 restart = true;
11157 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011158 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011159 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011160 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011161 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011162 }
11163 }
11164 }
11165 return restart;
11166 }
11167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 // =========================================================
11169 // SERVICES
11170 // =========================================================
11171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11173 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011174 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011176 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 }
11178 }
11179
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011180 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011181 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011182 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011183 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011184 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011185 }
11186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011188 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011189 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190 // Refuse possible leaked file descriptors
11191 if (service != null && service.hasFileDescriptors() == true) {
11192 throw new IllegalArgumentException("File descriptors passed in Intent");
11193 }
11194
Amith Yamasani742a6712011-05-04 14:49:28 -070011195 if (DEBUG_SERVICE)
11196 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 synchronized(this) {
11198 final int callingPid = Binder.getCallingPid();
11199 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011200 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011202 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011203 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 Binder.restoreCallingIdentity(origId);
11205 return res;
11206 }
11207 }
11208
11209 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070011210 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011212 if (DEBUG_SERVICE)
11213 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011215 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070011216 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 Binder.restoreCallingIdentity(origId);
11218 return res;
11219 }
11220 }
11221
11222 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011223 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011224 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 // Refuse possible leaked file descriptors
11226 if (service != null && service.hasFileDescriptors() == true) {
11227 throw new IllegalArgumentException("File descriptors passed in Intent");
11228 }
11229
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011230 checkValidCaller(Binder.getCallingUid(), userId);
11231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011233 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 }
11236
11237 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011238 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 // Refuse possible leaked file descriptors
11240 if (service != null && service.hasFileDescriptors() == true) {
11241 throw new IllegalArgumentException("File descriptors passed in Intent");
11242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011244 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011246 }
11247
11248 public boolean stopServiceToken(ComponentName className, IBinder token,
11249 int startId) {
11250 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011251 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 }
11254
11255 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011256 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011257 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011258 mServices.setServiceForegroundLocked(className, token, id, notification,
11259 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011260 }
11261 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011262
Dianne Hackborn41203752012-08-31 14:05:51 -070011263 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11264 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011265 final int callingUserId = UserHandle.getUserId(callingUid);
11266 if (callingUserId != userId) {
11267 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11268 if ((requireFull || checkComponentPermission(
11269 android.Manifest.permission.INTERACT_ACROSS_USERS,
11270 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11271 && checkComponentPermission(
11272 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11273 callingPid, callingUid, -1, true)
11274 != PackageManager.PERMISSION_GRANTED) {
11275 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11276 // In this case, they would like to just execute as their
11277 // owner user instead of failing.
11278 userId = callingUserId;
11279 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011280 StringBuilder builder = new StringBuilder(128);
11281 builder.append("Permission Denial: ");
11282 builder.append(name);
11283 if (callerPackage != null) {
11284 builder.append(" from ");
11285 builder.append(callerPackage);
11286 }
11287 builder.append(" asks to run as user ");
11288 builder.append(userId);
11289 builder.append(" but is calling from user ");
11290 builder.append(UserHandle.getUserId(callingUid));
11291 builder.append("; this requires ");
11292 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11293 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011294 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011295 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11296 }
11297 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011298 Slog.w(TAG, msg);
11299 throw new SecurityException(msg);
11300 }
11301 }
11302 }
11303 if (userId == UserHandle.USER_CURRENT
11304 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011305 // Note that we may be accessing this outside of a lock...
11306 // shouldn't be a big deal, if this is being called outside
11307 // of a locked context there is intrinsically a race with
11308 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011309 userId = mCurrentUserId;
11310 }
11311 if (!allowAll && userId < 0) {
11312 throw new IllegalArgumentException(
11313 "Call does not support special user #" + userId);
11314 }
11315 }
11316 return userId;
11317 }
11318
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011319 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11320 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011321 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011322 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011323 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11324 if (ActivityManager.checkUidPermission(
11325 android.Manifest.permission.INTERACT_ACROSS_USERS,
11326 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11327 ComponentName comp = new ComponentName(aInfo.packageName, className);
11328 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11329 + " requests FLAG_SINGLE_USER, but app does not hold "
11330 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11331 Slog.w(TAG, msg);
11332 throw new SecurityException(msg);
11333 }
11334 result = true;
11335 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011336 } else if (componentProcessName == aInfo.packageName) {
11337 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11338 } else if ("system".equals(componentProcessName)) {
11339 result = true;
11340 }
11341 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011342 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11343 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011344 }
11345 return result;
11346 }
11347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011348 public int bindService(IApplicationThread caller, IBinder token,
11349 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011350 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011351 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 // Refuse possible leaked file descriptors
11353 if (service != null && service.hasFileDescriptors() == true) {
11354 throw new IllegalArgumentException("File descriptors passed in Intent");
11355 }
11356
11357 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011358 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11359 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011360 }
11361 }
11362
11363 public boolean unbindService(IServiceConnection connection) {
11364 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011365 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 }
11368
11369 public void publishService(IBinder token, Intent intent, IBinder service) {
11370 // Refuse possible leaked file descriptors
11371 if (intent != null && intent.hasFileDescriptors() == true) {
11372 throw new IllegalArgumentException("File descriptors passed in Intent");
11373 }
11374
11375 synchronized(this) {
11376 if (!(token instanceof ServiceRecord)) {
11377 throw new IllegalArgumentException("Invalid service token");
11378 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011379 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011380 }
11381 }
11382
11383 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11384 // Refuse possible leaked file descriptors
11385 if (intent != null && intent.hasFileDescriptors() == true) {
11386 throw new IllegalArgumentException("File descriptors passed in Intent");
11387 }
11388
11389 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011390 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011391 }
11392 }
11393
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011394 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 synchronized(this) {
11396 if (!(token instanceof ServiceRecord)) {
11397 throw new IllegalArgumentException("Invalid service token");
11398 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011399 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 }
11402
11403 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011404 // BACKUP AND RESTORE
11405 // =========================================================
11406
11407 // Cause the target app to be launched if necessary and its backup agent
11408 // instantiated. The backup agent will invoke backupAgentCreated() on the
11409 // activity manager to announce its creation.
11410 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011411 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11412 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011413
11414 synchronized(this) {
11415 // !!! TODO: currently no check here that we're already bound
11416 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11417 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11418 synchronized (stats) {
11419 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11420 }
11421
Dianne Hackborne7f97212011-02-24 14:40:20 -080011422 // Backup agent is now in use, its package can't be stopped.
11423 try {
11424 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011425 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011426 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011427 } catch (IllegalArgumentException e) {
11428 Slog.w(TAG, "Failed trying to unstop package "
11429 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011430 }
11431
Christopher Tate181fafa2009-05-14 11:12:14 -070011432 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011433 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11434 ? new ComponentName(app.packageName, app.backupAgentName)
11435 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011436 // startProcessLocked() returns existing proc's record if it's already running
11437 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011438 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011439 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011440 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011441 return false;
11442 }
11443
11444 r.app = proc;
11445 mBackupTarget = r;
11446 mBackupAppName = app.packageName;
11447
Christopher Tate6fa95972009-06-05 18:43:55 -070011448 // Try not to kill the process during backup
11449 updateOomAdjLocked(proc);
11450
Christopher Tate181fafa2009-05-14 11:12:14 -070011451 // If the process is already attached, schedule the creation of the backup agent now.
11452 // If it is not yet live, this will be done when it attaches to the framework.
11453 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011454 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011455 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011456 proc.thread.scheduleCreateBackupAgent(app,
11457 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011458 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011459 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011460 }
11461 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011462 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011463 }
11464 // Invariants: at this point, the target app process exists and the application
11465 // is either already running or in the process of coming up. mBackupTarget and
11466 // mBackupAppName describe the app, so that when it binds back to the AM we
11467 // know that it's scheduled for a backup-agent operation.
11468 }
11469
11470 return true;
11471 }
11472
Christopher Tate346acb12012-10-15 19:20:25 -070011473 @Override
11474 public void clearPendingBackup() {
11475 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11476 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11477
11478 synchronized (this) {
11479 mBackupTarget = null;
11480 mBackupAppName = null;
11481 }
11482 }
11483
Christopher Tate181fafa2009-05-14 11:12:14 -070011484 // A backup agent has just come up
11485 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011486 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011487 + " = " + agent);
11488
11489 synchronized(this) {
11490 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011491 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011492 return;
11493 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011494 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011495
Dianne Hackborn06740692010-09-22 22:46:21 -070011496 long oldIdent = Binder.clearCallingIdentity();
11497 try {
11498 IBackupManager bm = IBackupManager.Stub.asInterface(
11499 ServiceManager.getService(Context.BACKUP_SERVICE));
11500 bm.agentConnected(agentPackageName, agent);
11501 } catch (RemoteException e) {
11502 // can't happen; the backup manager service is local
11503 } catch (Exception e) {
11504 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11505 e.printStackTrace();
11506 } finally {
11507 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011508 }
11509 }
11510
11511 // done with this agent
11512 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011513 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011514 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011515 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011516 return;
11517 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011518
11519 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011520 try {
11521 if (mBackupAppName == null) {
11522 Slog.w(TAG, "Unbinding backup agent with no active backup");
11523 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011524 }
Christopher Tate346acb12012-10-15 19:20:25 -070011525
11526 if (!mBackupAppName.equals(appInfo.packageName)) {
11527 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11528 return;
11529 }
11530
11531 // Not backing this app up any more; reset its OOM adjustment
11532 final ProcessRecord proc = mBackupTarget.app;
11533 updateOomAdjLocked(proc);
11534
11535 // If the app crashed during backup, 'thread' will be null here
11536 if (proc.thread != null) {
11537 try {
11538 proc.thread.scheduleDestroyBackupAgent(appInfo,
11539 compatibilityInfoForPackageLocked(appInfo));
11540 } catch (Exception e) {
11541 Slog.e(TAG, "Exception when unbinding backup agent:");
11542 e.printStackTrace();
11543 }
11544 }
11545 } finally {
11546 mBackupTarget = null;
11547 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011548 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011549 }
11550 }
11551 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011552 // BROADCASTS
11553 // =========================================================
11554
Josh Bartel7f208742010-02-25 11:01:44 -060011555 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011556 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011558 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11559 if (stickies == null) {
11560 return cur;
11561 }
11562 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 if (list == null) {
11564 return cur;
11565 }
11566 int N = list.size();
11567 for (int i=0; i<N; i++) {
11568 Intent intent = list.get(i);
11569 if (filter.match(resolver, intent, true, TAG) >= 0) {
11570 if (cur == null) {
11571 cur = new ArrayList<Intent>();
11572 }
11573 cur.add(intent);
11574 }
11575 }
11576 return cur;
11577 }
11578
Christopher Tatef46723b2012-01-26 14:19:24 -080011579 boolean isPendingBroadcastProcessLocked(int pid) {
11580 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11581 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583
Christopher Tatef46723b2012-01-26 14:19:24 -080011584 void skipPendingBroadcastLocked(int pid) {
11585 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11586 for (BroadcastQueue queue : mBroadcastQueues) {
11587 queue.skipPendingBroadcastLocked(pid);
11588 }
11589 }
11590
11591 // The app just attached; send any pending broadcasts that it should receive
11592 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11593 boolean didSomething = false;
11594 for (BroadcastQueue queue : mBroadcastQueues) {
11595 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011597 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 }
11599
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011600 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011601 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011602 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011603 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011604 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 synchronized(this) {
11606 ProcessRecord callerApp = null;
11607 if (caller != null) {
11608 callerApp = getRecordForAppLocked(caller);
11609 if (callerApp == null) {
11610 throw new SecurityException(
11611 "Unable to find app for caller " + caller
11612 + " (pid=" + Binder.getCallingPid()
11613 + ") when registering receiver " + receiver);
11614 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011615 if (callerApp.info.uid != Process.SYSTEM_UID &&
11616 !callerApp.pkgList.contains(callerPackage)) {
11617 throw new SecurityException("Given caller package " + callerPackage
11618 + " is not running in process " + callerApp);
11619 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011620 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011621 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011622 } else {
11623 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011624 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011625 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011626 }
11627
Dianne Hackborn139748f2012-09-24 11:36:57 -070011628 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011629 true, true, "registerReceiver", callerPackage);
11630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011631 List allSticky = null;
11632
11633 // Look for any matching sticky broadcasts...
11634 Iterator actions = filter.actionsIterator();
11635 if (actions != null) {
11636 while (actions.hasNext()) {
11637 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011638 allSticky = getStickiesLocked(action, filter, allSticky,
11639 UserHandle.USER_ALL);
11640 allSticky = getStickiesLocked(action, filter, allSticky,
11641 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 }
11643 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011644 allSticky = getStickiesLocked(null, filter, allSticky,
11645 UserHandle.USER_ALL);
11646 allSticky = getStickiesLocked(null, filter, allSticky,
11647 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 }
11649
11650 // The first sticky in the list is returned directly back to
11651 // the client.
11652 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11653
Joe Onorato8a9b2202010-02-26 18:56:32 -080011654 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 + ": " + sticky);
11656
11657 if (receiver == null) {
11658 return sticky;
11659 }
11660
11661 ReceiverList rl
11662 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11663 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011664 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11665 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 if (rl.app != null) {
11667 rl.app.receivers.add(rl);
11668 } else {
11669 try {
11670 receiver.asBinder().linkToDeath(rl, 0);
11671 } catch (RemoteException e) {
11672 return sticky;
11673 }
11674 rl.linkedToDeath = true;
11675 }
11676 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011677 } else if (rl.uid != callingUid) {
11678 throw new IllegalArgumentException(
11679 "Receiver requested to register for uid " + callingUid
11680 + " was previously registered for uid " + rl.uid);
11681 } else if (rl.pid != callingPid) {
11682 throw new IllegalArgumentException(
11683 "Receiver requested to register for pid " + callingPid
11684 + " was previously registered for pid " + rl.pid);
11685 } else if (rl.userId != userId) {
11686 throw new IllegalArgumentException(
11687 "Receiver requested to register for user " + userId
11688 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011690 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011691 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 rl.add(bf);
11693 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011694 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011695 }
11696 mReceiverResolver.addFilter(bf);
11697
11698 // Enqueue broadcasts for all existing stickies that match
11699 // this filter.
11700 if (allSticky != null) {
11701 ArrayList receivers = new ArrayList();
11702 receivers.add(bf);
11703
11704 int N = allSticky.size();
11705 for (int i=0; i<N; i++) {
11706 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011707 BroadcastQueue queue = broadcastQueueForIntent(intent);
11708 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011709 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11710 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011711 queue.enqueueParallelBroadcastLocked(r);
11712 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 }
11714 }
11715
11716 return sticky;
11717 }
11718 }
11719
11720 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011721 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722
Christopher Tatef46723b2012-01-26 14:19:24 -080011723 final long origId = Binder.clearCallingIdentity();
11724 try {
11725 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726
Christopher Tatef46723b2012-01-26 14:19:24 -080011727 synchronized(this) {
11728 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011730 if (rl != null) {
11731 if (rl.curBroadcast != null) {
11732 BroadcastRecord r = rl.curBroadcast;
11733 final boolean doNext = finishReceiverLocked(
11734 receiver.asBinder(), r.resultCode, r.resultData,
11735 r.resultExtras, r.resultAbort, true);
11736 if (doNext) {
11737 doTrim = true;
11738 r.queue.processNextBroadcast(false);
11739 }
11740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741
Christopher Tatef46723b2012-01-26 14:19:24 -080011742 if (rl.app != null) {
11743 rl.app.receivers.remove(rl);
11744 }
11745 removeReceiverLocked(rl);
11746 if (rl.linkedToDeath) {
11747 rl.linkedToDeath = false;
11748 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011750 }
11751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752
Christopher Tatef46723b2012-01-26 14:19:24 -080011753 // If we actually concluded any broadcasts, we might now be able
11754 // to trim the recipients' apps from our working set
11755 if (doTrim) {
11756 trimApplications();
11757 return;
11758 }
11759
11760 } finally {
11761 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 }
11764
11765 void removeReceiverLocked(ReceiverList rl) {
11766 mRegisteredReceivers.remove(rl.receiver.asBinder());
11767 int N = rl.size();
11768 for (int i=0; i<N; i++) {
11769 mReceiverResolver.removeFilter(rl.get(i));
11770 }
11771 }
11772
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011773 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011774 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11775 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011776 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011777 try {
11778 r.thread.dispatchPackageBroadcast(cmd, packages);
11779 } catch (RemoteException ex) {
11780 }
11781 }
11782 }
11783 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011784
11785 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11786 int[] users) {
11787 List<ResolveInfo> receivers = null;
11788 try {
11789 HashSet<ComponentName> singleUserReceivers = null;
11790 boolean scannedFirstReceivers = false;
11791 for (int user : users) {
11792 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11793 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011794 if (user != 0 && newReceivers != null) {
11795 // If this is not the primary user, we need to check for
11796 // any receivers that should be filtered out.
11797 for (int i=0; i<newReceivers.size(); i++) {
11798 ResolveInfo ri = newReceivers.get(i);
11799 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11800 newReceivers.remove(i);
11801 i--;
11802 }
11803 }
11804 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011805 if (newReceivers != null && newReceivers.size() == 0) {
11806 newReceivers = null;
11807 }
11808 if (receivers == null) {
11809 receivers = newReceivers;
11810 } else if (newReceivers != null) {
11811 // We need to concatenate the additional receivers
11812 // found with what we have do far. This would be easy,
11813 // but we also need to de-dup any receivers that are
11814 // singleUser.
11815 if (!scannedFirstReceivers) {
11816 // Collect any single user receivers we had already retrieved.
11817 scannedFirstReceivers = true;
11818 for (int i=0; i<receivers.size(); i++) {
11819 ResolveInfo ri = receivers.get(i);
11820 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11821 ComponentName cn = new ComponentName(
11822 ri.activityInfo.packageName, ri.activityInfo.name);
11823 if (singleUserReceivers == null) {
11824 singleUserReceivers = new HashSet<ComponentName>();
11825 }
11826 singleUserReceivers.add(cn);
11827 }
11828 }
11829 }
11830 // Add the new results to the existing results, tracking
11831 // and de-dupping single user receivers.
11832 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011833 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011834 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11835 ComponentName cn = new ComponentName(
11836 ri.activityInfo.packageName, ri.activityInfo.name);
11837 if (singleUserReceivers == null) {
11838 singleUserReceivers = new HashSet<ComponentName>();
11839 }
11840 if (!singleUserReceivers.contains(cn)) {
11841 singleUserReceivers.add(cn);
11842 receivers.add(ri);
11843 }
11844 } else {
11845 receivers.add(ri);
11846 }
11847 }
11848 }
11849 }
11850 } catch (RemoteException ex) {
11851 // pm is in same process, this will never happen.
11852 }
11853 return receivers;
11854 }
11855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 private final int broadcastIntentLocked(ProcessRecord callerApp,
11857 String callerPackage, Intent intent, String resolvedType,
11858 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011859 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011860 boolean ordered, boolean sticky, int callingPid, int callingUid,
11861 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 intent = new Intent(intent);
11863
Dianne Hackborne7f97212011-02-24 14:40:20 -080011864 // By default broadcasts do not go to stopped apps.
11865 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11866
Joe Onorato8a9b2202010-02-26 18:56:32 -080011867 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011869 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011870 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011871 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011872 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011873
Dianne Hackborn139748f2012-09-24 11:36:57 -070011874 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011875 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011876
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011877 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011878 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011879 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011880 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11881 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11882 Slog.w(TAG, "Skipping broadcast of " + intent
11883 + ": user " + userId + " is stopped");
11884 return ActivityManager.BROADCAST_SUCCESS;
11885 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011886 }
11887
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011888 /*
11889 * Prevent non-system code (defined here to be non-persistent
11890 * processes) from sending protected broadcasts.
11891 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011892 int callingAppId = UserHandle.getAppId(callingUid);
11893 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11894 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011895 callingUid == 0) {
11896 // Always okay.
11897 } else if (callerApp == null || !callerApp.persistent) {
11898 try {
11899 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11900 intent.getAction())) {
11901 String msg = "Permission Denial: not allowed to send broadcast "
11902 + intent.getAction() + " from pid="
11903 + callingPid + ", uid=" + callingUid;
11904 Slog.w(TAG, msg);
11905 throw new SecurityException(msg);
Dianne Hackborna40cfeb2013-03-25 17:49:36 -070011906 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) {
11907 // Special case for compatibility: we don't want apps to send this,
11908 // but historically it has not been protected and apps may be using it
11909 // to poke their own app widget. So, instead of making it protected,
11910 // just limit it to the caller.
11911 if (callerApp == null) {
11912 String msg = "Permission Denial: not allowed to send broadcast "
11913 + intent.getAction() + " from unknown caller.";
11914 Slog.w(TAG, msg);
11915 throw new SecurityException(msg);
11916 } else if (intent.getComponent() != null) {
11917 // They are good enough to send to an explicit component... verify
11918 // it is being sent to the calling app.
11919 if (!intent.getComponent().getPackageName().equals(
11920 callerApp.info.packageName)) {
11921 String msg = "Permission Denial: not allowed to send broadcast "
11922 + intent.getAction() + " to "
11923 + intent.getComponent().getPackageName() + " from "
11924 + callerApp.info.packageName;
11925 Slog.w(TAG, msg);
11926 throw new SecurityException(msg);
11927 }
11928 } else {
11929 // Limit broadcast to their own package.
11930 intent.setPackage(callerApp.info.packageName);
11931 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011932 }
11933 } catch (RemoteException e) {
11934 Slog.w(TAG, "Remote exception", e);
11935 return ActivityManager.BROADCAST_SUCCESS;
11936 }
11937 }
11938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 // Handle special intents: if this broadcast is from the package
11940 // manager about a package being removed, we need to remove all of
11941 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011942 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011944 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11945 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011946 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 || uidRemoved) {
11948 if (checkComponentPermission(
11949 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011950 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 == PackageManager.PERMISSION_GRANTED) {
11952 if (uidRemoved) {
11953 final Bundle intentExtras = intent.getExtras();
11954 final int uid = intentExtras != null
11955 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11956 if (uid >= 0) {
11957 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11958 synchronized (bs) {
11959 bs.removeUidStatsLocked(uid);
11960 }
Dianne Hackborn514074f2013-02-11 10:52:46 -080011961 mAppOpsService.uidRemoved(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 }
11963 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011964 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011965 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011966 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011967 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11968 if (list != null && (list.length > 0)) {
11969 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011970 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011971 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011972 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011973 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011974 }
11975 } else {
11976 Uri data = intent.getData();
11977 String ssp;
11978 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11979 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11980 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011981 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11982 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011983 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011984 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011985 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011986 new String[] {ssp}, userId);
Dianne Hackborn514074f2013-02-11 10:52:46 -080011987 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
11988 mAppOpsService.packageRemoved(
11989 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
11990 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 }
11993 }
11994 }
11995 } else {
11996 String msg = "Permission Denial: " + intent.getAction()
11997 + " broadcast from " + callerPackage + " (pid=" + callingPid
11998 + ", uid=" + callingUid + ")"
11999 + " requires "
12000 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012001 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 throw new SecurityException(msg);
12003 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012004
12005 // Special case for adding a package: by default turn on compatibility
12006 // mode.
12007 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012008 Uri data = intent.getData();
12009 String ssp;
12010 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12011 mCompatModePackages.handlePackageAddedLocked(ssp,
12012 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 }
12015
12016 /*
12017 * If this is the time zone changed action, queue up a message that will reset the timezone
12018 * of all currently running processes. This message will get queued up before the broadcast
12019 * happens.
12020 */
12021 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12022 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12023 }
12024
Robert Greenwalt03595d02010-11-02 14:08:23 -070012025 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12026 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12027 }
12028
Robert Greenwalt434203a2010-10-11 16:00:27 -070012029 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12030 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12031 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12032 }
12033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 // Add to the sticky list if requested.
12035 if (sticky) {
12036 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12037 callingPid, callingUid)
12038 != PackageManager.PERMISSION_GRANTED) {
12039 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12040 + callingPid + ", uid=" + callingUid
12041 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012042 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 throw new SecurityException(msg);
12044 }
12045 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012046 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012048 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 }
12050 if (intent.getComponent() != null) {
12051 throw new SecurityException(
12052 "Sticky broadcasts can't target a specific component");
12053 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012054 // We use userId directly here, since the "all" target is maintained
12055 // as a separate set of sticky broadcasts.
12056 if (userId != UserHandle.USER_ALL) {
12057 // But first, if this is not a broadcast to all users, then
12058 // make sure it doesn't conflict with an existing broadcast to
12059 // all users.
12060 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
12061 UserHandle.USER_ALL);
12062 if (stickies != null) {
12063 ArrayList<Intent> list = stickies.get(intent.getAction());
12064 if (list != null) {
12065 int N = list.size();
12066 int i;
12067 for (i=0; i<N; i++) {
12068 if (intent.filterEquals(list.get(i))) {
12069 throw new IllegalArgumentException(
12070 "Sticky broadcast " + intent + " for user "
12071 + userId + " conflicts with existing global broadcast");
12072 }
12073 }
12074 }
12075 }
12076 }
12077 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12078 if (stickies == null) {
12079 stickies = new HashMap<String, ArrayList<Intent>>();
12080 mStickyBroadcasts.put(userId, stickies);
12081 }
12082 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 if (list == null) {
12084 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012085 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 }
12087 int N = list.size();
12088 int i;
12089 for (i=0; i<N; i++) {
12090 if (intent.filterEquals(list.get(i))) {
12091 // This sticky already exists, replace it.
12092 list.set(i, new Intent(intent));
12093 break;
12094 }
12095 }
12096 if (i >= N) {
12097 list.add(new Intent(intent));
12098 }
12099 }
12100
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012101 int[] users;
12102 if (userId == UserHandle.USER_ALL) {
12103 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070012104 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012105 } else {
12106 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070012107 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012108 }
12109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012110 // Figure out who all will receive this broadcast.
12111 List receivers = null;
12112 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012113 // Need to resolve the intent to interested receivers...
12114 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12115 == 0) {
12116 receivers = collectReceiverComponents(intent, resolvedType, users);
12117 }
12118 if (intent.getComponent() == null) {
12119 registeredReceivers = mReceiverResolver.queryIntent(intent,
12120 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012121 }
12122
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012123 final boolean replacePending =
12124 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12125
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012127 + " replacePending=" + replacePending);
12128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012129 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12130 if (!ordered && NR > 0) {
12131 // If we are not serializing this broadcast, then send the
12132 // registered receivers separately so they don't wait for the
12133 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012134 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12135 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012136 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012137 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012138 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012140 TAG, "Enqueueing parallel broadcast " + r);
12141 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012142 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012143 queue.enqueueParallelBroadcastLocked(r);
12144 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146 registeredReceivers = null;
12147 NR = 0;
12148 }
12149
12150 // Merge into one list.
12151 int ir = 0;
12152 if (receivers != null) {
12153 // A special case for PACKAGE_ADDED: do not allow the package
12154 // being added to see this broadcast. This prevents them from
12155 // using this as a back door to get run as soon as they are
12156 // installed. Maybe in the future we want to have a special install
12157 // broadcast or such for apps, but we'd like to deliberately make
12158 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012159 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012160 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12161 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12162 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012163 Uri data = intent.getData();
12164 if (data != null) {
12165 String pkgName = data.getSchemeSpecificPart();
12166 if (pkgName != null) {
12167 skipPackages = new String[] { pkgName };
12168 }
12169 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012170 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012171 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012172 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012173 if (skipPackages != null && (skipPackages.length > 0)) {
12174 for (String skipPackage : skipPackages) {
12175 if (skipPackage != null) {
12176 int NT = receivers.size();
12177 for (int it=0; it<NT; it++) {
12178 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12179 if (curt.activityInfo.packageName.equals(skipPackage)) {
12180 receivers.remove(it);
12181 it--;
12182 NT--;
12183 }
12184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185 }
12186 }
12187 }
12188
12189 int NT = receivers != null ? receivers.size() : 0;
12190 int it = 0;
12191 ResolveInfo curt = null;
12192 BroadcastFilter curr = null;
12193 while (it < NT && ir < NR) {
12194 if (curt == null) {
12195 curt = (ResolveInfo)receivers.get(it);
12196 }
12197 if (curr == null) {
12198 curr = registeredReceivers.get(ir);
12199 }
12200 if (curr.getPriority() >= curt.priority) {
12201 // Insert this broadcast record into the final list.
12202 receivers.add(it, curr);
12203 ir++;
12204 curr = null;
12205 it++;
12206 NT++;
12207 } else {
12208 // Skip to the next ResolveInfo in the final list.
12209 it++;
12210 curt = null;
12211 }
12212 }
12213 }
12214 while (ir < NR) {
12215 if (receivers == null) {
12216 receivers = new ArrayList();
12217 }
12218 receivers.add(registeredReceivers.get(ir));
12219 ir++;
12220 }
12221
12222 if ((receivers != null && receivers.size() > 0)
12223 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012224 BroadcastQueue queue = broadcastQueueForIntent(intent);
12225 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012226 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012227 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012228 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012229 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012231 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 if (DEBUG_BROADCAST) {
12233 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012234 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012236 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012237 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012238 queue.enqueueOrderedBroadcastLocked(r);
12239 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241 }
12242
Dianne Hackborna4972e92012-03-14 10:38:05 -070012243 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 }
12245
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012246 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012247 // Refuse possible leaked file descriptors
12248 if (intent != null && intent.hasFileDescriptors() == true) {
12249 throw new IllegalArgumentException("File descriptors passed in Intent");
12250 }
12251
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012252 int flags = intent.getFlags();
12253
12254 if (!mProcessesReady) {
12255 // if the caller really truly claims to know what they're doing, go
12256 // ahead and allow the broadcast without launching any receivers
12257 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12258 intent = new Intent(intent);
12259 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12260 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12261 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12262 + " before boot completion");
12263 throw new IllegalStateException("Cannot broadcast before boot completed");
12264 }
12265 }
12266
12267 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12268 throw new IllegalArgumentException(
12269 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12270 }
12271
12272 return intent;
12273 }
12274
12275 public final int broadcastIntent(IApplicationThread caller,
12276 Intent intent, String resolvedType, IIntentReceiver resultTo,
12277 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012278 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012279 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012281 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12284 final int callingPid = Binder.getCallingPid();
12285 final int callingUid = Binder.getCallingUid();
12286 final long origId = Binder.clearCallingIdentity();
12287 int res = broadcastIntentLocked(callerApp,
12288 callerApp != null ? callerApp.info.packageName : null,
12289 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012290 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070012291 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012292 Binder.restoreCallingIdentity(origId);
12293 return res;
12294 }
12295 }
12296
12297 int broadcastIntentInPackage(String packageName, int uid,
12298 Intent intent, String resolvedType, IIntentReceiver resultTo,
12299 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012300 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012302 intent = verifyBroadcastLocked(intent);
12303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012304 final long origId = Binder.clearCallingIdentity();
12305 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12306 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012307 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012308 Binder.restoreCallingIdentity(origId);
12309 return res;
12310 }
12311 }
12312
Amith Yamasani742a6712011-05-04 14:49:28 -070012313 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 // Refuse possible leaked file descriptors
12315 if (intent != null && intent.hasFileDescriptors() == true) {
12316 throw new IllegalArgumentException("File descriptors passed in Intent");
12317 }
12318
Dianne Hackborn139748f2012-09-24 11:36:57 -070012319 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012320 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012322 synchronized(this) {
12323 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12324 != PackageManager.PERMISSION_GRANTED) {
12325 String msg = "Permission Denial: unbroadcastIntent() from pid="
12326 + Binder.getCallingPid()
12327 + ", uid=" + Binder.getCallingUid()
12328 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012329 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 throw new SecurityException(msg);
12331 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012332 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12333 if (stickies != null) {
12334 ArrayList<Intent> list = stickies.get(intent.getAction());
12335 if (list != null) {
12336 int N = list.size();
12337 int i;
12338 for (i=0; i<N; i++) {
12339 if (intent.filterEquals(list.get(i))) {
12340 list.remove(i);
12341 break;
12342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012343 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012344 if (list.size() <= 0) {
12345 stickies.remove(intent.getAction());
12346 }
12347 }
12348 if (stickies.size() <= 0) {
12349 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 }
12351 }
12352 }
12353 }
12354
12355 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12356 String resultData, Bundle resultExtras, boolean resultAbort,
12357 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012358 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12359 if (r == null) {
12360 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 return false;
12362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012363
Christopher Tatef46723b2012-01-26 14:19:24 -080012364 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12365 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012366 }
12367
12368 public void finishReceiver(IBinder who, int resultCode, String resultData,
12369 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012370 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371
12372 // Refuse possible leaked file descriptors
12373 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12374 throw new IllegalArgumentException("File descriptors passed in Bundle");
12375 }
12376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012378 try {
12379 boolean doNext = false;
12380 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381
Christopher Tatef46723b2012-01-26 14:19:24 -080012382 synchronized(this) {
12383 r = broadcastRecordForReceiverLocked(who);
12384 if (r != null) {
12385 doNext = r.queue.finishReceiverLocked(r, resultCode,
12386 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012389
Christopher Tatef46723b2012-01-26 14:19:24 -080012390 if (doNext) {
12391 r.queue.processNextBroadcast(false);
12392 }
12393 trimApplications();
12394 } finally {
12395 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 // =========================================================
12400 // INSTRUMENTATION
12401 // =========================================================
12402
12403 public boolean startInstrumentation(ComponentName className,
12404 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012405 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
12406 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012407 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012408 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012409 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012410 // Refuse possible leaked file descriptors
12411 if (arguments != null && arguments.hasFileDescriptors()) {
12412 throw new IllegalArgumentException("File descriptors passed in Bundle");
12413 }
12414
12415 synchronized(this) {
12416 InstrumentationInfo ii = null;
12417 ApplicationInfo ai = null;
12418 try {
12419 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012420 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012421 ai = AppGlobals.getPackageManager().getApplicationInfo(
12422 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012424 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012425 }
12426 if (ii == null) {
12427 reportStartInstrumentationFailure(watcher, className,
12428 "Unable to find instrumentation info for: " + className);
12429 return false;
12430 }
12431 if (ai == null) {
12432 reportStartInstrumentationFailure(watcher, className,
12433 "Unable to find instrumentation target package: " + ii.targetPackage);
12434 return false;
12435 }
12436
12437 int match = mContext.getPackageManager().checkSignatures(
12438 ii.targetPackage, ii.packageName);
12439 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12440 String msg = "Permission Denial: starting instrumentation "
12441 + className + " from pid="
12442 + Binder.getCallingPid()
12443 + ", uid=" + Binder.getCallingPid()
12444 + " not allowed because package " + ii.packageName
12445 + " does not have a signature matching the target "
12446 + ii.targetPackage;
12447 reportStartInstrumentationFailure(watcher, className, msg);
12448 throw new SecurityException(msg);
12449 }
12450
12451 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012452 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012453 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012454 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012456 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457 app.instrumentationProfileFile = profileFile;
12458 app.instrumentationArguments = arguments;
12459 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012460 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 app.instrumentationResultClass = className;
12462 Binder.restoreCallingIdentity(origId);
12463 }
12464
12465 return true;
12466 }
12467
12468 /**
12469 * Report errors that occur while attempting to start Instrumentation. Always writes the
12470 * error to the logs, but if somebody is watching, send the report there too. This enables
12471 * the "am" command to report errors with more information.
12472 *
12473 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12474 * @param cn The component name of the instrumentation.
12475 * @param report The error report.
12476 */
12477 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12478 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012479 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012480 try {
12481 if (watcher != null) {
12482 Bundle results = new Bundle();
12483 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12484 results.putString("Error", report);
12485 watcher.instrumentationStatus(cn, -1, results);
12486 }
12487 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012488 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 }
12490 }
12491
12492 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12493 if (app.instrumentationWatcher != null) {
12494 try {
12495 // NOTE: IInstrumentationWatcher *must* be oneway here
12496 app.instrumentationWatcher.instrumentationFinished(
12497 app.instrumentationClass,
12498 resultCode,
12499 results);
12500 } catch (RemoteException e) {
12501 }
12502 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012503 if (app.instrumentationUiAutomationConnection != null) {
12504 try {
12505 app.instrumentationUiAutomationConnection.shutdown();
12506 } catch (RemoteException re) {
12507 /* ignore */
12508 }
Adam Momtaz8f6f1f42013-04-10 12:42:58 -070012509 // Only a UiAutomation can set this flag and now that
12510 // it is finished we make sure it is reset to its default.
12511 mUserIsMonkey = false;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012514 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012516 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012517 app.instrumentationProfileFile = null;
12518 app.instrumentationArguments = null;
12519
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012520 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 }
12522
12523 public void finishInstrumentation(IApplicationThread target,
12524 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012525 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012526 // Refuse possible leaked file descriptors
12527 if (results != null && results.hasFileDescriptors()) {
12528 throw new IllegalArgumentException("File descriptors passed in Intent");
12529 }
12530
12531 synchronized(this) {
12532 ProcessRecord app = getRecordForAppLocked(target);
12533 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012534 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 return;
12536 }
12537 final long origId = Binder.clearCallingIdentity();
12538 finishInstrumentationLocked(app, resultCode, results);
12539 Binder.restoreCallingIdentity(origId);
12540 }
12541 }
12542
12543 // =========================================================
12544 // CONFIGURATION
12545 // =========================================================
12546
12547 public ConfigurationInfo getDeviceConfigurationInfo() {
12548 ConfigurationInfo config = new ConfigurationInfo();
12549 synchronized (this) {
12550 config.reqTouchScreen = mConfiguration.touchscreen;
12551 config.reqKeyboardType = mConfiguration.keyboard;
12552 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012553 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12554 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012555 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12556 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012557 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12558 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012559 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12560 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012561 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012562 }
12563 return config;
12564 }
12565
12566 public Configuration getConfiguration() {
12567 Configuration ci;
12568 synchronized(this) {
12569 ci = new Configuration(mConfiguration);
12570 }
12571 return ci;
12572 }
12573
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012574 public void updatePersistentConfiguration(Configuration values) {
12575 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12576 "updateConfiguration()");
12577 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12578 "updateConfiguration()");
12579 if (values == null) {
12580 throw new NullPointerException("Configuration must not be null");
12581 }
12582
12583 synchronized(this) {
12584 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012585 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012586 Binder.restoreCallingIdentity(origId);
12587 }
12588 }
12589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012590 public void updateConfiguration(Configuration values) {
12591 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12592 "updateConfiguration()");
12593
12594 synchronized(this) {
12595 if (values == null && mWindowManager != null) {
12596 // sentinel: fetch the current configuration from the window manager
12597 values = mWindowManager.computeNewConfiguration();
12598 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012599
12600 if (mWindowManager != null) {
12601 mProcessList.applyDisplaySize(mWindowManager);
12602 }
12603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012604 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012605 if (values != null) {
12606 Settings.System.clearConfiguration(values);
12607 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012608 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 Binder.restoreCallingIdentity(origId);
12610 }
12611 }
12612
12613 /**
12614 * Do either or both things: (1) change the current configuration, and (2)
12615 * make sure the given activity is running with the (now) current
12616 * configuration. Returns true if the activity has been left running, or
12617 * false if <var>starting</var> is being destroyed to match the new
12618 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012619 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012620 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012621 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012622 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012623 // do nothing if we are headless
12624 if (mHeadless) return true;
12625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012626 int changes = 0;
12627
12628 boolean kept = true;
12629
12630 if (values != null) {
12631 Configuration newConfig = new Configuration(mConfiguration);
12632 changes = newConfig.updateFrom(values);
12633 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012634 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012635 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012636 }
12637
Doug Zongker2bec3d42009-12-04 12:52:44 -080012638 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012639
Dianne Hackborn813075a62011-11-14 17:45:19 -080012640 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 saveLocaleLocked(values.locale,
12642 !values.locale.equals(mConfiguration.locale),
12643 values.userSetLocale);
12644 }
12645
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012646 mConfigurationSeq++;
12647 if (mConfigurationSeq <= 0) {
12648 mConfigurationSeq = 1;
12649 }
12650 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012652 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012653
12654 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012655
12656 // TODO: If our config changes, should we auto dismiss any currently
12657 // showing dialogs?
12658 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012659
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012660 AttributeCache ac = AttributeCache.instance();
12661 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012662 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012665 // Make sure all resources in our process are updated
12666 // right now, so that anyone who is going to retrieve
12667 // resource values after we return will be sure to get
12668 // the new ones. This is especially important during
12669 // boot, where the first config change needs to guarantee
12670 // all resources have that config before following boot
12671 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012672 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012673
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012674 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012675 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012676 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012677 mHandler.sendMessage(msg);
12678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012680 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12681 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012682 try {
12683 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012684 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012685 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012686 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012687 }
12688 } catch (Exception e) {
12689 }
12690 }
12691 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012692 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012693 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12694 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012696 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12697 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012698 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012699 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12700 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12701 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012702 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12703 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012705 }
12706 }
12707
12708 if (changes != 0 && starting == null) {
12709 // If the configuration changed, and the caller is not already
12710 // in the process of starting an activity, then find the top
12711 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012712 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012713 }
12714
12715 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012716 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012717 // And we need to make sure at this point that all other activities
12718 // are made visible with the correct configuration.
12719 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012720 }
12721
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012722 if (values != null && mWindowManager != null) {
12723 mWindowManager.setNewConfiguration(mConfiguration);
12724 }
12725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726 return kept;
12727 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012728
12729 /**
12730 * Decide based on the configuration whether we should shouw the ANR,
12731 * crash, etc dialogs. The idea is that if there is no affordnace to
12732 * press the on-screen buttons, we shouldn't show the dialog.
12733 *
12734 * A thought: SystemUI might also want to get told about this, the Power
12735 * dialog / global actions also might want different behaviors.
12736 */
12737 private static final boolean shouldShowDialogs(Configuration config) {
12738 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12739 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012741
12742 /**
12743 * Save the locale. You must be inside a synchronized (this) block.
12744 */
12745 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12746 if(isDiff) {
12747 SystemProperties.set("user.language", l.getLanguage());
12748 SystemProperties.set("user.region", l.getCountry());
12749 }
12750
12751 if(isPersist) {
12752 SystemProperties.set("persist.sys.language", l.getLanguage());
12753 SystemProperties.set("persist.sys.country", l.getCountry());
12754 SystemProperties.set("persist.sys.localevar", l.getVariant());
12755 }
12756 }
12757
Adam Powelldd8fab22012-03-22 17:47:27 -070012758 @Override
12759 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12760 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012761 return srec != null && srec.task.affinity != null &&
12762 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012763 }
12764
12765 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12766 Intent resultData) {
Craig Mautner2ad92072013-02-25 16:19:24 -080012767 ComponentName dest = destIntent.getComponent();
Adam Powelldd8fab22012-03-22 17:47:27 -070012768
12769 synchronized (this) {
12770 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012771 if (srec == null) {
12772 return false;
12773 }
Craig Mautner2ad92072013-02-25 16:19:24 -080012774 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12775 final int start = history.indexOf(srec);
12776 if (start < 0) {
12777 // Current activity is not in history stack; do nothing.
12778 return false;
12779 }
12780 int finishTo = start - 1;
12781 ActivityRecord parent = null;
12782 boolean foundParentInTask = false;
12783 if (dest != null) {
12784 TaskRecord tr = srec.task;
12785 for (int i = start - 1; i >= 0; i--) {
12786 ActivityRecord r = history.get(i);
12787 if (tr != r.task) {
12788 // Couldn't find parent in the same task; stop at the one above this.
12789 // (Root of current task; in-app "home" behavior)
12790 // Always at least finish the current activity.
12791 finishTo = Math.min(start - 1, i + 1);
12792 parent = history.get(finishTo);
12793 break;
12794 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12795 r.info.name.equals(dest.getClassName())) {
12796 finishTo = i;
12797 parent = r;
12798 foundParentInTask = true;
12799 break;
12800 }
12801 }
12802 }
12803
12804 if (mController != null) {
12805 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12806 if (next != null) {
12807 // ask watcher if this is allowed
12808 boolean resumeOK = true;
12809 try {
12810 resumeOK = mController.activityResuming(next.packageName);
12811 } catch (RemoteException e) {
12812 mController = null;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070012813 Watchdog.getInstance().setActivityController(null);
Craig Mautner2ad92072013-02-25 16:19:24 -080012814 }
12815
12816 if (!resumeOK) {
12817 return false;
12818 }
12819 }
12820 }
12821 final long origId = Binder.clearCallingIdentity();
12822 for (int i = start; i > finishTo; i--) {
12823 ActivityRecord r = history.get(i);
12824 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12825 "navigate-up", true);
12826 // Only return the supplied result for the first activity finished
12827 resultCode = Activity.RESULT_CANCELED;
12828 resultData = null;
12829 }
12830
12831 if (parent != null && foundParentInTask) {
12832 final int parentLaunchMode = parent.info.launchMode;
12833 final int destIntentFlags = destIntent.getFlags();
12834 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12835 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12836 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12837 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
12838 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
12839 } else {
12840 try {
12841 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
12842 destIntent.getComponent(), 0, srec.userId);
12843 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12844 null, aInfo, parent.appToken, null,
12845 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
12846 0, null, true, null);
12847 foundParentInTask = res == ActivityManager.START_SUCCESS;
12848 } catch (RemoteException e) {
12849 foundParentInTask = false;
12850 }
12851 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12852 resultData, "navigate-up", true);
12853 }
12854 }
12855 Binder.restoreCallingIdentity(origId);
12856 return foundParentInTask;
Adam Powelldd8fab22012-03-22 17:47:27 -070012857 }
12858 }
12859
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012860 public int getLaunchedFromUid(IBinder activityToken) {
12861 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12862 if (srec == null) {
12863 return -1;
12864 }
12865 return srec.launchedFromUid;
12866 }
12867
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012868 public String getLaunchedFromPackage(IBinder activityToken) {
12869 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12870 if (srec == null) {
12871 return null;
12872 }
12873 return srec.launchedFromPackage;
12874 }
12875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 // =========================================================
12877 // LIFETIME MANAGEMENT
12878 // =========================================================
12879
Christopher Tatef46723b2012-01-26 14:19:24 -080012880 // Returns which broadcast queue the app is the current [or imminent] receiver
12881 // on, or 'null' if the app is not an active broadcast recipient.
12882 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12883 BroadcastRecord r = app.curReceiver;
12884 if (r != null) {
12885 return r.queue;
12886 }
12887
12888 // It's not the current receiver, but it might be starting up to become one
12889 synchronized (this) {
12890 for (BroadcastQueue queue : mBroadcastQueues) {
12891 r = queue.mPendingBroadcast;
12892 if (r != null && r.curApp == app) {
12893 // found it; report which queue it's in
12894 return queue;
12895 }
12896 }
12897 }
12898
12899 return null;
12900 }
12901
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012902 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012903 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012905 // This adjustment has already been computed. If we are calling
12906 // from the top, we may have already computed our adjustment with
12907 // an earlier hidden adjustment that isn't really for us... if
12908 // so, use the new hidden adjustment.
12909 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012910 if (app.hasActivities) {
12911 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12912 } else if (app.hasClientActivities) {
12913 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12914 } else {
12915 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12916 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012917 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012918 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 }
12920
12921 if (app.thread == null) {
12922 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012923 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012924 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 }
12926
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012927 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12928 app.adjSource = null;
12929 app.adjTarget = null;
12930 app.empty = false;
12931 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012932 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012933
12934 final int activitiesSize = app.activities.size();
12935
Dianne Hackborn7d608422011-08-07 16:24:18 -070012936 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012937 // The max adjustment doesn't allow this app to be anything
12938 // below foreground, so it is not worth doing work for it.
12939 app.adjType = "fixed";
12940 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012941 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012942 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012943 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012944 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012945 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012946 // System process can do UI, and when they do we want to have
12947 // them trim their memory after the user leaves the UI. To
12948 // facilitate this, here we need to determine whether or not it
12949 // is currently showing UI.
12950 app.systemNoUi = true;
12951 if (app == TOP_APP) {
12952 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012953 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012954 } else if (activitiesSize > 0) {
12955 for (int j = 0; j < activitiesSize; j++) {
12956 final ActivityRecord r = app.activities.get(j);
12957 if (r.visible) {
12958 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012959 }
12960 if (r.app == app) {
12961 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012962 }
12963 }
12964 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012965 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012966 }
12967
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012968 app.keeping = false;
12969 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012970 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971
The Android Open Source Project4df24232009-03-05 14:34:35 -080012972 // Determine the importance of the process, starting with most
12973 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012974 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012975 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012976 boolean foregroundActivities = false;
12977 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012978 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012979 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012981 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012982 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012983 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012984 foregroundActivities = true;
12985 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012986 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012987 } else if (app.instrumentationClass != null) {
12988 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012989 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012990 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012991 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012992 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012993 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012995 // counts as being in the foreground for OOM killer purposes.
12996 // It's placed in a sched group based on the nature of the
12997 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012998 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012999 schedGroup = (queue == mFgBroadcastQueue)
13000 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013001 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013002 } else if (app.executingServices.size() > 0) {
13003 // An app that is currently executing a service callback also
13004 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013005 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013006 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013007 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013008 } else {
13009 // Assume process is hidden (has activities); we will correct
13010 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013011 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013012 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013013 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013014 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013016
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013017 boolean hasStoppingActivities = false;
13018
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013019 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013020 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013021 for (int j = 0; j < activitiesSize; j++) {
13022 final ActivityRecord r = app.activities.get(j);
13023 if (r.visible) {
13024 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013025 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13026 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013027 app.adjType = "visible";
13028 }
13029 schedGroup = Process.THREAD_GROUP_DEFAULT;
13030 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013031 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013032 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013033 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013034 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013035 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13036 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013037 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013038 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013039 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013040 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013041 } else if (r.state == ActivityState.STOPPING) {
13042 // We will apply the actual adjustment later, because
13043 // we want to allow this process to immediately go through
13044 // any memory trimming that is in effect.
13045 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013046 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013047 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013048 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013049 if (r.app == app) {
13050 app.hasActivities = true;
13051 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013052 }
13053 }
13054
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013055 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013056 if (app.hasClientActivities) {
13057 adj = clientHiddenAdj;
13058 app.adjType = "bg-client-act";
13059 } else {
13060 // Whoops, this process is completely empty as far as we know
13061 // at this point.
13062 adj = emptyAdj;
13063 app.empty = true;
13064 app.adjType = "bg-empty";
13065 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013066 }
13067
Dianne Hackborn7d608422011-08-07 16:24:18 -070013068 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013069 if (app.foregroundServices) {
13070 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013071 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013072 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013073 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013074 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013075 } else if (app.forcingToForeground != null) {
13076 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013077 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013078 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013079 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013080 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013081 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013082 }
13083 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013084
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013085 if (app.foregroundServices) {
13086 interesting = true;
13087 }
13088
Dianne Hackborn7d608422011-08-07 16:24:18 -070013089 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013090 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013091 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013092 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013093 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013094 app.adjType = "heavy";
13095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013096
Dianne Hackborn7d608422011-08-07 16:24:18 -070013097 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013098 // This process is hosting what we currently consider to be the
13099 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013100 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013101 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013102 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013103 app.adjType = "home";
13104 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013105
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013106 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13107 && app.activities.size() > 0) {
13108 // This was the previous process that showed UI to the user.
13109 // We want to try to keep it around more aggressively, to give
13110 // a good experience around switching between two apps.
13111 adj = ProcessList.PREVIOUS_APP_ADJ;
13112 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13113 app.hidden = false;
13114 app.adjType = "previous";
13115 }
13116
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013117 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13118 + " reason=" + app.adjType);
13119
The Android Open Source Project4df24232009-03-05 14:34:35 -080013120 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013121 // there are applications dependent on our services or providers, but
13122 // this gives us a baseline and makes sure we don't get into an
13123 // infinite recursion.
13124 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013125 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013126
Christopher Tate6fa95972009-06-05 18:43:55 -070013127 if (mBackupTarget != null && app == mBackupTarget.app) {
13128 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013129 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013130 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013131 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013132 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013133 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013134 }
13135 }
13136
Dianne Hackborn7d608422011-08-07 16:24:18 -070013137 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013138 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013139 final long now = SystemClock.uptimeMillis();
13140 // This process is more important if the top activity is
13141 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013142 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013143 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013144 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013146 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013147 // If this process has shown some UI, let it immediately
13148 // go to the LRU list because it may be pretty heavy with
13149 // UI stuff. We'll tag it with a label just to help
13150 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013151 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013152 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013153 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013154 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013155 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013156 // This service has seen some activity within
13157 // recent memory, so we will keep its process ahead
13158 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013159 if (adj > ProcessList.SERVICE_ADJ) {
13160 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013161 app.adjType = "started-services";
13162 app.hidden = false;
13163 }
13164 }
13165 // If we have let the service slide into the background
13166 // state, still have some text describing what it is doing
13167 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013168 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013169 app.adjType = "started-bg-services";
13170 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013171 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013172 // Don't kill this process because it is doing work; it
13173 // has said it is doing work.
13174 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013176 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013177 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013178 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013180 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013181 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013183 // XXX should compute this based on the max of
13184 // all connected clients.
13185 ConnectionRecord cr = clist.get(i);
13186 if (cr.binding.client == app) {
13187 // Binding to ourself is not interesting.
13188 continue;
13189 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013190 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013191 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013192 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013193 int myHiddenAdj = hiddenAdj;
13194 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013195 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013196 myHiddenAdj = client.hiddenAdj;
13197 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013198 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013199 }
13200 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013201 int myClientHiddenAdj = clientHiddenAdj;
13202 if (myClientHiddenAdj > client.clientHiddenAdj) {
13203 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
13204 myClientHiddenAdj = client.clientHiddenAdj;
13205 } else {
13206 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
13207 }
13208 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013209 int myEmptyAdj = emptyAdj;
13210 if (myEmptyAdj > client.emptyAdj) {
13211 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
13212 myEmptyAdj = client.emptyAdj;
13213 } else {
13214 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
13215 }
13216 }
13217 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013218 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013219 String adjType = null;
13220 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13221 // Not doing bind OOM management, so treat
13222 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013223 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013224 // If this process has shown some UI, let it immediately
13225 // go to the LRU list because it may be pretty heavy with
13226 // UI stuff. We'll tag it with a label just to help
13227 // debug and understand what is going on.
13228 if (adj > clientAdj) {
13229 adjType = "bound-bg-ui-services";
13230 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013231 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013232 clientAdj = adj;
13233 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013234 if (now >= (s.lastActivity
13235 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013236 // This service has not seen activity within
13237 // recent memory, so allow it to drop to the
13238 // LRU list if there is no other reason to keep
13239 // it around. We'll also tag it with a label just
13240 // to help debug and undertand what is going on.
13241 if (adj > clientAdj) {
13242 adjType = "bound-bg-services";
13243 }
13244 clientAdj = adj;
13245 }
13246 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013247 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13248 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
13249 // If this connection is keeping the service
13250 // created, then we want to try to better follow
13251 // its memory management semantics for activities.
13252 // That is, if it is sitting in the background
13253 // LRU list as a hidden process (with activities),
13254 // we don't want the service it is connected to
13255 // to go into the empty LRU and quickly get killed,
13256 // because I'll we'll do is just end up restarting
13257 // the service.
13258 app.hasClientActivities |= client.hasActivities;
13259 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013260 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013261 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013262 // If this process has recently shown UI, and
13263 // the process that is binding to it is less
13264 // important than being visible, then we don't
13265 // care about the binding as much as we care
13266 // about letting this process get into the LRU
13267 // list to be killed and restarted if needed for
13268 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013269 if (app.hasShownUi && app != mHomeProcess
13270 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013271 adjType = "bound-bg-ui-services";
13272 } else {
13273 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13274 |Context.BIND_IMPORTANT)) != 0) {
13275 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013276 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13277 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13278 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13279 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13280 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013281 adj = clientAdj;
13282 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013283 app.pendingUiClean = true;
13284 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13285 adj = ProcessList.VISIBLE_APP_ADJ;
13286 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013287 }
13288 if (!client.hidden) {
13289 app.hidden = false;
13290 }
13291 if (client.keeping) {
13292 app.keeping = true;
13293 }
13294 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013295 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013296 }
13297 if (adjType != null) {
13298 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013299 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13300 .REASON_SERVICE_IN_USE;
13301 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013302 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013303 app.adjTarget = s.name;
13304 }
13305 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13306 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13307 schedGroup = Process.THREAD_GROUP_DEFAULT;
13308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013309 }
13310 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013311 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013312 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013313 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013314 (a.visible || a.state == ActivityState.RESUMED
13315 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013316 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013317 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13318 schedGroup = Process.THREAD_GROUP_DEFAULT;
13319 }
13320 app.hidden = false;
13321 app.adjType = "service";
13322 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13323 .REASON_SERVICE_IN_USE;
13324 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013325 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013326 app.adjTarget = s.name;
13327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
13330 }
13331 }
13332 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013333
Dianne Hackborn287952c2010-09-22 22:34:31 -070013334 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013335 // would like to avoid killing it unless it would prevent the current
13336 // application from running. By default we put the process in
13337 // with the rest of the background processes; as we scan through
13338 // its services we may bump it up from there.
13339 if (adj > hiddenAdj) {
13340 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013341 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013342 app.adjType = "bg-services";
13343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 }
13345
Dianne Hackborn7d608422011-08-07 16:24:18 -070013346 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013347 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013348 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013349 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013350 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013351 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013352 for (int i = cpr.connections.size()-1;
13353 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13354 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13355 i--) {
13356 ContentProviderConnection conn = cpr.connections.get(i);
13357 ProcessRecord client = conn.client;
13358 if (client == app) {
13359 // Being our own client is not interesting.
13360 continue;
13361 }
13362 int myHiddenAdj = hiddenAdj;
13363 if (myHiddenAdj > client.hiddenAdj) {
13364 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13365 myHiddenAdj = client.hiddenAdj;
13366 } else {
13367 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013368 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013369 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013370 int myClientHiddenAdj = clientHiddenAdj;
13371 if (myClientHiddenAdj > client.clientHiddenAdj) {
13372 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13373 myClientHiddenAdj = client.clientHiddenAdj;
13374 } else {
13375 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13376 }
13377 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013378 int myEmptyAdj = emptyAdj;
13379 if (myEmptyAdj > client.emptyAdj) {
13380 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13381 myEmptyAdj = client.emptyAdj;
13382 } else {
13383 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13384 }
13385 }
13386 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013387 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013388 if (adj > clientAdj) {
13389 if (app.hasShownUi && app != mHomeProcess
13390 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13391 app.adjType = "bg-ui-provider";
13392 } else {
13393 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13394 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13395 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013396 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013397 if (!client.hidden) {
13398 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013399 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013400 if (client.keeping) {
13401 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013402 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013403 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13404 .REASON_PROVIDER_IN_USE;
13405 app.adjSource = client;
13406 app.adjSourceOom = clientAdj;
13407 app.adjTarget = cpr.name;
13408 }
13409 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13410 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013411 }
13412 }
13413 // If the provider has external (non-framework) process
13414 // dependencies, ensure that its adjustment is at least
13415 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013416 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013417 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13418 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013419 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013420 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013421 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013422 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013423 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013424 }
13425 }
13426 }
13427 }
13428
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013429 if (adj == ProcessList.SERVICE_ADJ) {
13430 if (doingAll) {
13431 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13432 mNewNumServiceProcs++;
13433 }
13434 if (app.serviceb) {
13435 adj = ProcessList.SERVICE_B_ADJ;
13436 }
13437 } else {
13438 app.serviceb = false;
13439 }
13440
13441 app.nonStoppingAdj = adj;
13442
13443 if (hasStoppingActivities) {
13444 // Only upgrade adjustment.
13445 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13446 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13447 app.adjType = "stopping";
13448 }
13449 }
13450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013451 app.curRawAdj = adj;
13452
Joe Onorato8a9b2202010-02-26 18:56:32 -080013453 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013454 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13455 if (adj > app.maxAdj) {
13456 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013457 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013458 schedGroup = Process.THREAD_GROUP_DEFAULT;
13459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013460 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013461 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013462 app.keeping = true;
13463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013465 if (app.hasAboveClient) {
13466 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13467 // then we need to drop its adjustment to be lower than the service's
13468 // in order to honor the request. We want to drop it by one adjustment
13469 // level... but there is special meaning applied to various levels so
13470 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013471 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013472 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013473 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13474 adj = ProcessList.VISIBLE_APP_ADJ;
13475 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13476 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13477 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13478 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013479 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013480 adj++;
13481 }
13482 }
13483
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013484 int importance = app.memImportance;
13485 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13486 app.curAdj = adj;
13487 app.curSchedGroup = schedGroup;
13488 if (!interesting) {
13489 // For this reporting, if there is not something explicitly
13490 // interesting in this process then we will push it to the
13491 // background importance.
13492 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13493 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13494 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13495 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13496 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13497 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13498 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13499 } else if (adj >= ProcessList.SERVICE_ADJ) {
13500 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13501 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13502 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13503 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13504 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13505 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13506 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13507 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13508 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13509 } else {
13510 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13511 }
13512 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013513
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013514 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13515 if (foregroundActivities != app.foregroundActivities) {
13516 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13517 }
13518 if (changes != 0) {
13519 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13520 app.memImportance = importance;
13521 app.foregroundActivities = foregroundActivities;
13522 int i = mPendingProcessChanges.size()-1;
13523 ProcessChangeItem item = null;
13524 while (i >= 0) {
13525 item = mPendingProcessChanges.get(i);
13526 if (item.pid == app.pid) {
13527 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13528 break;
13529 }
13530 i--;
13531 }
13532 if (i < 0) {
13533 // No existing item in pending changes; need a new one.
13534 final int NA = mAvailProcessChanges.size();
13535 if (NA > 0) {
13536 item = mAvailProcessChanges.remove(NA-1);
13537 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13538 } else {
13539 item = new ProcessChangeItem();
13540 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13541 }
13542 item.changes = 0;
13543 item.pid = app.pid;
13544 item.uid = app.info.uid;
13545 if (mPendingProcessChanges.size() == 0) {
13546 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13547 "*** Enqueueing dispatch processes changed!");
13548 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13549 }
13550 mPendingProcessChanges.add(item);
13551 }
13552 item.changes |= changes;
13553 item.importance = importance;
13554 item.foregroundActivities = foregroundActivities;
13555 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13556 + Integer.toHexString(System.identityHashCode(item))
13557 + " " + app.toShortString() + ": changes=" + item.changes
13558 + " importance=" + item.importance
13559 + " foreground=" + item.foregroundActivities
13560 + " type=" + app.adjType + " source=" + app.adjSource
13561 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013562 }
13563
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013564 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013565 }
13566
13567 /**
13568 * Ask a given process to GC right now.
13569 */
13570 final void performAppGcLocked(ProcessRecord app) {
13571 try {
13572 app.lastRequestedGc = SystemClock.uptimeMillis();
13573 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013574 if (app.reportLowMemory) {
13575 app.reportLowMemory = false;
13576 app.thread.scheduleLowMemory();
13577 } else {
13578 app.thread.processInBackground();
13579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013580 }
13581 } catch (Exception e) {
13582 // whatever.
13583 }
13584 }
13585
13586 /**
13587 * Returns true if things are idle enough to perform GCs.
13588 */
Josh Bartel7f208742010-02-25 11:01:44 -060013589 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013590 boolean processingBroadcasts = false;
13591 for (BroadcastQueue q : mBroadcastQueues) {
13592 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13593 processingBroadcasts = true;
13594 }
13595 }
13596 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013597 && (mSleeping || (mMainStack.mResumedActivity != null &&
13598 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013599 }
13600
13601 /**
13602 * Perform GCs on all processes that are waiting for it, but only
13603 * if things are idle.
13604 */
13605 final void performAppGcsLocked() {
13606 final int N = mProcessesToGc.size();
13607 if (N <= 0) {
13608 return;
13609 }
Josh Bartel7f208742010-02-25 11:01:44 -060013610 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013611 while (mProcessesToGc.size() > 0) {
13612 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013613 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013614 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13615 <= SystemClock.uptimeMillis()) {
13616 // To avoid spamming the system, we will GC processes one
13617 // at a time, waiting a few seconds between each.
13618 performAppGcLocked(proc);
13619 scheduleAppGcsLocked();
13620 return;
13621 } else {
13622 // It hasn't been long enough since we last GCed this
13623 // process... put it in the list to wait for its time.
13624 addProcessToGcListLocked(proc);
13625 break;
13626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013627 }
13628 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013629
13630 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 }
13632 }
13633
13634 /**
13635 * If all looks good, perform GCs on all processes waiting for them.
13636 */
13637 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013638 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 performAppGcsLocked();
13640 return;
13641 }
13642 // Still not idle, wait some more.
13643 scheduleAppGcsLocked();
13644 }
13645
13646 /**
13647 * Schedule the execution of all pending app GCs.
13648 */
13649 final void scheduleAppGcsLocked() {
13650 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013651
13652 if (mProcessesToGc.size() > 0) {
13653 // Schedule a GC for the time to the next process.
13654 ProcessRecord proc = mProcessesToGc.get(0);
13655 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13656
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013657 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013658 long now = SystemClock.uptimeMillis();
13659 if (when < (now+GC_TIMEOUT)) {
13660 when = now + GC_TIMEOUT;
13661 }
13662 mHandler.sendMessageAtTime(msg, when);
13663 }
13664 }
13665
13666 /**
13667 * Add a process to the array of processes waiting to be GCed. Keeps the
13668 * list in sorted order by the last GC time. The process can't already be
13669 * on the list.
13670 */
13671 final void addProcessToGcListLocked(ProcessRecord proc) {
13672 boolean added = false;
13673 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13674 if (mProcessesToGc.get(i).lastRequestedGc <
13675 proc.lastRequestedGc) {
13676 added = true;
13677 mProcessesToGc.add(i+1, proc);
13678 break;
13679 }
13680 }
13681 if (!added) {
13682 mProcessesToGc.add(0, proc);
13683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013684 }
13685
13686 /**
13687 * Set up to ask a process to GC itself. This will either do it
13688 * immediately, or put it on the list of processes to gc the next
13689 * time things are idle.
13690 */
13691 final void scheduleAppGcLocked(ProcessRecord app) {
13692 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013693 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013694 return;
13695 }
13696 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013697 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013698 scheduleAppGcsLocked();
13699 }
13700 }
13701
Dianne Hackborn287952c2010-09-22 22:34:31 -070013702 final void checkExcessivePowerUsageLocked(boolean doKills) {
13703 updateCpuStatsNow();
13704
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013705 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013706 boolean doWakeKills = doKills;
13707 boolean doCpuKills = doKills;
13708 if (mLastPowerCheckRealtime == 0) {
13709 doWakeKills = false;
13710 }
13711 if (mLastPowerCheckUptime == 0) {
13712 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013713 }
13714 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013715 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013716 }
13717 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013718 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13719 final long curUptime = SystemClock.uptimeMillis();
13720 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13721 mLastPowerCheckRealtime = curRealtime;
13722 mLastPowerCheckUptime = curUptime;
13723 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13724 doWakeKills = false;
13725 }
13726 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13727 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013728 }
13729 int i = mLruProcesses.size();
13730 while (i > 0) {
13731 i--;
13732 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013733 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013734 long wtime;
13735 synchronized (stats) {
13736 wtime = stats.getProcessWakeTime(app.info.uid,
13737 app.pid, curRealtime);
13738 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013739 long wtimeUsed = wtime - app.lastWakeTime;
13740 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13741 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013742 StringBuilder sb = new StringBuilder(128);
13743 sb.append("Wake for ");
13744 app.toShortString(sb);
13745 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013746 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013747 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013748 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013749 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013750 sb.append((wtimeUsed*100)/realtimeSince);
13751 sb.append("%)");
13752 Slog.i(TAG, sb.toString());
13753 sb.setLength(0);
13754 sb.append("CPU for ");
13755 app.toShortString(sb);
13756 sb.append(": over ");
13757 TimeUtils.formatDuration(uptimeSince, sb);
13758 sb.append(" used ");
13759 TimeUtils.formatDuration(cputimeUsed, sb);
13760 sb.append(" (");
13761 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013762 sb.append("%)");
13763 Slog.i(TAG, sb.toString());
13764 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013765 // If a process has held a wake lock for more
13766 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013767 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013768 if (doWakeKills && realtimeSince > 0
13769 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13770 synchronized (stats) {
13771 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13772 realtimeSince, wtimeUsed);
13773 }
13774 Slog.w(TAG, "Excessive wake lock in " + app.processName
13775 + " (pid " + app.pid + "): held " + wtimeUsed
13776 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013777 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013778 app.processName, app.setAdj, "excessive wake lock");
13779 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013780 } else if (doCpuKills && uptimeSince > 0
13781 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13782 synchronized (stats) {
13783 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13784 uptimeSince, cputimeUsed);
13785 }
13786 Slog.w(TAG, "Excessive CPU in " + app.processName
13787 + " (pid " + app.pid + "): used " + cputimeUsed
13788 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013789 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013790 app.processName, app.setAdj, "excessive cpu");
13791 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013792 } else {
13793 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013794 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013795 }
13796 }
13797 }
13798 }
13799
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013800 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013801 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013802 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013803 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013804 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013805
13806 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013807 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013808 }
13809
Dianne Hackborn287952c2010-09-22 22:34:31 -070013810 final boolean wasKeeping = app.keeping;
13811
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013812 boolean success = true;
13813
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013814 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013815
Jeff Brown10e89712011-07-08 18:52:57 -070013816 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013817 if (wasKeeping && !app.keeping) {
13818 // This app is no longer something we want to keep. Note
13819 // its current wake lock time to later know to kill it if
13820 // it is not behaving well.
13821 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13822 synchronized (stats) {
13823 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13824 app.pid, SystemClock.elapsedRealtime());
13825 }
13826 app.lastCpuTime = app.curCpuTime;
13827 }
13828
13829 app.setRawAdj = app.curRawAdj;
13830 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013832 if (app.curAdj != app.setAdj) {
13833 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013834 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013835 TAG, "Set " + app.pid + " " + app.processName +
13836 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013837 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013838 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013839 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013840 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013841 }
13842 }
13843 if (app.setSchedGroup != app.curSchedGroup) {
13844 app.setSchedGroup = app.curSchedGroup;
13845 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13846 "Setting process group of " + app.processName
13847 + " to " + app.curSchedGroup);
13848 if (app.waitingToKill != null &&
13849 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13850 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013851 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013852 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013853 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013854 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013855 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013856 } else {
13857 if (true) {
13858 long oldId = Binder.clearCallingIdentity();
13859 try {
13860 Process.setProcessGroup(app.pid, app.curSchedGroup);
13861 } catch (Exception e) {
13862 Slog.w(TAG, "Failed setting process group of " + app.pid
13863 + " to " + app.curSchedGroup);
13864 e.printStackTrace();
13865 } finally {
13866 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013867 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013868 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013869 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013870 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013871 app.thread.setSchedulingGroup(app.curSchedGroup);
13872 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013873 }
13874 }
13875 }
13876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013878 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013879 }
13880
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013881 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013882 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013884 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013885 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013886 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887 }
13888 }
13889 return resumedActivity;
13890 }
13891
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013892 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013893 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13895 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013896 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13897 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013898
13899 mAdjSeq++;
13900
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013901 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13902 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013903 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13904 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013905 if (nowHidden != wasHidden) {
13906 // Changed to/from hidden state, so apps after it in the LRU
13907 // list may also be changed.
13908 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013910 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 }
13912
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013913 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013914 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013916 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013917
13918 if (false) {
13919 RuntimeException e = new RuntimeException();
13920 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013921 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013922 }
13923
13924 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013925 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013927 final int emptyProcessLimit;
13928 final int hiddenProcessLimit;
13929 if (mProcessLimit <= 0) {
13930 emptyProcessLimit = hiddenProcessLimit = 0;
13931 } else if (mProcessLimit == 1) {
13932 emptyProcessLimit = 1;
13933 hiddenProcessLimit = 0;
13934 } else {
13935 emptyProcessLimit = (mProcessLimit*2)/3;
13936 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13937 }
13938
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013939 // Let's determine how many processes we have running vs.
13940 // how many slots we have for background processes; we may want
13941 // to put multiple processes in a slot of there are enough of
13942 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013943 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13944 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013945 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13946 if (numEmptyProcs > hiddenProcessLimit) {
13947 // If there are more empty processes than our limit on hidden
13948 // processes, then use the hidden process limit for the factor.
13949 // This ensures that the really old empty processes get pushed
13950 // down to the bottom, so if we are running low on memory we will
13951 // have a better chance at keeping around more hidden processes
13952 // instead of a gazillion empty processes.
13953 numEmptyProcs = hiddenProcessLimit;
13954 }
13955 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013956 if (emptyFactor < 1) emptyFactor = 1;
13957 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13958 if (hiddenFactor < 1) hiddenFactor = 1;
13959 int stepHidden = 0;
13960 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013961 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013962 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013963 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013964
13965 mNumNonHiddenProcs = 0;
13966 mNumHiddenProcs = 0;
13967
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013968 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013970 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013971 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013972 int nextHiddenAdj = curHiddenAdj+1;
13973 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13974 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013975 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013976 while (i > 0) {
13977 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013978 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013979 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013980 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013981 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013982 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13983 // This process was assigned as a hidden process... step the
13984 // hidden level.
13985 mNumHiddenProcs++;
13986 if (curHiddenAdj != nextHiddenAdj) {
13987 stepHidden++;
13988 if (stepHidden >= hiddenFactor) {
13989 stepHidden = 0;
13990 curHiddenAdj = nextHiddenAdj;
13991 nextHiddenAdj += 2;
13992 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13993 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13994 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013995 if (curClientHiddenAdj <= curHiddenAdj) {
13996 curClientHiddenAdj = curHiddenAdj + 1;
13997 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13998 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13999 }
14000 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014001 }
14002 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014003 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014004 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014005 Slog.i(TAG, "No longer want " + app.processName
14006 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014007 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014008 app.processName, app.setAdj, "too many background");
14009 app.killedBackground = true;
14010 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014011 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014012 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
14013 // This process has a client that has activities. We will have
14014 // given it the current hidden adj; here we will just leave it
14015 // without stepping the hidden adj.
14016 curClientHiddenAdj++;
14017 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
14018 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
14019 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014020 } else {
14021 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
14022 // This process was assigned as an empty process... step the
14023 // empty level.
14024 if (curEmptyAdj != nextEmptyAdj) {
14025 stepEmpty++;
14026 if (stepEmpty >= emptyFactor) {
14027 stepEmpty = 0;
14028 curEmptyAdj = nextEmptyAdj;
14029 nextEmptyAdj += 2;
14030 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
14031 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
14032 }
14033 }
14034 }
14035 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14036 mNumNonHiddenProcs++;
14037 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014038 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14039 && !app.hasClientActivities) {
14040 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
14041 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014042 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014043 + " (pid " + app.pid + "): empty for "
14044 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
14045 / 1000) + "s");
14046 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
14047 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014048 app.killedBackground = true;
14049 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014050 } else {
14051 numEmpty++;
14052 if (numEmpty > emptyProcessLimit) {
14053 Slog.i(TAG, "No longer want " + app.processName
14054 + " (pid " + app.pid + "): empty #" + numEmpty);
14055 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
14056 app.processName, app.setAdj, "too many background");
14057 app.killedBackground = true;
14058 Process.killProcessQuiet(app.pid);
14059 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014060 }
14061 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070014062 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014063 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014064 // If this is an isolated process, and there are no
14065 // services running in it, then the process is no longer
14066 // needed. We agressively kill these because we can by
14067 // definition not re-use the same process again, and it is
14068 // good to avoid having whatever code was running in them
14069 // left sitting around after no longer needed.
14070 Slog.i(TAG, "Isolated process " + app.processName
14071 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014072 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014073 app.processName, app.setAdj, "isolated not needed");
14074 app.killedBackground = true;
14075 Process.killProcessQuiet(app.pid);
14076 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014077 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14078 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14079 && !app.killedBackground) {
14080 numTrimming++;
14081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 }
14083 }
14084
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014085 mNumServiceProcs = mNewNumServiceProcs;
14086
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014087 // Now determine the memory trimming level of background processes.
14088 // Unfortunately we need to start at the back of the list to do this
14089 // properly. We only do this if the number of background apps we
14090 // are managing to keep around is less than half the maximum we desire;
14091 // if we are keeping a good number around, we'll let them use whatever
14092 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014093 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
14094 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014095 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014096 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014097 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014098 int minFactor = 2;
14099 if (mHomeProcess != null) minFactor++;
14100 if (mPreviousProcess != null) minFactor++;
14101 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070014102 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014103 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014104 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014105 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014106 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014107 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14108 } else {
14109 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14110 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014111 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014112 for (i=0; i<N; i++) {
14113 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014114 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14115 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014116 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014117 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14118 try {
14119 app.thread.scheduleTrimMemory(curLevel);
14120 } catch (RemoteException e) {
14121 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014122 if (false) {
14123 // For now we won't do this; our memory trimming seems
14124 // to be good enough at this point that destroying
14125 // activities causes more harm than good.
14126 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14127 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014128 // Need to do this on its own message because the stack may not
14129 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014130 // For these apps we will also finish their activities
14131 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014132 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014133 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014134 }
14135 }
14136 app.trimMemoryLevel = curLevel;
14137 step++;
14138 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014139 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014140 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014141 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14142 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014143 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014144 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14145 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014146 break;
14147 }
14148 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014149 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014150 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014151 && app.thread != null) {
14152 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014153 app.thread.scheduleTrimMemory(
14154 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014155 } catch (RemoteException e) {
14156 }
14157 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014158 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014159 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014160 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014161 && app.pendingUiClean) {
14162 // If this application is now in the background and it
14163 // had done UI, then give it the special trim level to
14164 // have it free UI resources.
14165 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14166 if (app.trimMemoryLevel < level && app.thread != null) {
14167 try {
14168 app.thread.scheduleTrimMemory(level);
14169 } catch (RemoteException e) {
14170 }
14171 }
14172 app.pendingUiClean = false;
14173 }
14174 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014175 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014176 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014177 } catch (RemoteException e) {
14178 }
14179 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014180 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014181 }
14182 }
14183 } else {
14184 final int N = mLruProcesses.size();
14185 for (i=0; i<N; i++) {
14186 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014187 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014188 && app.pendingUiClean) {
14189 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14190 && app.thread != null) {
14191 try {
14192 app.thread.scheduleTrimMemory(
14193 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14194 } catch (RemoteException e) {
14195 }
14196 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014197 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014198 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014199 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014200 }
14201 }
14202
14203 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014204 // Need to do this on its own message because the stack may not
14205 // be in a consistent state at this point.
14206 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014208 }
14209
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014210 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014211 synchronized (this) {
14212 int i;
14213
14214 // First remove any unused application processes whose package
14215 // has been removed.
14216 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14217 final ProcessRecord app = mRemovedProcesses.get(i);
14218 if (app.activities.size() == 0
14219 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014220 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014221 TAG, "Exiting empty application process "
14222 + app.processName + " ("
14223 + (app.thread != null ? app.thread.asBinder() : null)
14224 + ")\n");
14225 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014226 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014227 app.processName, app.setAdj, "empty");
14228 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014229 } else {
14230 try {
14231 app.thread.scheduleExit();
14232 } catch (Exception e) {
14233 // Ignore exceptions.
14234 }
14235 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014236 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014237 mRemovedProcesses.remove(i);
14238
14239 if (app.persistent) {
14240 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014241 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014242 }
14243 }
14244 }
14245 }
14246
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014247 // Now update the oom adj for all processes.
14248 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014249 }
14250 }
14251
14252 /** This method sends the specified signal to each of the persistent apps */
14253 public void signalPersistentProcesses(int sig) throws RemoteException {
14254 if (sig != Process.SIGNAL_USR1) {
14255 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14256 }
14257
14258 synchronized (this) {
14259 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14260 != PackageManager.PERMISSION_GRANTED) {
14261 throw new SecurityException("Requires permission "
14262 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14263 }
14264
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014265 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14266 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014267 if (r.thread != null && r.persistent) {
14268 Process.sendSignal(r.pid, sig);
14269 }
14270 }
14271 }
14272 }
14273
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014274 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14275 if (proc == null || proc == mProfileProc) {
14276 proc = mProfileProc;
14277 path = mProfileFile;
14278 profileType = mProfileType;
14279 clearProfilerLocked();
14280 }
14281 if (proc == null) {
14282 return;
14283 }
14284 try {
14285 proc.thread.profilerControl(false, path, null, profileType);
14286 } catch (RemoteException e) {
14287 throw new IllegalStateException("Process disappeared");
14288 }
14289 }
14290
14291 private void clearProfilerLocked() {
14292 if (mProfileFd != null) {
14293 try {
14294 mProfileFd.close();
14295 } catch (IOException e) {
14296 }
14297 }
14298 mProfileApp = null;
14299 mProfileProc = null;
14300 mProfileFile = null;
14301 mProfileType = 0;
14302 mAutoStopProfiler = false;
14303 }
14304
Dianne Hackborn1676c852012-09-10 14:52:30 -070014305 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014306 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014307
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014308 try {
14309 synchronized (this) {
14310 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14311 // its own permission.
14312 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14313 != PackageManager.PERMISSION_GRANTED) {
14314 throw new SecurityException("Requires permission "
14315 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014316 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014317
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014318 if (start && fd == null) {
14319 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014320 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014321
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014322 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014323 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014324 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014325 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014326
14327 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014328 throw new IllegalArgumentException("Unknown process: " + process);
14329 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014330
14331 if (start) {
14332 stopProfilerLocked(null, null, 0);
14333 setProfileApp(proc.info, proc.processName, path, fd, false);
14334 mProfileProc = proc;
14335 mProfileType = profileType;
14336 try {
14337 fd = fd.dup();
14338 } catch (IOException e) {
14339 fd = null;
14340 }
14341 proc.thread.profilerControl(start, path, fd, profileType);
14342 fd = null;
14343 mProfileFd = null;
14344 } else {
14345 stopProfilerLocked(proc, path, profileType);
14346 if (fd != null) {
14347 try {
14348 fd.close();
14349 } catch (IOException e) {
14350 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014351 }
14352 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014353
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014354 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014355 }
14356 } catch (RemoteException e) {
14357 throw new IllegalStateException("Process disappeared");
14358 } finally {
14359 if (fd != null) {
14360 try {
14361 fd.close();
14362 } catch (IOException e) {
14363 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014364 }
14365 }
14366 }
Andy McFadden824c5102010-07-09 16:26:57 -070014367
Dianne Hackborn1676c852012-09-10 14:52:30 -070014368 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014369 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014370 userId, true, true, callName, null);
14371 ProcessRecord proc = null;
14372 try {
14373 int pid = Integer.parseInt(process);
14374 synchronized (mPidsSelfLocked) {
14375 proc = mPidsSelfLocked.get(pid);
14376 }
14377 } catch (NumberFormatException e) {
14378 }
14379
14380 if (proc == null) {
14381 HashMap<String, SparseArray<ProcessRecord>> all
14382 = mProcessNames.getMap();
14383 SparseArray<ProcessRecord> procs = all.get(process);
14384 if (procs != null && procs.size() > 0) {
14385 proc = procs.valueAt(0);
14386 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14387 for (int i=1; i<procs.size(); i++) {
14388 ProcessRecord thisProc = procs.valueAt(i);
14389 if (thisProc.userId == userId) {
14390 proc = thisProc;
14391 break;
14392 }
14393 }
14394 }
14395 }
14396 }
14397
14398 return proc;
14399 }
14400
14401 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014402 String path, ParcelFileDescriptor fd) throws RemoteException {
14403
14404 try {
14405 synchronized (this) {
14406 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14407 // its own permission (same as profileControl).
14408 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14409 != PackageManager.PERMISSION_GRANTED) {
14410 throw new SecurityException("Requires permission "
14411 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14412 }
14413
14414 if (fd == null) {
14415 throw new IllegalArgumentException("null fd");
14416 }
14417
Dianne Hackborn1676c852012-09-10 14:52:30 -070014418 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014419 if (proc == null || proc.thread == null) {
14420 throw new IllegalArgumentException("Unknown process: " + process);
14421 }
14422
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014423 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14424 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014425 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14426 throw new SecurityException("Process not debuggable: " + proc);
14427 }
14428 }
14429
14430 proc.thread.dumpHeap(managed, path, fd);
14431 fd = null;
14432 return true;
14433 }
14434 } catch (RemoteException e) {
14435 throw new IllegalStateException("Process disappeared");
14436 } finally {
14437 if (fd != null) {
14438 try {
14439 fd.close();
14440 } catch (IOException e) {
14441 }
14442 }
14443 }
14444 }
14445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014446 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14447 public void monitor() {
14448 synchronized (this) { }
14449 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014450
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014451 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014452 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14453 ProcessRecord processRecord = mLruProcesses.get(i);
14454 try {
14455 if (processRecord.thread != null) {
14456 processRecord.thread.setCoreSettings(settings);
14457 }
14458 } catch (RemoteException re) {
14459 /* ignore */
14460 }
14461 }
14462 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014463
14464 // Multi-user methods
14465
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014466 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014467 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014468 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14469 != PackageManager.PERMISSION_GRANTED) {
14470 String msg = "Permission Denial: switchUser() from pid="
14471 + Binder.getCallingPid()
14472 + ", uid=" + Binder.getCallingUid()
14473 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14474 Slog.w(TAG, msg);
14475 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014476 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014477
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014478 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014479 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014480 synchronized (this) {
14481 final int oldUserId = mCurrentUserId;
14482 if (oldUserId == userId) {
14483 return true;
14484 }
14485
14486 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14487 if (userInfo == null) {
14488 Slog.w(TAG, "No user info for user #" + userId);
14489 return false;
14490 }
14491
14492 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14493 R.anim.screen_user_enter);
14494
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014495 boolean needStart = false;
14496
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014497 // If the user we are switching to is not currently started, then
14498 // we need to start it now.
14499 if (mStartedUsers.get(userId) == null) {
14500 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014501 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014502 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014503 }
14504
14505 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014506 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014507 final Integer userIdInt = Integer.valueOf(userId);
14508 mUserLru.remove(userIdInt);
14509 mUserLru.add(userIdInt);
14510
Craig Mautnerf1b67412012-09-19 13:18:29 -070014511 mWindowManager.setCurrentUser(userId);
14512
Adam Cohenf7522022012-10-03 20:03:18 -070014513 // Once the internal notion of the active user has switched, we lock the device
14514 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014515 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014516
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014517 final UserStartedState uss = mStartedUsers.get(userId);
14518
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014519 // Make sure user is in the started state. If it is currently
14520 // stopping, we need to knock that off.
14521 if (uss.mState == UserStartedState.STATE_STOPPING) {
14522 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14523 // so we can just fairly silently bring the user back from
14524 // the almost-dead.
14525 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014526 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014527 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014528 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14529 // This means ACTION_SHUTDOWN has been sent, so we will
14530 // need to treat this as a new boot of the user.
14531 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014532 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014533 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014534 }
14535
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014536 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14537 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14538 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14539 oldUserId, userId, uss));
14540 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14541 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014542 if (needStart) {
14543 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14544 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14545 | Intent.FLAG_RECEIVER_FOREGROUND);
14546 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14547 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014548 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014549 false, false, MY_PID, Process.SYSTEM_UID, userId);
14550 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014551
14552 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14553 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014554 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014555 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014556 broadcastIntentLocked(null, null, intent, null,
14557 new IIntentReceiver.Stub() {
14558 public void performReceive(Intent intent, int resultCode,
14559 String data, Bundle extras, boolean ordered,
14560 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014561 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014562 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014563 }, 0, null, null, null, AppOpsManager.OP_NONE,
14564 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014565 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014566 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014567 } else {
14568 getUserManagerLocked().makeInitialized(userInfo.id);
14569 }
14570 }
14571
14572 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14573 if (!haveActivities) {
14574 startHomeActivityLocked(userId);
14575 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014576
Jeff Sharkey86597df2012-11-09 15:00:31 -080014577 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014578 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014579 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014580 if (needStart) {
14581 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14582 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14583 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14584 broadcastIntentLocked(null, null, intent,
14585 null, new IIntentReceiver.Stub() {
14586 @Override
14587 public void performReceive(Intent intent, int resultCode, String data,
14588 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14589 throws RemoteException {
14590 }
14591 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014592 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014593 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014594 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014595 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014596 } finally {
14597 Binder.restoreCallingIdentity(ident);
14598 }
Amith Yamasani13593602012-03-22 16:16:17 -070014599
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014600 return true;
14601 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014602
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014603 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14604 long ident = Binder.clearCallingIdentity();
14605 try {
14606 Intent intent;
14607 if (oldUserId >= 0) {
14608 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014609 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14610 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014611 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14612 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014613 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014614 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14615 }
14616 if (newUserId >= 0) {
14617 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14619 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014620 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14621 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014622 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014623 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14624 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014625 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14626 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014627 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14628 broadcastIntentLocked(null, null, intent,
14629 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014630 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014631 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14632 }
14633 } finally {
14634 Binder.restoreCallingIdentity(ident);
14635 }
14636 }
14637
14638 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14639 final int newUserId) {
14640 final int N = mUserSwitchObservers.beginBroadcast();
14641 if (N > 0) {
14642 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14643 int mCount = 0;
14644 @Override
14645 public void sendResult(Bundle data) throws RemoteException {
14646 synchronized (ActivityManagerService.this) {
14647 if (mCurUserSwitchCallback == this) {
14648 mCount++;
14649 if (mCount == N) {
14650 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14651 }
14652 }
14653 }
14654 }
14655 };
14656 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014657 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014658 mCurUserSwitchCallback = callback;
14659 }
14660 for (int i=0; i<N; i++) {
14661 try {
14662 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14663 newUserId, callback);
14664 } catch (RemoteException e) {
14665 }
14666 }
14667 } else {
14668 synchronized (this) {
14669 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14670 }
14671 }
14672 mUserSwitchObservers.finishBroadcast();
14673 }
14674
14675 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14676 synchronized (this) {
14677 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14678 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14679 }
14680 }
14681
14682 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14683 mCurUserSwitchCallback = null;
14684 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14685 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14686 oldUserId, newUserId, uss));
14687 }
14688
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014689 void userInitialized(UserStartedState uss, int newUserId) {
14690 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014691 }
14692
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014693 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014694 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014695 }
14696
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014697 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14698 boolean clearInitializing, boolean clearSwitching) {
14699 boolean unfrozen = false;
14700 synchronized (this) {
14701 if (clearInitializing) {
14702 uss.initializing = false;
14703 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14704 }
14705 if (clearSwitching) {
14706 uss.switching = false;
14707 }
14708 if (!uss.switching && !uss.initializing) {
14709 mWindowManager.stopFreezingScreen();
14710 unfrozen = true;
14711 }
14712 }
14713 if (unfrozen) {
14714 final int N = mUserSwitchObservers.beginBroadcast();
14715 for (int i=0; i<N; i++) {
14716 try {
14717 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14718 } catch (RemoteException e) {
14719 }
14720 }
14721 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014722 }
14723 }
14724
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014725 void finishUserSwitch(UserStartedState uss) {
14726 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014727 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014728 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14729 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014730 final int userId = uss.mHandle.getIdentifier();
14731 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14732 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14733 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014734 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014735 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014736 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014737 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014738 int num = mUserLru.size();
14739 int i = 0;
14740 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14741 Integer oldUserId = mUserLru.get(i);
14742 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14743 if (oldUss == null) {
14744 // Shouldn't happen, but be sane if it does.
14745 mUserLru.remove(i);
14746 num--;
14747 continue;
14748 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014749 if (oldUss.mState == UserStartedState.STATE_STOPPING
14750 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014751 // This user is already stopping, doesn't count.
14752 num--;
14753 i++;
14754 continue;
14755 }
14756 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14757 // Owner and current can't be stopped, but count as running.
14758 i++;
14759 continue;
14760 }
14761 // This is a user to be stopped.
14762 stopUserLocked(oldUserId, null);
14763 num--;
14764 i++;
14765 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014766 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014767 }
14768
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014769 @Override
14770 public int stopUser(final int userId, final IStopUserCallback callback) {
14771 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14772 != PackageManager.PERMISSION_GRANTED) {
14773 String msg = "Permission Denial: switchUser() from pid="
14774 + Binder.getCallingPid()
14775 + ", uid=" + Binder.getCallingUid()
14776 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14777 Slog.w(TAG, msg);
14778 throw new SecurityException(msg);
14779 }
14780 if (userId <= 0) {
14781 throw new IllegalArgumentException("Can't stop primary user " + userId);
14782 }
Amith Yamasani13593602012-03-22 16:16:17 -070014783 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014784 return stopUserLocked(userId, callback);
14785 }
14786 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014787
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014788 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14789 if (mCurrentUserId == userId) {
14790 return ActivityManager.USER_OP_IS_CURRENT;
14791 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014792
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014793 final UserStartedState uss = mStartedUsers.get(userId);
14794 if (uss == null) {
14795 // User is not started, nothing to do... but we do need to
14796 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014797 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014798 mHandler.post(new Runnable() {
14799 @Override
14800 public void run() {
14801 try {
14802 callback.userStopped(userId);
14803 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014804 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014805 }
14806 });
14807 }
14808 return ActivityManager.USER_OP_SUCCESS;
14809 }
14810
14811 if (callback != null) {
14812 uss.mStopCallbacks.add(callback);
14813 }
14814
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014815 if (uss.mState != UserStartedState.STATE_STOPPING
14816 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014817 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014818 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014819
14820 long ident = Binder.clearCallingIdentity();
14821 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014822 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014823 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014824 // stop the user.
14825 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14826 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14827 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14828 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14829 // This is the result receiver for the final shutdown broadcast.
14830 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014831 @Override
14832 public void performReceive(Intent intent, int resultCode, String data,
14833 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14834 finishUserStop(uss);
14835 }
14836 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014837 // This is the result receiver for the initial stopping broadcast.
14838 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14839 @Override
14840 public void performReceive(Intent intent, int resultCode, String data,
14841 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14842 // On to the next.
14843 synchronized (ActivityManagerService.this) {
14844 if (uss.mState != UserStartedState.STATE_STOPPING) {
14845 // Whoops, we are being started back up. Abort, abort!
14846 return;
14847 }
14848 uss.mState = UserStartedState.STATE_SHUTDOWN;
14849 }
14850 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014851 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014852 true, false, MY_PID, Process.SYSTEM_UID, userId);
14853 }
14854 };
14855 // Kick things off.
14856 broadcastIntentLocked(null, null, stoppingIntent,
14857 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014858 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014859 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014860 } finally {
14861 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014862 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014863 }
Amith Yamasani13593602012-03-22 16:16:17 -070014864
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014865 return ActivityManager.USER_OP_SUCCESS;
14866 }
14867
14868 void finishUserStop(UserStartedState uss) {
14869 final int userId = uss.mHandle.getIdentifier();
14870 boolean stopped;
14871 ArrayList<IStopUserCallback> callbacks;
14872 synchronized (this) {
14873 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014874 if (mStartedUsers.get(userId) != uss) {
14875 stopped = false;
14876 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014877 stopped = false;
14878 } else {
14879 stopped = true;
14880 // User can no longer run.
14881 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014882 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014883 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014884
14885 // Clean up all state and processes associated with the user.
14886 // Kill all the processes for the user.
14887 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014888 }
14889 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014890
14891 for (int i=0; i<callbacks.size(); i++) {
14892 try {
14893 if (stopped) callbacks.get(i).userStopped(userId);
14894 else callbacks.get(i).userStopAborted(userId);
14895 } catch (RemoteException e) {
14896 }
14897 }
14898 }
14899
14900 @Override
14901 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014902 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14903 != PackageManager.PERMISSION_GRANTED) && (
14904 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14905 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014906 String msg = "Permission Denial: getCurrentUser() from pid="
14907 + Binder.getCallingPid()
14908 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014909 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014910 Slog.w(TAG, msg);
14911 throw new SecurityException(msg);
14912 }
14913 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014914 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014915 }
Amith Yamasani13593602012-03-22 16:16:17 -070014916 }
14917
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014918 int getCurrentUserIdLocked() {
14919 return mCurrentUserId;
14920 }
14921
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014922 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014923 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014924 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14925 != PackageManager.PERMISSION_GRANTED) {
14926 String msg = "Permission Denial: isUserRunning() from pid="
14927 + Binder.getCallingPid()
14928 + ", uid=" + Binder.getCallingUid()
14929 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14930 Slog.w(TAG, msg);
14931 throw new SecurityException(msg);
14932 }
14933 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014934 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014935 }
14936 }
14937
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014938 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014939 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014940 if (state == null) {
14941 return false;
14942 }
14943 if (orStopped) {
14944 return true;
14945 }
14946 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014947 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014948 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014949
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014950 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014951 public int[] getRunningUserIds() {
14952 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14953 != PackageManager.PERMISSION_GRANTED) {
14954 String msg = "Permission Denial: isUserRunning() from pid="
14955 + Binder.getCallingPid()
14956 + ", uid=" + Binder.getCallingUid()
14957 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14958 Slog.w(TAG, msg);
14959 throw new SecurityException(msg);
14960 }
14961 synchronized (this) {
14962 return mStartedUserArray;
14963 }
14964 }
14965
14966 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014967 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014968 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014969 UserStartedState uss = mStartedUsers.valueAt(i);
14970 // This list does not include stopping users.
14971 if (uss.mState != UserStartedState.STATE_STOPPING
14972 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14973 num++;
14974 }
14975 }
14976 mStartedUserArray = new int[num];
14977 num = 0;
14978 for (int i=0; i<mStartedUsers.size(); i++) {
14979 UserStartedState uss = mStartedUsers.valueAt(i);
14980 if (uss.mState != UserStartedState.STATE_STOPPING
14981 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14982 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14983 num++;
14984 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014985 }
14986 }
14987
14988 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014989 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14990 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14991 != PackageManager.PERMISSION_GRANTED) {
14992 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14993 + Binder.getCallingPid()
14994 + ", uid=" + Binder.getCallingUid()
14995 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14996 Slog.w(TAG, msg);
14997 throw new SecurityException(msg);
14998 }
14999
15000 mUserSwitchObservers.register(observer);
15001 }
15002
15003 @Override
15004 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
15005 mUserSwitchObservers.unregister(observer);
15006 }
15007
Dianne Hackborn1676c852012-09-10 14:52:30 -070015008 private boolean userExists(int userId) {
15009 if (userId == 0) {
15010 return true;
15011 }
15012 UserManagerService ums = getUserManagerLocked();
15013 return ums != null ? (ums.getUserInfo(userId) != null) : false;
15014 }
15015
15016 int[] getUsersLocked() {
15017 UserManagerService ums = getUserManagerLocked();
15018 return ums != null ? ums.getUserIds() : new int[] { 0 };
15019 }
15020
15021 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070015022 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070015023 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
15024 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070015025 }
15026 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070015027 }
15028
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015029 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070015030 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015031
15032 throw new SecurityException("Caller uid=" + uid
15033 + " is not privileged to communicate with user=" + userId);
15034 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015035
15036 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070015037 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070015038 }
15039
Dianne Hackborn599db5c2012-08-03 19:28:48 -070015040 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015041 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015042 ApplicationInfo newInfo = new ApplicationInfo(info);
15043 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070015044 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15045 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070015046 return newInfo;
15047 }
15048
15049 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070015050 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070015051 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070015052 return aInfo;
15053 }
15054
15055 ActivityInfo info = new ActivityInfo(aInfo);
15056 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15057 return info;
15058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015059}