blob: d8e199bafebaf2d723bcb6de884f9b2bcab71a40 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080024import com.android.server.AppOpsService;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070025import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import com.android.server.IntentResolver;
27import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.server.SystemServer;
29import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070030import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070031import com.android.server.pm.UserManagerService;
Craig Mautner4b71aa12012-12-27 17:20:01 -080032import com.android.server.wm.AppTransition;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080033import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034
Dianne Hackborndd71fc82009-12-16 19:24:32 -080035import dalvik.system.Zygote;
36
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.app.Activity;
38import android.app.ActivityManager;
39import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070040import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.ActivityThread;
42import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070043import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020044import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070046import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.app.IApplicationThread;
48import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070049import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070050import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.IThumbnailReceiver;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070054import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070056import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070057import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080059import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020060import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080061import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080062import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070063import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070065import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.ContentResolver;
67import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020068import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070069import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070070import android.content.IIntentReceiver;
71import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070072import android.content.Intent;
73import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070074import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.content.pm.ActivityInfo;
76import android.content.pm.ApplicationInfo;
77import android.content.pm.ConfigurationInfo;
78import android.content.pm.IPackageDataObserver;
79import android.content.pm.IPackageManager;
80import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080081import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070083import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070084import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070085import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.pm.ProviderInfo;
87import android.content.pm.ResolveInfo;
88import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040089import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.content.res.Configuration;
91import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070092import android.net.Proxy;
93import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.net.Uri;
95import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080096import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080097import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070098import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080099import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800101import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.FileUtils;
103import android.os.Handler;
104import android.os.IBinder;
105import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700106import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700107import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.Looper;
109import android.os.Message;
110import android.os.Parcel;
111import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700113import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400115import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700117import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.SystemClock;
119import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700120import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700121import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700123import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800125import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700126import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700128import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700130import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.view.Gravity;
132import android.view.LayoutInflater;
133import android.view.View;
134import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.BufferedInputStream;
137import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700138import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.DataInputStream;
140import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.File;
142import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700143import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700145import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200146import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800147import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700149import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.lang.ref.WeakReference;
151import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700152import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700153import java.util.Collections;
154import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.util.HashMap;
156import java.util.HashSet;
157import java.util.Iterator;
158import java.util.List;
159import java.util.Locale;
160import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700161import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700162import java.util.concurrent.atomic.AtomicBoolean;
163import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700165public final class ActivityManagerService extends ActivityManagerNative
166 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700167 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700169 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400171 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG_SWITCH = localLOGV || false;
173 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700174 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_PAUSE = localLOGV || false;
176 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
177 static final boolean DEBUG_TRANSITION = localLOGV || false;
178 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800179 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700180 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700182 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean DEBUG_VISBILITY = localLOGV || false;
184 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700185 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700186 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700187 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800188 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700190 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700191 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700192 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700193 static final boolean DEBUG_POWER = localLOGV || false;
194 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700195 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700196 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 static final boolean VALIDATE_TOKENS = false;
198 static final boolean SHOW_ACTIVITY_START_TIME = true;
199
200 // Control over CPU and battery monitoring.
201 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
202 static final boolean MONITOR_CPU_USAGE = true;
203 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
204 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
205 static final boolean MONITOR_THREAD_CPU_USAGE = false;
206
Dianne Hackborn1655be42009-05-08 14:29:01 -0700207 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700208 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700209
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800210 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700212 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 // Maximum number of recent tasks that we can remember.
215 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700216
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700217 // Amount of time after a call to stopAppSwitches() during which we will
218 // prevent further untrusted switches from happening.
219 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
221 // How long we wait for a launched process to attach to the activity manager
222 // before we decide it's never going to come up for real.
223 static final int PROC_START_TIMEOUT = 10*1000;
224
Jeff Brown3f9dd282011-07-08 20:02:19 -0700225 // 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, when the process was
227 // started with a wrapper for instrumentation (such as Valgrind) because it
228 // could take much longer than usual.
229 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // How long to wait after going idle before forcing apps to GC.
232 static final int GC_TIMEOUT = 5*1000;
233
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700234 // The minimum amount of time between successive GC requests for a process.
235 static final int GC_MIN_INTERVAL = 60*1000;
236
Dianne Hackborn287952c2010-09-22 22:34:31 -0700237 // The rate at which we check for apps using excessive power -- 15 mins.
238 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
239
240 // The minimum sample duration we will allow before deciding we have
241 // enough data on wake locks to start killing things.
242 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
243
244 // The minimum sample duration we will allow before deciding we have
245 // enough data on CPU usage to start killing things.
246 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800249 static final int BROADCAST_FG_TIMEOUT = 10*1000;
250 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // How long we wait until we timeout on key dispatching.
253 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // How long we wait until we timeout on key dispatching during instrumentation.
256 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
257
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700258 // Amount of time we wait for observers to handle a user switch before
259 // giving up on them and unfreezing the screen.
260 static final int USER_SWITCH_TIMEOUT = 2*1000;
261
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700262 // Maximum number of users we allow to be running at a time.
263 static final int MAX_RUNNING_USERS = 3;
264
Dan Egnor42471dd2010-01-07 17:25:22 -0800265 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 static final String[] EMPTY_STRING_ARRAY = new String[0];
268
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700269 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700270
271 private final boolean mHeadless;
272
Joe Onorato54a4a412011-11-02 20:50:08 -0700273 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
274 // default actuion automatically. Important for devices without direct input
275 // devices.
276 private boolean mShowDialogs = true;
277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700279 * Description of a request to start a new activity, which has been held
280 * due to app switches being disabled.
281 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700282 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700283 ActivityRecord r;
284 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700285 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700286 }
287
288 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
289 = new ArrayList<PendingActivityLaunch>();
290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800292 BroadcastQueue mFgBroadcastQueue;
293 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800294 // Convenient for easy iteration over the queues. Foreground is first
295 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800297
298 BroadcastQueue broadcastQueueForIntent(Intent intent) {
299 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
300 if (DEBUG_BACKGROUND_BROADCAST) {
301 Slog.i(TAG, "Broadcast intent " + intent + " on "
302 + (isFg ? "foreground" : "background")
303 + " queue");
304 }
305 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
306 }
307
308 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
309 for (BroadcastQueue queue : mBroadcastQueues) {
310 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
311 if (r != null) {
312 return r;
313 }
314 }
315 return null;
316 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317
318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * Activity we have told the window manager to have key focus.
320 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700321 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * List of intents that were used to start the most recent tasks.
324 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700325 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326
327 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700328 * Process management.
329 */
330 final ProcessList mProcessList = new ProcessList();
331
332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 * All of the applications we currently have running organized by name.
334 * The keys are strings of the application package name (as
335 * returned by the package manager), and the keys are ApplicationRecord
336 * objects.
337 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700338 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339
340 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800341 * The currently running isolated processes.
342 */
343 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
344
345 /**
346 * Counter for assigning isolated process uids, to avoid frequently reusing the
347 * same ones.
348 */
349 int mNextIsolatedProcessUid = 0;
350
351 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700352 * The currently running heavy-weight process, if any.
353 */
354 ProcessRecord mHeavyWeightProcess = null;
355
356 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 * The last time that various processes have crashed.
358 */
359 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
360
361 /**
362 * Set of applications that we consider to be bad, and will reject
363 * incoming broadcasts from (which the user has no control over).
364 * Processes are added to this set when they have crashed twice within
365 * a minimum amount of time; they are removed from it when they are
366 * later restarted (hopefully due to some user action). The value is the
367 * time it was added to the list.
368 */
369 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
370
371 /**
372 * All of the processes we currently have running organized by pid.
373 * The keys are the pid running the application.
374 *
375 * <p>NOTE: This object is protected by its own lock, NOT the global
376 * activity manager lock!
377 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700378 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379
380 /**
381 * All of the processes that have been forced to be foreground. The key
382 * is the pid of the caller who requested it (we hold a death
383 * link on it).
384 */
385 abstract class ForegroundToken implements IBinder.DeathRecipient {
386 int pid;
387 IBinder token;
388 }
389 final SparseArray<ForegroundToken> mForegroundProcesses
390 = new SparseArray<ForegroundToken>();
391
392 /**
393 * List of records for processes that someone had tried to start before the
394 * system was ready. We don't start them at that point, but ensure they
395 * are started by the time booting is complete.
396 */
397 final ArrayList<ProcessRecord> mProcessesOnHold
398 = new ArrayList<ProcessRecord>();
399
400 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800401 * List of persistent applications that are in the process
402 * of being started.
403 */
404 final ArrayList<ProcessRecord> mPersistentStartingProcesses
405 = new ArrayList<ProcessRecord>();
406
407 /**
408 * Processes that are being forcibly torn down.
409 */
410 final ArrayList<ProcessRecord> mRemovedProcesses
411 = new ArrayList<ProcessRecord>();
412
413 /**
414 * List of running applications, sorted by recent usage.
415 * The first entry in the list is the least recently used.
416 * It contains ApplicationRecord objects. This list does NOT include
417 * any persistent application records (since we never want to exit them).
418 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800419 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 = new ArrayList<ProcessRecord>();
421
422 /**
423 * List of processes that should gc as soon as things are idle.
424 */
425 final ArrayList<ProcessRecord> mProcessesToGc
426 = new ArrayList<ProcessRecord>();
427
428 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800429 * This is the process holding what we currently consider to be
430 * the "home" activity.
431 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700432 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800433
434 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700435 * This is the process holding the activity the user last visited that
436 * is in a different process from the one they are currently in.
437 */
438 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800439
440 /**
441 * The time at which the previous process was last visible.
442 */
443 long mPreviousProcessVisibleTime;
444
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700445 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700446 * Which uses have been started, so are allowed to run code.
447 */
448 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
449
450 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700451 * LRU list of history of current users. Most recently current is at the end.
452 */
453 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
454
455 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700456 * Constant array of the users that are currently started.
457 */
458 int[] mStartedUserArray = new int[] { 0 };
459
460 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700461 * Registered observers of the user switching mechanics.
462 */
463 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
464 = new RemoteCallbackList<IUserSwitchObserver>();
465
466 /**
467 * Currently active user switch.
468 */
469 Object mCurUserSwitchCallback;
470
471 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400472 * Packages that the user has asked to have run in screen size
473 * compatibility mode instead of filling the screen.
474 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700475 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400476
477 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 * Set of PendingResultRecord objects that are currently active.
479 */
480 final HashSet mPendingResultRecords = new HashSet();
481
482 /**
483 * Set of IntentSenderRecord objects that are currently active.
484 */
485 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
486 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
487
488 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800489 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700490 * already logged DropBox entries for. Guarded by itself. If
491 * something (rogue user app) forces this over
492 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
493 */
494 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
495 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
496
497 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700498 * Strict Mode background batched logging state.
499 *
500 * The string buffer is guarded by itself, and its lock is also
501 * used to determine if another batched write is already
502 * in-flight.
503 */
504 private final StringBuilder mStrictModeBuffer = new StringBuilder();
505
506 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 * Keeps track of all IIntentReceivers that have been registered for
508 * broadcasts. Hash keys are the receiver IBinder, hash value is
509 * a ReceiverList.
510 */
511 final HashMap mRegisteredReceivers = new HashMap();
512
513 /**
514 * Resolver for broadcast intents to registered receivers.
515 * Holds BroadcastFilter (subclass of IntentFilter).
516 */
517 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
518 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
519 @Override
520 protected boolean allowFilterResult(
521 BroadcastFilter filter, List<BroadcastFilter> dest) {
522 IBinder target = filter.receiverList.receiver.asBinder();
523 for (int i=dest.size()-1; i>=0; i--) {
524 if (dest.get(i).receiverList.receiver.asBinder() == target) {
525 return false;
526 }
527 }
528 return true;
529 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700530
531 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700532 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700533 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
534 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700535 return super.newResult(filter, match, userId);
536 }
537 return null;
538 }
539
540 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700541 protected BroadcastFilter[] newArray(int size) {
542 return new BroadcastFilter[size];
543 }
544
545 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700546 protected String packageForFilter(BroadcastFilter filter) {
547 return filter.packageName;
548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 };
550
551 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700552 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700554 * that action (which should usually be one). The SparseArray is keyed
555 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
556 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700558 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
559 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700561 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562
563 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700564 * Backup/restore process management
565 */
566 String mBackupAppName = null;
567 BackupRecord mBackupTarget = null;
568
569 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800570 * List of PendingThumbnailsRecord objects of clients who are still
571 * waiting to receive all of the thumbnails for a task.
572 */
573 final ArrayList mPendingThumbnails = new ArrayList();
574
575 /**
576 * List of HistoryRecord objects that have been finished and must
577 * still report back to a pending thumbnail receiver.
578 */
579 final ArrayList mCancelledThumbnails = new ArrayList();
580
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700581 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 /**
584 * List of content providers who have clients waiting for them. The
585 * application is currently being launched and the provider will be
586 * removed from this list once it is published.
587 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700588 final ArrayList<ContentProviderRecord> mLaunchingProviders
589 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590
591 /**
592 * Global set of specific Uri permissions that have been granted.
593 */
594 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
595 = new SparseArray<HashMap<Uri, UriPermission>>();
596
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800597 CoreSettingsObserver mCoreSettingsObserver;
598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 /**
600 * Thread-local storage used to carry caller permissions over through
601 * indirect content-provider access.
602 * @see #ActivityManagerService.openContentUri()
603 */
604 private class Identity {
605 public int pid;
606 public int uid;
607
608 Identity(int _pid, int _uid) {
609 pid = _pid;
610 uid = _uid;
611 }
612 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
615
616 /**
617 * All information we have collected about the runtime performance of
618 * any user id that can impact battery performance.
619 */
620 final BatteryStatsService mBatteryStatsService;
621
622 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800623 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 */
625 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800626
627 /**
628 * Information about and control over application operations
629 */
630 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800631
632 /**
633 * Current configuration information. HistoryRecord objects are given
634 * a reference to this object to indicate which configuration they are
635 * currently running in, so this object must be kept immutable.
636 */
637 Configuration mConfiguration = new Configuration();
638
639 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800640 * Current sequencing integer of the configuration, for skipping old
641 * configurations.
642 */
643 int mConfigurationSeq = 0;
644
645 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700646 * Hardware-reported OpenGLES version.
647 */
648 final int GL_ES_VERSION;
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * List of initialization arguments to pass to all processes when binding applications to them.
652 * For example, references to the commonly used services.
653 */
654 HashMap<String, IBinder> mAppBindArgs;
655
656 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700657 * Temporary to avoid allocations. Protected by main lock.
658 */
659 final StringBuilder mStringBuilder = new StringBuilder(256);
660
661 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 * Used to control how we initialize the service.
663 */
664 boolean mStartRunning = false;
665 ComponentName mTopComponent;
666 String mTopAction;
667 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700668 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 boolean mSystemReady = false;
670 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700671 boolean mWaitingUpdate = false;
672 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700673 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700674 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675
676 Context mContext;
677
678 int mFactoryTest;
679
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700680 boolean mCheckedForSetup;
681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700683 * The time at which we will allow normal application switches again,
684 * after a call to {@link #stopAppSwitches()}.
685 */
686 long mAppSwitchesAllowedTime;
687
688 /**
689 * This is set to true after the first switch after mAppSwitchesAllowedTime
690 * is set; any switches after that will clear the time.
691 */
692 boolean mDidAppSwitch;
693
694 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700695 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700696 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700697 long mLastPowerCheckRealtime;
698
699 /**
700 * Last time (in uptime) at which we checked for power usage.
701 */
702 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700703
704 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705 * Set while we are wanting to sleep, to prevent any
706 * activities from being started/resumed.
707 */
708 boolean mSleeping = false;
709
710 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700711 * State of external calls telling us if the device is asleep.
712 */
713 boolean mWentToSleep = false;
714
715 /**
716 * State of external call telling us if the lock screen is shown.
717 */
718 boolean mLockScreenShown = false;
719
720 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700721 * Set if we are shutting down the system, similar to sleeping.
722 */
723 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724
725 /**
726 * Task identifier that activities are currently being started
727 * in. Incremented each time a new task is created.
728 * todo: Replace this with a TokenSpace class that generates non-repeating
729 * integers that won't wrap.
730 */
731 int mCurTask = 1;
732
733 /**
734 * Current sequence id for oom_adj computation traversal.
735 */
736 int mAdjSeq = 0;
737
738 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700739 * Current sequence id for process LRU updating.
740 */
741 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742
743 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700744 * Keep track of the non-hidden/empty process we last found, to help
745 * determine how to distribute hidden/empty processes next time.
746 */
747 int mNumNonHiddenProcs = 0;
748
749 /**
750 * Keep track of the number of hidden procs, to balance oom adj
751 * distribution between those and empty procs.
752 */
753 int mNumHiddenProcs = 0;
754
755 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700756 * Keep track of the number of service processes we last found, to
757 * determine on the next iteration which should be B services.
758 */
759 int mNumServiceProcs = 0;
760 int mNewNumServiceProcs = 0;
761
762 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 * System monitoring: number of processes that died since the last
764 * N procs were started.
765 */
766 int[] mProcDeaths = new int[20];
767
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700768 /**
769 * This is set if we had to do a delayed dexopt of an app before launching
770 * it, to increasing the ANR timeouts in that case.
771 */
772 boolean mDidDexOpt;
773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 String mDebugApp = null;
775 boolean mWaitForDebugger = false;
776 boolean mDebugTransient = false;
777 String mOrigDebugApp = null;
778 boolean mOrigWaitForDebugger = false;
779 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700780 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700781 String mProfileApp = null;
782 ProcessRecord mProfileProc = null;
783 String mProfileFile;
784 ParcelFileDescriptor mProfileFd;
785 int mProfileType = 0;
786 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800787 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700789 static class ProcessChangeItem {
790 static final int CHANGE_ACTIVITIES = 1<<0;
791 static final int CHANGE_IMPORTANCE= 1<<1;
792 int changes;
793 int uid;
794 int pid;
795 int importance;
796 boolean foregroundActivities;
797 }
798
Jeff Sharkeya4620792011-05-20 15:29:23 -0700799 final RemoteCallbackList<IProcessObserver> mProcessObservers
800 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700801 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
802
803 final ArrayList<ProcessChangeItem> mPendingProcessChanges
804 = new ArrayList<ProcessChangeItem>();
805 final ArrayList<ProcessChangeItem> mAvailProcessChanges
806 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 /**
809 * Callback of last caller to {@link #requestPss}.
810 */
811 Runnable mRequestPssCallback;
812
813 /**
814 * Remaining processes for which we are waiting results from the last
815 * call to {@link #requestPss}.
816 */
817 final ArrayList<ProcessRecord> mRequestPssList
818 = new ArrayList<ProcessRecord>();
819
820 /**
821 * Runtime statistics collection thread. This object's lock is used to
822 * protect all related state.
823 */
824 final Thread mProcessStatsThread;
825
826 /**
827 * Used to collect process stats when showing not responding dialog.
828 * Protected by mProcessStatsThread.
829 */
830 final ProcessStats mProcessStats = new ProcessStats(
831 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700832 final AtomicLong mLastCpuTime = new AtomicLong(0);
833 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 long mLastWriteTime = 0;
836
837 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700838 * Used to retain an update lock when the foreground activity is in
839 * immersive mode.
840 */
841 final UpdateLock mUpdateLock = new UpdateLock("immersive");
842
843 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 * Set to true after the system has finished booting.
845 */
846 boolean mBooted = false;
847
Dianne Hackborn7d608422011-08-07 16:24:18 -0700848 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700849 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
851 WindowManagerService mWindowManager;
852
853 static ActivityManagerService mSelf;
854 static ActivityThread mSystemThread;
855
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700856 private int mCurrentUserId = 0;
857 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700858 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 private final class AppDeathRecipient implements IBinder.DeathRecipient {
861 final ProcessRecord mApp;
862 final int mPid;
863 final IApplicationThread mAppThread;
864
865 AppDeathRecipient(ProcessRecord app, int pid,
866 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 TAG, "New death recipient " + this
869 + " for thread " + thread.asBinder());
870 mApp = app;
871 mPid = pid;
872 mAppThread = thread;
873 }
874
875 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 TAG, "Death received in " + this
878 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 synchronized(ActivityManagerService.this) {
880 appDiedLocked(mApp, mPid, mAppThread);
881 }
882 }
883 }
884
885 static final int SHOW_ERROR_MSG = 1;
886 static final int SHOW_NOT_RESPONDING_MSG = 2;
887 static final int SHOW_FACTORY_ERROR_MSG = 3;
888 static final int UPDATE_CONFIGURATION_MSG = 4;
889 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
890 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 static final int SERVICE_TIMEOUT_MSG = 12;
892 static final int UPDATE_TIME_ZONE = 13;
893 static final int SHOW_UID_ERROR_MSG = 14;
894 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700896 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700897 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800898 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700899 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
900 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700901 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700902 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700903 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700904 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700905 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700906 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700907 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700908 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700909 static final int REPORT_USER_SWITCH_MSG = 34;
910 static final int CONTINUE_USER_SWITCH_MSG = 35;
911 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700912 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800914 static final int FIRST_ACTIVITY_STACK_MSG = 100;
915 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
916 static final int FIRST_COMPAT_MODE_MSG = 300;
917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700919 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700920 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921
922 final Handler mHandler = new Handler() {
923 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800924 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 //}
926
927 public void handleMessage(Message msg) {
928 switch (msg.what) {
929 case SHOW_ERROR_MSG: {
930 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700931 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
932 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 synchronized (ActivityManagerService.this) {
934 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700935 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800937 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700938 if (res != null) {
939 res.set(0);
940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 return;
942 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700943 if (!showBackground && UserHandle.getAppId(proc.uid)
944 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
945 && proc.pid != MY_PID) {
946 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
947 if (res != null) {
948 res.set(0);
949 }
950 return;
951 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700952 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700953 Dialog d = new AppErrorDialog(mContext,
954 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 d.show();
956 proc.crashDialog = d;
957 } else {
958 // The device is asleep, so just pretend that the user
959 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700960 if (res != null) {
961 res.set(0);
962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700965
966 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 } break;
968 case SHOW_NOT_RESPONDING_MSG: {
969 synchronized (ActivityManagerService.this) {
970 HashMap data = (HashMap) msg.obj;
971 ProcessRecord proc = (ProcessRecord)data.get("app");
972 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800973 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 return;
975 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800976
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700977 Intent intent = new Intent("android.intent.action.ANR");
978 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800979 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
980 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700981 }
982 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800983 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700984 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800985
Justin Kohbc52ca22012-03-29 15:11:44 -0700986 if (mShowDialogs) {
987 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -0700988 mContext, proc, (ActivityRecord)data.get("activity"),
989 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -0700990 d.show();
991 proc.anrDialog = d;
992 } else {
993 // Just kill the app if there is no dialog to be shown.
994 killAppAtUsersRequest(proc, null);
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700997
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700998 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001000 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1001 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1002 synchronized (ActivityManagerService.this) {
1003 ProcessRecord proc = (ProcessRecord) data.get("app");
1004 if (proc == null) {
1005 Slog.e(TAG, "App not found when showing strict mode dialog.");
1006 break;
1007 }
1008 if (proc.crashDialog != null) {
1009 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1010 return;
1011 }
1012 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001013 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001014 Dialog d = new StrictModeViolationDialog(mContext,
1015 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001016 d.show();
1017 proc.crashDialog = d;
1018 } else {
1019 // The device is asleep, so just pretend that the user
1020 // saw a crash dialog and hit "force quit".
1021 res.set(0);
1022 }
1023 }
1024 ensureBootCompleted();
1025 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 case SHOW_FACTORY_ERROR_MSG: {
1027 Dialog d = new FactoryErrorDialog(
1028 mContext, msg.getData().getCharSequence("msg"));
1029 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001030 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 } break;
1032 case UPDATE_CONFIGURATION_MSG: {
1033 final ContentResolver resolver = mContext.getContentResolver();
1034 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1035 } break;
1036 case GC_BACKGROUND_PROCESSES_MSG: {
1037 synchronized (ActivityManagerService.this) {
1038 performAppGcsIfAppropriateLocked();
1039 }
1040 } break;
1041 case WAIT_FOR_DEBUGGER_MSG: {
1042 synchronized (ActivityManagerService.this) {
1043 ProcessRecord app = (ProcessRecord)msg.obj;
1044 if (msg.arg1 != 0) {
1045 if (!app.waitedForDebugger) {
1046 Dialog d = new AppWaitingForDebuggerDialog(
1047 ActivityManagerService.this,
1048 mContext, app);
1049 app.waitDialog = d;
1050 app.waitedForDebugger = true;
1051 d.show();
1052 }
1053 } else {
1054 if (app.waitDialog != null) {
1055 app.waitDialog.dismiss();
1056 app.waitDialog = null;
1057 }
1058 }
1059 }
1060 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001062 if (mDidDexOpt) {
1063 mDidDexOpt = false;
1064 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1065 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001066 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001067 return;
1068 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001069 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 } break;
1071 case UPDATE_TIME_ZONE: {
1072 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001073 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1074 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 if (r.thread != null) {
1076 try {
1077 r.thread.updateTimeZone();
1078 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001079 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
1081 }
1082 }
1083 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001084 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001085 case CLEAR_DNS_CACHE: {
1086 synchronized (ActivityManagerService.this) {
1087 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1088 ProcessRecord r = mLruProcesses.get(i);
1089 if (r.thread != null) {
1090 try {
1091 r.thread.clearDnsCache();
1092 } catch (RemoteException ex) {
1093 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1094 }
1095 }
1096 }
1097 }
1098 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001099 case UPDATE_HTTP_PROXY: {
1100 ProxyProperties proxy = (ProxyProperties)msg.obj;
1101 String host = "";
1102 String port = "";
1103 String exclList = "";
1104 if (proxy != null) {
1105 host = proxy.getHost();
1106 port = Integer.toString(proxy.getPort());
1107 exclList = proxy.getExclusionList();
1108 }
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.setHttpProxy(host, port, exclList);
1115 } catch (RemoteException ex) {
1116 Slog.w(TAG, "Failed to update http proxy for: " +
1117 r.info.processName);
1118 }
1119 }
1120 }
1121 }
1122 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001124 String title = "System UIDs Inconsistent";
1125 String text = "UIDs on the system are inconsistent, you need to wipe your"
1126 + " data partition or your device will be unstable.";
1127 Log.e(TAG, title + ": " + text);
1128 if (mShowDialogs) {
1129 // XXX This is a temporary dialog, no need to localize.
1130 AlertDialog d = new BaseErrorDialog(mContext);
1131 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1132 d.setCancelable(false);
1133 d.setTitle(title);
1134 d.setMessage(text);
1135 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1136 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1137 mUidAlert = d;
1138 d.show();
1139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 } break;
1141 case IM_FEELING_LUCKY_MSG: {
1142 if (mUidAlert != null) {
1143 mUidAlert.dismiss();
1144 mUidAlert = null;
1145 }
1146 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001148 if (mDidDexOpt) {
1149 mDidDexOpt = false;
1150 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1151 nmsg.obj = msg.obj;
1152 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1153 return;
1154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 ProcessRecord app = (ProcessRecord)msg.obj;
1156 synchronized (ActivityManagerService.this) {
1157 processStartTimedOutLocked(app);
1158 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001159 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001160 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1161 synchronized (ActivityManagerService.this) {
1162 doPendingActivityLaunchesLocked(true);
1163 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001164 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001165 case KILL_APPLICATION_MSG: {
1166 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001167 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001168 boolean restart = (msg.arg2 == 1);
1169 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001170 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1171 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001172 }
1173 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001174 case FINALIZE_PENDING_INTENT_MSG: {
1175 ((PendingIntentRecord)msg.obj).completeFinalize();
1176 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001177 case POST_HEAVY_NOTIFICATION_MSG: {
1178 INotificationManager inm = NotificationManager.getService();
1179 if (inm == null) {
1180 return;
1181 }
1182
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001183 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001184 ProcessRecord process = root.app;
1185 if (process == null) {
1186 return;
1187 }
1188
1189 try {
1190 Context context = mContext.createPackageContext(process.info.packageName, 0);
1191 String text = mContext.getString(R.string.heavy_weight_notification,
1192 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1193 Notification notification = new Notification();
1194 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1195 notification.when = 0;
1196 notification.flags = Notification.FLAG_ONGOING_EVENT;
1197 notification.tickerText = text;
1198 notification.defaults = 0; // please be quiet
1199 notification.sound = null;
1200 notification.vibrate = null;
1201 notification.setLatestEventInfo(context, text,
1202 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001203 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1204 PendingIntent.FLAG_CANCEL_CURRENT, null,
1205 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001206
1207 try {
1208 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001209 inm.enqueueNotificationWithTag("android", null,
1210 R.string.heavy_weight_notification,
1211 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001212 } catch (RuntimeException e) {
1213 Slog.w(ActivityManagerService.TAG,
1214 "Error showing notification for heavy-weight app", e);
1215 } catch (RemoteException e) {
1216 }
1217 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001218 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001219 }
1220 } break;
1221 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1222 INotificationManager inm = NotificationManager.getService();
1223 if (inm == null) {
1224 return;
1225 }
1226 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001227 inm.cancelNotificationWithTag("android", null,
1228 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001229 } catch (RuntimeException e) {
1230 Slog.w(ActivityManagerService.TAG,
1231 "Error canceling notification for service", e);
1232 } catch (RemoteException e) {
1233 }
1234 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001235 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1236 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001237 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001238 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001239 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1240 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001241 }
1242 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001243 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1244 synchronized (ActivityManagerService.this) {
1245 ActivityRecord ar = (ActivityRecord)msg.obj;
1246 if (mCompatModeDialog != null) {
1247 if (mCompatModeDialog.mAppInfo.packageName.equals(
1248 ar.info.applicationInfo.packageName)) {
1249 return;
1250 }
1251 mCompatModeDialog.dismiss();
1252 mCompatModeDialog = null;
1253 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001254 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001255 if (mCompatModePackages.getPackageAskCompatModeLocked(
1256 ar.packageName)) {
1257 int mode = mCompatModePackages.computeCompatModeLocked(
1258 ar.info.applicationInfo);
1259 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1260 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1261 mCompatModeDialog = new CompatModeDialog(
1262 ActivityManagerService.this, mContext,
1263 ar.info.applicationInfo);
1264 mCompatModeDialog.show();
1265 }
1266 }
1267 }
1268 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001269 break;
1270 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001271 case DISPATCH_PROCESSES_CHANGED: {
1272 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001273 break;
1274 }
1275 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001276 final int pid = msg.arg1;
1277 final int uid = msg.arg2;
1278 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001279 break;
1280 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001281 case REPORT_MEM_USAGE: {
1282 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1283 if (!isDebuggable) {
1284 return;
1285 }
1286 synchronized (ActivityManagerService.this) {
1287 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001288 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1289 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001290 // avoid spamming.
1291 return;
1292 }
1293 mLastMemUsageReportTime = now;
1294 }
1295 Thread thread = new Thread() {
1296 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001297 StringBuilder dropBuilder = new StringBuilder(1024);
1298 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001299 StringWriter oomSw = new StringWriter();
1300 PrintWriter oomPw = new PrintWriter(oomSw);
1301 StringWriter catSw = new StringWriter();
1302 PrintWriter catPw = new PrintWriter(catSw);
1303 String[] emptyArgs = new String[] { };
1304 StringBuilder tag = new StringBuilder(128);
1305 StringBuilder stack = new StringBuilder(128);
1306 tag.append("Low on memory -- ");
1307 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1308 tag, stack);
1309 dropBuilder.append(stack);
1310 dropBuilder.append('\n');
1311 dropBuilder.append('\n');
1312 String oomString = oomSw.toString();
1313 dropBuilder.append(oomString);
1314 dropBuilder.append('\n');
1315 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001316 try {
1317 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1318 "procrank", });
1319 final InputStreamReader converter = new InputStreamReader(
1320 proc.getInputStream());
1321 BufferedReader in = new BufferedReader(converter);
1322 String line;
1323 while (true) {
1324 line = in.readLine();
1325 if (line == null) {
1326 break;
1327 }
1328 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001329 logBuilder.append(line);
1330 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001331 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001332 dropBuilder.append(line);
1333 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001334 }
1335 converter.close();
1336 } catch (IOException e) {
1337 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001338 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001339 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001340 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001341 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001342 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1343 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001344 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001345 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001346 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001347 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001348 addErrorToDropBox("lowmem", null, "system_server", null,
1349 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001350 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001351 synchronized (ActivityManagerService.this) {
1352 long now = SystemClock.uptimeMillis();
1353 if (mLastMemUsageReportTime < now) {
1354 mLastMemUsageReportTime = now;
1355 }
1356 }
1357 }
1358 };
1359 thread.start();
1360 break;
1361 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001362 case REPORT_USER_SWITCH_MSG: {
1363 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1364 break;
1365 }
1366 case CONTINUE_USER_SWITCH_MSG: {
1367 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1368 break;
1369 }
1370 case USER_SWITCH_TIMEOUT_MSG: {
1371 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1372 break;
1373 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001374 case IMMERSIVE_MODE_LOCK_MSG: {
1375 final boolean nextState = (msg.arg1 != 0);
1376 if (mUpdateLock.isHeld() != nextState) {
1377 if (DEBUG_IMMERSIVE) {
1378 final ActivityRecord r = (ActivityRecord) msg.obj;
1379 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1380 }
1381 if (nextState) {
1382 mUpdateLock.acquire();
1383 } else {
1384 mUpdateLock.release();
1385 }
1386 }
1387 break;
1388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390 }
1391 };
1392
1393 public static void setSystemProcess() {
1394 try {
1395 ActivityManagerService m = mSelf;
1396
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001397 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001399 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001400 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 if (MONITOR_CPU_USAGE) {
1402 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 ServiceManager.addService("permission", new PermissionController(m));
1405
1406 ApplicationInfo info =
1407 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001408 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001409 mSystemThread.installSystemApplicationInfo(info);
1410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 synchronized (mSelf) {
1412 ProcessRecord app = mSelf.newProcessRecordLocked(
1413 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001414 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001416 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001417 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001418 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 synchronized (mSelf.mPidsSelfLocked) {
1420 mSelf.mPidsSelfLocked.put(app.pid, app);
1421 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001422 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 } catch (PackageManager.NameNotFoundException e) {
1425 throw new RuntimeException(
1426 "Unable to find android system package", e);
1427 }
1428 }
1429
1430 public void setWindowManager(WindowManagerService wm) {
1431 mWindowManager = wm;
1432 }
1433
1434 public static final Context main(int factoryTest) {
1435 AThread thr = new AThread();
1436 thr.start();
1437
1438 synchronized (thr) {
1439 while (thr.mService == null) {
1440 try {
1441 thr.wait();
1442 } catch (InterruptedException e) {
1443 }
1444 }
1445 }
1446
1447 ActivityManagerService m = thr.mService;
1448 mSelf = m;
1449 ActivityThread at = ActivityThread.systemMain();
1450 mSystemThread = at;
1451 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001452 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 m.mContext = context;
1454 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001455 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456
1457 m.mBatteryStatsService.publish(context);
1458 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001459 m.mAppOpsService.publish(context);
1460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 synchronized (thr) {
1462 thr.mReady = true;
1463 thr.notifyAll();
1464 }
1465
1466 m.startRunning(null, null, null, null);
1467
1468 return context;
1469 }
1470
1471 public static ActivityManagerService self() {
1472 return mSelf;
1473 }
1474
1475 static class AThread extends Thread {
1476 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001477 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 boolean mReady = false;
1479
1480 public AThread() {
1481 super("ActivityManager");
1482 }
1483
1484 public void run() {
1485 Looper.prepare();
1486
1487 android.os.Process.setThreadPriority(
1488 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001489 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490
1491 ActivityManagerService m = new ActivityManagerService();
1492
1493 synchronized (this) {
1494 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001495 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 notifyAll();
1497 }
1498
1499 synchronized (this) {
1500 while (!mReady) {
1501 try {
1502 wait();
1503 } catch (InterruptedException e) {
1504 }
1505 }
1506 }
1507
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001508 // For debug builds, log event loop stalls to dropbox for analysis.
1509 if (StrictMode.conditionallyEnableDebugLogging()) {
1510 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1511 }
1512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 Looper.loop();
1514 }
1515 }
1516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 static class MemBinder extends Binder {
1518 ActivityManagerService mActivityManagerService;
1519 MemBinder(ActivityManagerService activityManagerService) {
1520 mActivityManagerService = activityManagerService;
1521 }
1522
1523 @Override
1524 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001525 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1526 != PackageManager.PERMISSION_GRANTED) {
1527 pw.println("Permission Denial: can't dump meminfo from from pid="
1528 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1529 + " without permission " + android.Manifest.permission.DUMP);
1530 return;
1531 }
1532
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001533 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001534 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 }
1536 }
1537
Chet Haase9c1e23b2011-03-24 10:51:31 -07001538 static class GraphicsBinder extends Binder {
1539 ActivityManagerService mActivityManagerService;
1540 GraphicsBinder(ActivityManagerService activityManagerService) {
1541 mActivityManagerService = activityManagerService;
1542 }
1543
1544 @Override
1545 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001546 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1547 != PackageManager.PERMISSION_GRANTED) {
1548 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1549 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1550 + " without permission " + android.Manifest.permission.DUMP);
1551 return;
1552 }
1553
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001554 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001555 }
1556 }
1557
Jeff Brown6754ba22011-12-14 20:20:01 -08001558 static class DbBinder extends Binder {
1559 ActivityManagerService mActivityManagerService;
1560 DbBinder(ActivityManagerService activityManagerService) {
1561 mActivityManagerService = activityManagerService;
1562 }
1563
1564 @Override
1565 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1566 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1567 != PackageManager.PERMISSION_GRANTED) {
1568 pw.println("Permission Denial: can't dump dbinfo from from pid="
1569 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1570 + " without permission " + android.Manifest.permission.DUMP);
1571 return;
1572 }
1573
1574 mActivityManagerService.dumpDbInfo(fd, pw, args);
1575 }
1576 }
1577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 static class CpuBinder extends Binder {
1579 ActivityManagerService mActivityManagerService;
1580 CpuBinder(ActivityManagerService activityManagerService) {
1581 mActivityManagerService = activityManagerService;
1582 }
1583
1584 @Override
1585 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001586 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1587 != PackageManager.PERMISSION_GRANTED) {
1588 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1589 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1590 + " without permission " + android.Manifest.permission.DUMP);
1591 return;
1592 }
1593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001594 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001595 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1596 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1597 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 }
1600 }
1601
1602 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001603 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001604
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001605 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1606 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1607 mBroadcastQueues[0] = mFgBroadcastQueue;
1608 mBroadcastQueues[1] = mBgBroadcastQueue;
1609
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001610 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001611 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 File dataDir = Environment.getDataDirectory();
1614 File systemDir = new File(dataDir, "system");
1615 systemDir.mkdirs();
1616 mBatteryStatsService = new BatteryStatsService(new File(
1617 systemDir, "batterystats.bin").toString());
1618 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001619 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001620 mOnBattery = DEBUG_POWER ? true
1621 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001622 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001623
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001624 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001625 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001626 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001627 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001629 // User 0 is the first and only user that runs at boot.
1630 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001631 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001632 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001633
Jack Palevichb90d28c2009-07-22 15:35:24 -07001634 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1635 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1636
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001637 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001638 mConfiguration.setLocale(Locale.getDefault());
1639
Dianne Hackborn813075a62011-11-14 17:45:19 -08001640 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 mProcessStats.init();
1642
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001643 mCompatModePackages = new CompatModePackages(this, systemDir);
1644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 // Add ourself to the Watchdog monitors.
1646 Watchdog.getInstance().addMonitor(this);
1647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 mProcessStatsThread = new Thread("ProcessStats") {
1649 public void run() {
1650 while (true) {
1651 try {
1652 try {
1653 synchronized(this) {
1654 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001655 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001657 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 // + ", write delay=" + nextWriteDelay);
1659 if (nextWriteDelay < nextCpuDelay) {
1660 nextCpuDelay = nextWriteDelay;
1661 }
1662 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001663 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 this.wait(nextCpuDelay);
1665 }
1666 }
1667 } catch (InterruptedException e) {
1668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 updateCpuStatsNow();
1670 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001671 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673 }
1674 }
1675 };
1676 mProcessStatsThread.start();
1677 }
1678
1679 @Override
1680 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1681 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001682 if (code == SYSPROPS_TRANSACTION) {
1683 // We need to tell all apps about the system property change.
1684 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1685 synchronized(this) {
1686 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1687 final int NA = apps.size();
1688 for (int ia=0; ia<NA; ia++) {
1689 ProcessRecord app = apps.valueAt(ia);
1690 if (app.thread != null) {
1691 procs.add(app.thread.asBinder());
1692 }
1693 }
1694 }
1695 }
1696
1697 int N = procs.size();
1698 for (int i=0; i<N; i++) {
1699 Parcel data2 = Parcel.obtain();
1700 try {
1701 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1702 } catch (RemoteException e) {
1703 }
1704 data2.recycle();
1705 }
1706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 try {
1708 return super.onTransact(code, data, reply, flags);
1709 } catch (RuntimeException e) {
1710 // The activity manager only throws security exceptions, so let's
1711 // log all others.
1712 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001713 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715 throw e;
1716 }
1717 }
1718
1719 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001720 final long now = SystemClock.uptimeMillis();
1721 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1722 return;
1723 }
1724 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1725 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 mProcessStatsThread.notify();
1727 }
1728 }
1729 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 void updateCpuStatsNow() {
1732 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001733 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 final long now = SystemClock.uptimeMillis();
1735 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001738 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1739 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 haveNewCpuStats = true;
1741 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001742 //Slog.i(TAG, mProcessStats.printCurrentState());
1743 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 // + mProcessStats.getTotalCpuPercent() + "%");
1745
Joe Onorato8a9b2202010-02-26 18:56:32 -08001746 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 if ("true".equals(SystemProperties.get("events.cpu"))) {
1748 int user = mProcessStats.getLastUserTime();
1749 int system = mProcessStats.getLastSystemTime();
1750 int iowait = mProcessStats.getLastIoWaitTime();
1751 int irq = mProcessStats.getLastIrqTime();
1752 int softIrq = mProcessStats.getLastSoftIrqTime();
1753 int idle = mProcessStats.getLastIdleTime();
1754
1755 int total = user + system + iowait + irq + softIrq + idle;
1756 if (total == 0) total = 1;
1757
Doug Zongker2bec3d42009-12-04 12:52:44 -08001758 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 ((user+system+iowait+irq+softIrq) * 100) / total,
1760 (user * 100) / total,
1761 (system * 100) / total,
1762 (iowait * 100) / total,
1763 (irq * 100) / total,
1764 (softIrq * 100) / total);
1765 }
1766 }
1767
Amith Yamasanie43530a2009-08-21 13:11:37 -07001768 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001769 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001770 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 synchronized(mPidsSelfLocked) {
1772 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001773 if (mOnBattery) {
1774 int perc = bstats.startAddingCpuLocked();
1775 int totalUTime = 0;
1776 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001777 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001779 ProcessStats.Stats st = mProcessStats.getStats(i);
1780 if (!st.working) {
1781 continue;
1782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001784 int otherUTime = (st.rel_utime*perc)/100;
1785 int otherSTime = (st.rel_stime*perc)/100;
1786 totalUTime += otherUTime;
1787 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (pr != null) {
1789 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001790 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1791 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001792 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001793 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001794 } else {
1795 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001796 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001797 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001798 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1799 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001800 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 }
1803 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001804 bstats.finishAddingCpuLocked(perc, totalUTime,
1805 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
1807 }
1808 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1811 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001812 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
1814 }
1815 }
1816 }
1817
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001818 @Override
1819 public void batteryNeedsCpuUpdate() {
1820 updateCpuStatsNow();
1821 }
1822
1823 @Override
1824 public void batteryPowerChanged(boolean onBattery) {
1825 // When plugging in, update the CPU stats first before changing
1826 // the plug state.
1827 updateCpuStatsNow();
1828 synchronized (this) {
1829 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001830 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001831 }
1832 }
1833 }
1834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 /**
1836 * Initialize the application bind args. These are passed to each
1837 * process when the bindApplication() IPC is sent to the process. They're
1838 * lazily setup to make sure the services are running when they're asked for.
1839 */
1840 private HashMap<String, IBinder> getCommonServicesLocked() {
1841 if (mAppBindArgs == null) {
1842 mAppBindArgs = new HashMap<String, IBinder>();
1843
1844 // Setup the application init args
1845 mAppBindArgs.put("package", ServiceManager.getService("package"));
1846 mAppBindArgs.put("window", ServiceManager.getService("window"));
1847 mAppBindArgs.put(Context.ALARM_SERVICE,
1848 ServiceManager.getService(Context.ALARM_SERVICE));
1849 }
1850 return mAppBindArgs;
1851 }
1852
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if (mFocusedActivity != r) {
1855 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001856 if (r != null) {
1857 mWindowManager.setFocusedApp(r.appToken, true);
1858 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001859 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 }
1862
Christopher Tate73c2aee2012-03-15 16:27:14 -07001863 final void applyUpdateLockStateLocked(ActivityRecord r) {
1864 // Modifications to the UpdateLock state are done on our handler, outside
1865 // the activity manager's locks. The new state is determined based on the
1866 // state *now* of the relevant activity record. The object is passed to
1867 // the handler solely for logging detail, not to be consulted/modified.
1868 final boolean nextState = r != null && r.immersive;
1869 mHandler.sendMessage(
1870 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1871 }
1872
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001873 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001875 int lrui = mLruProcesses.indexOf(app);
1876 if (lrui >= 0) mLruProcesses.remove(lrui);
1877
1878 int i = mLruProcesses.size()-1;
1879 int skipTop = 0;
1880
Dianne Hackborn906497c2010-05-10 15:57:38 -07001881 app.lruSeq = mLruSeq;
1882
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001883 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001884 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001885 if (app.activities.size() > 0) {
1886 // If this process has activities, we more strongly want to keep
1887 // it around.
1888 app.lruWeight = app.lastActivityTime;
1889 } else if (app.pubProviders.size() > 0) {
1890 // If this process contains content providers, we want to keep
1891 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001892 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001893 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001894 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001895 } else {
1896 // If this process doesn't have activities, we less strongly
1897 // want to keep it around, and generally want to avoid getting
1898 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001899 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001900 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001901 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001902 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001903
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001904 while (i >= 0) {
1905 ProcessRecord p = mLruProcesses.get(i);
1906 // If this app shouldn't be in front of the first N background
1907 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001908 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001909 skipTop--;
1910 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001911 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001912 mLruProcesses.add(i+1, app);
1913 break;
1914 }
1915 i--;
1916 }
1917 if (i < 0) {
1918 mLruProcesses.add(0, app);
1919 }
1920
Dianne Hackborn906497c2010-05-10 15:57:38 -07001921 // If the app is currently using a content provider or service,
1922 // bump those processes as well.
1923 if (app.connections.size() > 0) {
1924 for (ConnectionRecord cr : app.connections) {
1925 if (cr.binding != null && cr.binding.service != null
1926 && cr.binding.service.app != null
1927 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001928 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001929 }
1930 }
1931 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001932 for (int j=app.conProviders.size()-1; j>=0; j--) {
1933 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1934 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001935 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001936 }
1937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001941 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001942 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001943 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001944
1945 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1946 if (oomAdj) {
1947 updateOomAdjLocked();
1948 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001949 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001950
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001951 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001953 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001954 // The system gets to run in any process. If there are multiple
1955 // processes with the same uid, just pick the first (this
1956 // should never happen).
1957 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1958 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001959 if (procs == null) return null;
1960 final int N = procs.size();
1961 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001962 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 }
1965 ProcessRecord proc = mProcessNames.get(processName, uid);
1966 return proc;
1967 }
1968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001969 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001970 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001971 try {
1972 if (pm.performDexOpt(packageName)) {
1973 mDidDexOpt = true;
1974 }
1975 } catch (RemoteException e) {
1976 }
1977 }
1978
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001979 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08001981 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
1982 || transit == AppTransition.TRANSIT_TASK_OPEN
1983 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
1985
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001986 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001988 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1989 boolean isolated) {
1990 ProcessRecord app;
1991 if (!isolated) {
1992 app = getProcessRecordLocked(processName, info.uid);
1993 } else {
1994 // If this is an isolated process, it can't re-use an existing process.
1995 app = null;
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 // We don't have to do anything more if:
1998 // (1) There is an existing application record; and
1999 // (2) The caller doesn't think it is dead, OR there is no thread
2000 // object attached to it so we know it couldn't have crashed; and
2001 // (3) There is a pid assigned to it, so it is either starting or
2002 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002003 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 + " app=" + app + " knownToBeDead=" + knownToBeDead
2005 + " thread=" + (app != null ? app.thread : null)
2006 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002007 if (app != null && app.pid > 0) {
2008 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002009 // We already have the app running, or are waiting for it to
2010 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002011 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002012 // If this is a new package in the process, add the package to the list
2013 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002014 return app;
2015 } else {
2016 // An application record is attached to a previous process,
2017 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002018 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002019 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023 String hostingNameStr = hostingName != null
2024 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002025
2026 if (!isolated) {
2027 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2028 // If we are in the background, then check to see if this process
2029 // is bad. If so, we will just silently fail.
2030 if (mBadProcesses.get(info.processName, info.uid) != null) {
2031 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2032 + "/" + info.processName);
2033 return null;
2034 }
2035 } else {
2036 // When the user is explicitly starting a process, then clear its
2037 // crash count so that we won't make it bad until they see at
2038 // least one crash dialog again, and make the process good again
2039 // if it had been bad.
2040 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002041 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002042 mProcessCrashTimes.remove(info.processName, info.uid);
2043 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002044 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2045 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002046 info.processName);
2047 mBadProcesses.remove(info.processName, info.uid);
2048 if (app != null) {
2049 app.bad = false;
2050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 }
2053 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002056 app = newProcessRecordLocked(null, info, processName, isolated);
2057 if (app == null) {
2058 Slog.w(TAG, "Failed making new process record for "
2059 + processName + "/" + info.uid + " isolated=" + isolated);
2060 return null;
2061 }
2062 mProcessNames.put(processName, app.uid, app);
2063 if (isolated) {
2064 mIsolatedProcesses.put(app.uid, app);
2065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 } else {
2067 // If this is a new package in the process, add the package to the list
2068 app.addPackage(info.packageName);
2069 }
2070
2071 // If the system is not ready yet, then hold off on starting this
2072 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002073 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002074 && !isAllowedWhileBooting(info)
2075 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 if (!mProcessesOnHold.contains(app)) {
2077 mProcessesOnHold.add(app);
2078 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002079 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 return app;
2081 }
2082
2083 startProcessLocked(app, hostingType, hostingNameStr);
2084 return (app.pid != 0) ? app : null;
2085 }
2086
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002087 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2088 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2089 }
2090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 private final void startProcessLocked(ProcessRecord app,
2092 String hostingType, String hostingNameStr) {
2093 if (app.pid > 0 && app.pid != MY_PID) {
2094 synchronized (mPidsSelfLocked) {
2095 mPidsSelfLocked.remove(app.pid);
2096 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2097 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002098 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 }
2100
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002101 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2102 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 mProcessesOnHold.remove(app);
2104
2105 updateCpuStats();
2106
2107 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2108 mProcDeaths[0] = 0;
2109
2110 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002111 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002114 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002115 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002116 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002117 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002118 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002119 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002120
2121 if (Environment.isExternalStorageEmulated()) {
2122 if (pm.checkPermission(
2123 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2124 app.info.packageName) == PERMISSION_GRANTED) {
2125 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2126 } else {
2127 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2128 }
2129 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002130 } catch (PackageManager.NameNotFoundException e) {
2131 Slog.w(TAG, "Unable to retrieve gids", e);
2132 }
Kenny Roote091f222012-09-11 15:01:26 -07002133
2134 /*
2135 * Add shared application GID so applications can share some
2136 * resources like shared libraries
2137 */
2138 if (permGids == null) {
2139 gids = new int[1];
2140 } else {
2141 gids = new int[permGids.length + 1];
2142 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2143 }
2144 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2147 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2148 && mTopComponent != null
2149 && app.processName.equals(mTopComponent.getPackageName())) {
2150 uid = 0;
2151 }
2152 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2153 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2154 uid = 0;
2155 }
2156 }
2157 int debugFlags = 0;
2158 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2159 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002160 // Also turn on CheckJNI for debuggable apps. It's quite
2161 // awkward to turn on otherwise.
2162 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002163 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002164 // Run the app in safe mode if its manifest requests so or the
2165 // system is booted in safe mode.
2166 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2167 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002168 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2171 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2172 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002173 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2174 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 if ("1".equals(SystemProperties.get("debug.assert"))) {
2177 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2178 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002179
2180 // Start the process. It will either succeed and return a result containing
2181 // the PID of the new process, or else throw a RuntimeException.
2182 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002183 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002184 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2187 synchronized (bs) {
2188 if (bs.isOnBattery()) {
2189 app.batteryStats.incStartsLocked();
2190 }
2191 }
2192
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002193 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2194 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 app.processName, hostingType,
2196 hostingNameStr != null ? hostingNameStr : "");
2197
2198 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002199 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002202 StringBuilder buf = mStringBuilder;
2203 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 buf.append("Start proc ");
2205 buf.append(app.processName);
2206 buf.append(" for ");
2207 buf.append(hostingType);
2208 if (hostingNameStr != null) {
2209 buf.append(" ");
2210 buf.append(hostingNameStr);
2211 }
2212 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002213 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 buf.append(" uid=");
2215 buf.append(uid);
2216 buf.append(" gids={");
2217 if (gids != null) {
2218 for (int gi=0; gi<gids.length; gi++) {
2219 if (gi != 0) buf.append(", ");
2220 buf.append(gids[gi]);
2221
2222 }
2223 }
2224 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002225 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002226 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002227 app.usingWrapper = startResult.usingWrapper;
2228 app.removed = false;
2229 synchronized (mPidsSelfLocked) {
2230 this.mPidsSelfLocked.put(startResult.pid, app);
2231 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2232 msg.obj = app;
2233 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2234 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236 } catch (RuntimeException e) {
2237 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002238 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002239 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002240 }
2241 }
2242
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002243 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 if (resumed) {
2245 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2246 } else {
2247 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2248 }
2249 }
2250
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002251 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002252 if (mHeadless) {
2253 // Added because none of the other calls to ensureBootCompleted seem to fire
2254 // when running headless.
2255 ensureBootCompleted();
2256 return false;
2257 }
2258
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002259 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2260 && mTopAction == null) {
2261 // We are running in factory test mode, but unable to find
2262 // the factory test app, so just sit around displaying the
2263 // error message and don't try to start anything.
2264 return false;
2265 }
2266 Intent intent = new Intent(
2267 mTopAction,
2268 mTopData != null ? Uri.parse(mTopData) : null);
2269 intent.setComponent(mTopComponent);
2270 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2271 intent.addCategory(Intent.CATEGORY_HOME);
2272 }
2273 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002274 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002275 if (aInfo != null) {
2276 intent.setComponent(new ComponentName(
2277 aInfo.applicationInfo.packageName, aInfo.name));
2278 // Don't do this if the home app is currently being
2279 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002280 aInfo = new ActivityInfo(aInfo);
2281 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002282 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2283 aInfo.applicationInfo.uid);
2284 if (app == null || app.instrumentationClass == null) {
2285 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002286 mMainStack.startActivityLocked(null, intent, null, aInfo,
2287 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002288 }
2289 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002290
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002291 return true;
2292 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002293
Amith Yamasani259d5e52012-08-31 15:11:01 -07002294 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2295 ActivityInfo ai = null;
2296 ComponentName comp = intent.getComponent();
2297 try {
2298 if (comp != null) {
2299 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2300 } else {
2301 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2302 intent,
2303 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2304 flags, userId);
2305
2306 if (info != null) {
2307 ai = info.activityInfo;
2308 }
2309 }
2310 } catch (RemoteException e) {
2311 // ignore
2312 }
2313
2314 return ai;
2315 }
2316
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002317 /**
2318 * Starts the "new version setup screen" if appropriate.
2319 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002320 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002321 // Only do this once per boot.
2322 if (mCheckedForSetup) {
2323 return;
2324 }
2325
2326 // We will show this screen if the current one is a different
2327 // version than the last one shown, and we are not running in
2328 // low-level factory test mode.
2329 final ContentResolver resolver = mContext.getContentResolver();
2330 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002331 Settings.Global.getInt(resolver,
2332 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002333 mCheckedForSetup = true;
2334
2335 // See if we should be showing the platform update setup UI.
2336 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2337 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2338 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2339
2340 // We don't allow third party apps to replace this.
2341 ResolveInfo ri = null;
2342 for (int i=0; ris != null && i<ris.size(); i++) {
2343 if ((ris.get(i).activityInfo.applicationInfo.flags
2344 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2345 ri = ris.get(i);
2346 break;
2347 }
2348 }
2349
2350 if (ri != null) {
2351 String vers = ri.activityInfo.metaData != null
2352 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2353 : null;
2354 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2355 vers = ri.activityInfo.applicationInfo.metaData.getString(
2356 Intent.METADATA_SETUP_VERSION);
2357 }
2358 String lastVers = Settings.Secure.getString(
2359 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2360 if (vers != null && !vers.equals(lastVers)) {
2361 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2362 intent.setComponent(new ComponentName(
2363 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002364 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2365 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002366 }
2367 }
2368 }
2369 }
2370
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002371 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002372 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002373 }
2374
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002375 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002376 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002377 throw new SecurityException("Isolated process not allowed to call " + caller);
2378 }
2379 }
2380
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002381 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002382 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002383 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002384 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2385 }
2386 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002387
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002388 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002389 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2390 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002391 synchronized (this) {
2392 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2393 }
2394 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002395
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002396 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002397 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002398 synchronized (this) {
2399 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2400 }
2401 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002402
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002403 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002404 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2405 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002406 synchronized (this) {
2407 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002408 }
2409 }
2410
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002411 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002412 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002413 synchronized (this) {
2414 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2415 }
2416 }
2417
2418 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002419 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2420 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002421 synchronized (this) {
2422 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2423 }
2424 }
2425
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002427 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002428 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002431 private void dispatchProcessesChanged() {
2432 int N;
2433 synchronized (this) {
2434 N = mPendingProcessChanges.size();
2435 if (mActiveProcessChanges.length < N) {
2436 mActiveProcessChanges = new ProcessChangeItem[N];
2437 }
2438 mPendingProcessChanges.toArray(mActiveProcessChanges);
2439 mAvailProcessChanges.addAll(mPendingProcessChanges);
2440 mPendingProcessChanges.clear();
2441 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2442 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002443 int i = mProcessObservers.beginBroadcast();
2444 while (i > 0) {
2445 i--;
2446 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2447 if (observer != null) {
2448 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002449 for (int j=0; j<N; j++) {
2450 ProcessChangeItem item = mActiveProcessChanges[j];
2451 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2452 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2453 + item.pid + " uid=" + item.uid + ": "
2454 + item.foregroundActivities);
2455 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2456 item.foregroundActivities);
2457 }
2458 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2459 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2460 + item.pid + " uid=" + item.uid + ": " + item.importance);
2461 observer.onImportanceChanged(item.pid, item.uid,
2462 item.importance);
2463 }
2464 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002465 } catch (RemoteException e) {
2466 }
2467 }
2468 }
2469 mProcessObservers.finishBroadcast();
2470 }
2471
2472 private void dispatchProcessDied(int pid, int uid) {
2473 int i = mProcessObservers.beginBroadcast();
2474 while (i > 0) {
2475 i--;
2476 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2477 if (observer != null) {
2478 try {
2479 observer.onProcessDied(pid, uid);
2480 } catch (RemoteException e) {
2481 }
2482 }
2483 }
2484 mProcessObservers.finishBroadcast();
2485 }
2486
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002488 final int N = mPendingActivityLaunches.size();
2489 if (N <= 0) {
2490 return;
2491 }
2492 for (int i=0; i<N; i++) {
2493 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002494 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002495 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002496 }
2497 mPendingActivityLaunches.clear();
2498 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002499
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002500 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002501 Intent intent, String resolvedType, IBinder resultTo,
2502 String resultWho, int requestCode, int startFlags,
2503 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002504 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002505 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002506 }
2507
2508 public final int startActivityAsUser(IApplicationThread caller,
2509 Intent intent, String resolvedType, IBinder resultTo,
2510 String resultWho, int requestCode, int startFlags,
2511 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002512 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002513 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002514 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002515 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002516 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2517 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002518 }
2519
2520 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002521 Intent intent, String resolvedType, IBinder resultTo,
2522 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002523 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002524 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002525 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002526 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002527 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002528 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002529 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002530 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002531 return res;
2532 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002533
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002534 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002535 Intent intent, String resolvedType, IBinder resultTo,
2536 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002537 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002538 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002539 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002540 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002541 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002542 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002543 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002544 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002545 }
2546
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002547 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002548 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002549 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002550 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002551 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002552 // Refuse possible leaked file descriptors
2553 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2554 throw new IllegalArgumentException("File descriptors passed in Intent");
2555 }
2556
2557 IIntentSender sender = intent.getTarget();
2558 if (!(sender instanceof PendingIntentRecord)) {
2559 throw new IllegalArgumentException("Bad PendingIntent object");
2560 }
2561
2562 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002563
2564 synchronized (this) {
2565 // If this is coming from the currently resumed activity, it is
2566 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 if (mMainStack.mResumedActivity != null
2568 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002569 Binder.getCallingUid()) {
2570 mAppSwitchesAllowedTime = 0;
2571 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002572 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002573 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2574 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002575 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002576 }
2577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002579 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 // Refuse possible leaked file descriptors
2581 if (intent != null && intent.hasFileDescriptors() == true) {
2582 throw new IllegalArgumentException("File descriptors passed in Intent");
2583 }
2584
2585 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002586 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2587 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002588 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 return false;
2590 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 if (r.app == null || r.app.thread == null) {
2592 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002593 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 return false;
2595 }
2596 intent = new Intent(intent);
2597 // The caller is not allowed to change the data.
2598 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2599 // And we are resetting to find the next component...
2600 intent.setComponent(null);
2601
2602 ActivityInfo aInfo = null;
2603 try {
2604 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002605 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002607 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002608 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609
2610 // Look for the original activity in the list...
2611 final int N = resolves != null ? resolves.size() : 0;
2612 for (int i=0; i<N; i++) {
2613 ResolveInfo rInfo = resolves.get(i);
2614 if (rInfo.activityInfo.packageName.equals(r.packageName)
2615 && rInfo.activityInfo.name.equals(r.info.name)) {
2616 // We found the current one... the next matching is
2617 // after it.
2618 i++;
2619 if (i<N) {
2620 aInfo = resolves.get(i).activityInfo;
2621 }
2622 break;
2623 }
2624 }
2625 } catch (RemoteException e) {
2626 }
2627
2628 if (aInfo == null) {
2629 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002630 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 return false;
2632 }
2633
2634 intent.setComponent(new ComponentName(
2635 aInfo.applicationInfo.packageName, aInfo.name));
2636 intent.setFlags(intent.getFlags()&~(
2637 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2638 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2639 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2640 Intent.FLAG_ACTIVITY_NEW_TASK));
2641
2642 // Okay now we need to start the new activity, replacing the
2643 // currently running activity. This is a little tricky because
2644 // we want to start the new one as if the current one is finished,
2645 // but not finish the current one first so that there is no flicker.
2646 // And thus...
2647 final boolean wasFinishing = r.finishing;
2648 r.finishing = true;
2649
2650 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002651 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 final String resultWho = r.resultWho;
2653 final int requestCode = r.requestCode;
2654 r.resultTo = null;
2655 if (resultTo != null) {
2656 resultTo.removeResultsLocked(r, resultWho, requestCode);
2657 }
2658
2659 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002660 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002661 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2662 resultWho, requestCode, -1, r.launchedFromUid, 0,
2663 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 Binder.restoreCallingIdentity(origId);
2665
2666 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002667 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 return false;
2669 }
2670 return true;
2671 }
2672 }
2673
Dianne Hackborn41203752012-08-31 14:05:51 -07002674 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002676 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2677
Dianne Hackborn139748f2012-09-24 11:36:57 -07002678 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002679 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680
Amith Yamasani742a6712011-05-04 14:49:28 -07002681 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002682 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002683 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002684 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002685 }
2686
2687 public final int startActivities(IApplicationThread caller,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002688 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2689 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002690 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002691 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002692 false, true, "startActivity", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002693 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002694 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002695 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002696 }
2697
Dianne Hackborn41203752012-08-31 14:05:51 -07002698 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002699 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002700 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002701
Dianne Hackborn139748f2012-09-24 11:36:57 -07002702 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002703 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002704 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002705 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002706 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002709 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002710 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002711 // Quick case: check if the top-most recent task is the same.
2712 if (N > 0 && mRecentTasks.get(0) == task) {
2713 return;
2714 }
2715 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 for (int i=0; i<N; i++) {
2717 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002718 if (task.userId == tr.userId
2719 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2720 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 mRecentTasks.remove(i);
2722 i--;
2723 N--;
2724 if (task.intent == null) {
2725 // If the new recent task we are adding is not fully
2726 // specified, then replace it with the existing recent task.
2727 task = tr;
2728 }
2729 }
2730 }
2731 if (N >= MAX_RECENT_TASKS) {
2732 mRecentTasks.remove(N-1);
2733 }
2734 mRecentTasks.add(0, task);
2735 }
2736
2737 public void setRequestedOrientation(IBinder token,
2738 int requestedOrientation) {
2739 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002740 ActivityRecord r = mMainStack.isInStackLocked(token);
2741 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 return;
2743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002745 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002746 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002747 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002748 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 if (config != null) {
2750 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002751 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002752 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002753 }
2754 }
2755 Binder.restoreCallingIdentity(origId);
2756 }
2757 }
2758
2759 public int getRequestedOrientation(IBinder token) {
2760 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002761 ActivityRecord r = mMainStack.isInStackLocked(token);
2762 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2764 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002765 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 }
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 /**
2770 * This is the internal entry point for handling Activity.finish().
2771 *
2772 * @param token The Binder token referencing the Activity we want to finish.
2773 * @param resultCode Result code, if any, from this Activity.
2774 * @param resultData Result data (Intent), if any, from this Activity.
2775 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002776 * @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 -08002777 */
2778 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2779 // Refuse possible leaked file descriptors
2780 if (resultData != null && resultData.hasFileDescriptors() == true) {
2781 throw new IllegalArgumentException("File descriptors passed in Intent");
2782 }
2783
2784 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002785 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002787 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788 if (next != null) {
2789 // ask watcher if this is allowed
2790 boolean resumeOK = true;
2791 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002792 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002794 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002795 }
2796
2797 if (!resumeOK) {
2798 return false;
2799 }
2800 }
2801 }
2802 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002803 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002804 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 Binder.restoreCallingIdentity(origId);
2806 return res;
2807 }
2808 }
2809
Dianne Hackborn860755f2010-06-03 18:47:52 -07002810 public final void finishHeavyWeightApp() {
2811 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2812 != PackageManager.PERMISSION_GRANTED) {
2813 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2814 + Binder.getCallingPid()
2815 + ", uid=" + Binder.getCallingUid()
2816 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2817 Slog.w(TAG, msg);
2818 throw new SecurityException(msg);
2819 }
2820
2821 synchronized(this) {
2822 if (mHeavyWeightProcess == null) {
2823 return;
2824 }
2825
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002826 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002827 mHeavyWeightProcess.activities);
2828 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002829 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002830 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002831 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002832 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002834 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002835 }
2836 }
2837 }
2838
Dianne Hackborn41203752012-08-31 14:05:51 -07002839 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2840 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002841 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002842 }
2843 }
2844
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002845 public void crashApplication(int uid, int initialPid, String packageName,
2846 String message) {
2847 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2848 != PackageManager.PERMISSION_GRANTED) {
2849 String msg = "Permission Denial: crashApplication() from pid="
2850 + Binder.getCallingPid()
2851 + ", uid=" + Binder.getCallingUid()
2852 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2853 Slog.w(TAG, msg);
2854 throw new SecurityException(msg);
2855 }
2856
2857 synchronized(this) {
2858 ProcessRecord proc = null;
2859
2860 // Figure out which process to kill. We don't trust that initialPid
2861 // still has any relation to current pids, so must scan through the
2862 // list.
2863 synchronized (mPidsSelfLocked) {
2864 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2865 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002866 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002867 continue;
2868 }
2869 if (p.pid == initialPid) {
2870 proc = p;
2871 break;
2872 }
2873 for (String str : p.pkgList) {
2874 if (str.equals(packageName)) {
2875 proc = p;
2876 }
2877 }
2878 }
2879 }
2880
2881 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002882 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002883 + " initialPid=" + initialPid
2884 + " packageName=" + packageName);
2885 return;
2886 }
2887
2888 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002889 if (proc.pid == Process.myPid()) {
2890 Log.w(TAG, "crashApplication: trying to crash self!");
2891 return;
2892 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002893 long ident = Binder.clearCallingIdentity();
2894 try {
2895 proc.thread.scheduleCrash(message);
2896 } catch (RemoteException e) {
2897 }
2898 Binder.restoreCallingIdentity(ident);
2899 }
2900 }
2901 }
2902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 public final void finishSubActivity(IBinder token, String resultWho,
2904 int requestCode) {
2905 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002907 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 Binder.restoreCallingIdentity(origId);
2909 }
2910 }
2911
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002912 public boolean finishActivityAffinity(IBinder token) {
2913 synchronized(this) {
2914 final long origId = Binder.clearCallingIdentity();
2915 boolean res = mMainStack.finishActivityAffinityLocked(token);
2916 Binder.restoreCallingIdentity(origId);
2917 return res;
2918 }
2919 }
2920
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002921 public boolean willActivityBeVisible(IBinder token) {
2922 synchronized(this) {
2923 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002924 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2925 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002926 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002927 return true;
2928 }
2929 if (r.fullscreen && !r.finishing) {
2930 return false;
2931 }
2932 }
2933 return true;
2934 }
2935 }
2936
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002937 public void overridePendingTransition(IBinder token, String packageName,
2938 int enterAnim, int exitAnim) {
2939 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002940 ActivityRecord self = mMainStack.isInStackLocked(token);
2941 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002942 return;
2943 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002944
2945 final long origId = Binder.clearCallingIdentity();
2946
2947 if (self.state == ActivityState.RESUMED
2948 || self.state == ActivityState.PAUSING) {
2949 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002950 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002951 }
2952
2953 Binder.restoreCallingIdentity(origId);
2954 }
2955 }
2956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 * Main function for removing an existing process from the activity manager
2959 * as a result of that process going away. Clears out all connections
2960 * to the process.
2961 */
2962 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002963 boolean restarting, boolean allowRestart) {
2964 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002966 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 }
2968
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002969 if (mProfileProc == app) {
2970 clearProfilerLocked();
2971 }
2972
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002974 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002975 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2976 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002977 mMainStack.mPausingActivity = null;
2978 }
2979 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2980 mMainStack.mLastPausedActivity = null;
2981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982
2983 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002984 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985
2986 app.activities.clear();
2987
2988 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002989 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 + " running instrumentation " + app.instrumentationClass);
2991 Bundle info = new Bundle();
2992 info.putString("shortMsg", "Process crashed.");
2993 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2994 }
2995
2996 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002997 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 // If there was nothing to resume, and we are not already
2999 // restarting this process, but there is a visible activity that
3000 // is hosted by the process... then make sure all visible
3001 // activities are running, taking care of restarting this
3002 // process.
3003 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 }
3006 }
3007 }
3008 }
3009
3010 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3011 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003013 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3014 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3016 return i;
3017 }
3018 }
3019 return -1;
3020 }
3021
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003022 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023 IApplicationThread thread) {
3024 if (thread == null) {
3025 return null;
3026 }
3027
3028 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003029 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
3031
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003032 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 IApplicationThread thread) {
3034
3035 mProcDeaths[0]++;
3036
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003037 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3038 synchronized (stats) {
3039 stats.noteProcessDiedLocked(app.info.uid, pid);
3040 }
3041
Magnus Edlund7bb25812010-02-24 15:45:06 +01003042 // Clean up already done if the process has been re-started.
3043 if (app.pid == pid && app.thread != null &&
3044 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003045 if (!app.killedBackground) {
3046 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3047 + ") has died.");
3048 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003049 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003050 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 TAG, "Dying app: " + app + ", pid: " + pid
3052 + ", thread: " + thread.asBinder());
3053 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003054 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055
3056 if (doLowMem) {
3057 // If there are no longer any background processes running,
3058 // and the app that died was not running instrumentation,
3059 // then tell everyone we are now low on memory.
3060 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003061 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3062 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003063 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 haveBg = true;
3065 break;
3066 }
3067 }
3068
3069 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003070 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003071 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003072 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3073 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003074 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003075 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3076 // The low memory report is overriding any current
3077 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003078 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003079 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003080 rec.lastRequestedGc = 0;
3081 } else {
3082 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003084 rec.reportLowMemory = true;
3085 rec.lastLowMemory = now;
3086 mProcessesToGc.remove(rec);
3087 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
3089 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003090 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003091 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
3093 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003094 } else if (app.pid != pid) {
3095 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003096 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003097 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003098 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003099 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003100 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 + thread.asBinder());
3102 }
3103 }
3104
Dan Egnor42471dd2010-01-07 17:25:22 -08003105 /**
3106 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003107 * @param clearTraces causes the dump file to be erased prior to the new
3108 * traces being written, if true; when false, the new traces will be
3109 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003110 * @param firstPids of dalvik VM processes to dump stack traces for first
3111 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003112 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003113 * @return file containing stack traces, or null if no dump file is configured
3114 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003115 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003116 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003117 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3118 if (tracesPath == null || tracesPath.length() == 0) {
3119 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003121
3122 File tracesFile = new File(tracesPath);
3123 try {
3124 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003125 if (!tracesDir.exists()) {
3126 tracesFile.mkdirs();
3127 if (!SELinux.restorecon(tracesDir)) {
3128 return null;
3129 }
3130 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003131 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3132
Christopher Tate6ee412d2010-05-28 12:01:56 -07003133 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003134 tracesFile.createNewFile();
3135 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3136 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003137 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003138 return null;
3139 }
3140
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003141 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003142 return tracesFile;
3143 }
3144
3145 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003146 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003147 // Use a FileObserver to detect when traces finish writing.
3148 // The order of traces is considered important to maintain for legibility.
3149 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3150 public synchronized void onEvent(int event, String path) { notify(); }
3151 };
3152
3153 try {
3154 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003155
3156 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003157 if (firstPids != null) {
3158 try {
3159 int num = firstPids.size();
3160 for (int i = 0; i < num; i++) {
3161 synchronized (observer) {
3162 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3163 observer.wait(200); // Wait for write-close, give up after 200msec
3164 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003165 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003166 } catch (InterruptedException e) {
3167 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003168 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003169 }
3170
3171 // Next measure CPU usage.
3172 if (processStats != null) {
3173 processStats.init();
3174 System.gc();
3175 processStats.update();
3176 try {
3177 synchronized (processStats) {
3178 processStats.wait(500); // measure over 1/2 second.
3179 }
3180 } catch (InterruptedException e) {
3181 }
3182 processStats.update();
3183
3184 // We'll take the stack crawls of just the top apps using CPU.
3185 final int N = processStats.countWorkingStats();
3186 int numProcs = 0;
3187 for (int i=0; i<N && numProcs<5; i++) {
3188 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3189 if (lastPids.indexOfKey(stats.pid) >= 0) {
3190 numProcs++;
3191 try {
3192 synchronized (observer) {
3193 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3194 observer.wait(200); // Wait for write-close, give up after 200msec
3195 }
3196 } catch (InterruptedException e) {
3197 Log.wtf(TAG, e);
3198 }
3199
3200 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003201 }
3202 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003203
Dan Egnor42471dd2010-01-07 17:25:22 -08003204 } finally {
3205 observer.stopWatching();
3206 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003207
3208 if (nativeProcs != null) {
3209 int[] pids = Process.getPidsForCommands(nativeProcs);
3210 if (pids != null) {
3211 for (int pid : pids) {
3212 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3213 }
3214 }
3215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 }
3217
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003218 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003219 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003220 return;
3221 }
3222 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3223 if (tracesPath == null || tracesPath.length() == 0) {
3224 return;
3225 }
3226
3227 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3228 StrictMode.allowThreadDiskWrites();
3229 try {
3230 final File tracesFile = new File(tracesPath);
3231 final File tracesDir = tracesFile.getParentFile();
3232 final File tracesTmp = new File(tracesDir, "__tmp__");
3233 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003234 if (!tracesDir.exists()) {
3235 tracesFile.mkdirs();
3236 if (!SELinux.restorecon(tracesDir.getPath())) {
3237 return;
3238 }
3239 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003240 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3241
3242 if (tracesFile.exists()) {
3243 tracesTmp.delete();
3244 tracesFile.renameTo(tracesTmp);
3245 }
3246 StringBuilder sb = new StringBuilder();
3247 Time tobj = new Time();
3248 tobj.set(System.currentTimeMillis());
3249 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3250 sb.append(": ");
3251 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3252 sb.append(" since ");
3253 sb.append(msg);
3254 FileOutputStream fos = new FileOutputStream(tracesFile);
3255 fos.write(sb.toString().getBytes());
3256 if (app == null) {
3257 fos.write("\n*** No application process!".getBytes());
3258 }
3259 fos.close();
3260 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3261 } catch (IOException e) {
3262 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3263 return;
3264 }
3265
3266 if (app != null) {
3267 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3268 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003269 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003270 }
3271
3272 File lastTracesFile = null;
3273 File curTracesFile = null;
3274 for (int i=9; i>=0; i--) {
3275 String name = String.format("slow%02d.txt", i);
3276 curTracesFile = new File(tracesDir, name);
3277 if (curTracesFile.exists()) {
3278 if (lastTracesFile != null) {
3279 curTracesFile.renameTo(lastTracesFile);
3280 } else {
3281 curTracesFile.delete();
3282 }
3283 }
3284 lastTracesFile = curTracesFile;
3285 }
3286 tracesFile.renameTo(curTracesFile);
3287 if (tracesTmp.exists()) {
3288 tracesTmp.renameTo(tracesFile);
3289 }
3290 } finally {
3291 StrictMode.setThreadPolicy(oldPolicy);
3292 }
3293 }
3294
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003295 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003296 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003297 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3298 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3299
Dianne Hackborn287952c2010-09-22 22:34:31 -07003300 if (mController != null) {
3301 try {
3302 // 0 == continue, -1 = kill process immediately
3303 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3304 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3305 } catch (RemoteException e) {
3306 mController = null;
3307 }
3308 }
3309
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003310 long anrTime = SystemClock.uptimeMillis();
3311 if (MONITOR_CPU_USAGE) {
3312 updateCpuStatsNow();
3313 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003314
3315 synchronized (this) {
3316 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3317 if (mShuttingDown) {
3318 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3319 return;
3320 } else if (app.notResponding) {
3321 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3322 return;
3323 } else if (app.crashing) {
3324 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3325 return;
3326 }
3327
3328 // In case we come through here for the same app before completing
3329 // this one, mark as anring now so we will bail out.
3330 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003331
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003332 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003333 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3334 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003335
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003336 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003337 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003338
3339 int parentPid = app.pid;
3340 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003341 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003342
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003343 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003344
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003345 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3346 ProcessRecord r = mLruProcesses.get(i);
3347 if (r != null && r.thread != null) {
3348 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003349 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3350 if (r.persistent) {
3351 firstPids.add(pid);
3352 } else {
3353 lastPids.put(pid, Boolean.TRUE);
3354 }
3355 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 }
3358 }
3359
Dan Egnor42471dd2010-01-07 17:25:22 -08003360 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003361 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003362 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003363 info.append("ANR in ").append(app.processName);
3364 if (activity != null && activity.shortComponentName != null) {
3365 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003366 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003367 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003369 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003371 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003372 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374
Dianne Hackborn287952c2010-09-22 22:34:31 -07003375 final ProcessStats processStats = new ProcessStats(true);
3376
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003377 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003378
Dan Egnor42471dd2010-01-07 17:25:22 -08003379 String cpuInfo = null;
3380 if (MONITOR_CPU_USAGE) {
3381 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003382 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003383 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003384 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003385 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003386 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
3388
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003389 info.append(processStats.printCurrentState(anrTime));
3390
Joe Onorato8a9b2202010-02-26 18:56:32 -08003391 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003392 if (tracesFile == null) {
3393 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3394 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3395 }
3396
Jeff Sharkeya353d262011-10-28 11:12:06 -07003397 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3398 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003399
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003400 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003402 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3403 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003405 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3406 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 }
3408 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003409 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
3411 }
3412
Dan Egnor42471dd2010-01-07 17:25:22 -08003413 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3414 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3415 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003416
3417 synchronized (this) {
3418 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003419 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003420 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003421 app.processName, app.setAdj, "background ANR");
3422 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003423 return;
3424 }
3425
3426 // Set the app's notResponding state, and look up the errorReportReceiver
3427 makeAppNotRespondingLocked(app,
3428 activity != null ? activity.shortComponentName : null,
3429 annotation != null ? "ANR " + annotation : "ANR",
3430 info.toString());
3431
3432 // Bring up the infamous App Not Responding dialog
3433 Message msg = Message.obtain();
3434 HashMap map = new HashMap();
3435 msg.what = SHOW_NOT_RESPONDING_MSG;
3436 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003437 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003438 map.put("app", app);
3439 if (activity != null) {
3440 map.put("activity", activity);
3441 }
3442
3443 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 }
3446
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003447 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3448 if (!mLaunchWarningShown) {
3449 mLaunchWarningShown = true;
3450 mHandler.post(new Runnable() {
3451 @Override
3452 public void run() {
3453 synchronized (ActivityManagerService.this) {
3454 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3455 d.show();
3456 mHandler.postDelayed(new Runnable() {
3457 @Override
3458 public void run() {
3459 synchronized (ActivityManagerService.this) {
3460 d.dismiss();
3461 mLaunchWarningShown = false;
3462 }
3463 }
3464 }, 4000);
3465 }
3466 }
3467 });
3468 }
3469 }
3470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003472 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003473 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 int uid = Binder.getCallingUid();
3475 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003476 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003477 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 long callingId = Binder.clearCallingIdentity();
3479 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003480 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 int pkgUid = -1;
3482 synchronized(this) {
3483 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003484 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 } catch (RemoteException e) {
3486 }
3487 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003488 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 return false;
3490 }
3491 if (uid == pkgUid || checkComponentPermission(
3492 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003493 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003495 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 } else {
3497 throw new SecurityException(pid+" does not have permission:"+
3498 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3499 "for process:"+packageName);
3500 }
3501 }
3502
3503 try {
3504 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003505 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3507 Uri.fromParts("package", packageName, null));
3508 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003509 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003510 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 } catch (RemoteException e) {
3512 }
3513 } finally {
3514 Binder.restoreCallingIdentity(callingId);
3515 }
3516 return true;
3517 }
3518
Dianne Hackborn1676c852012-09-10 14:52:30 -07003519 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003520 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3521 != PackageManager.PERMISSION_GRANTED &&
3522 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3523 != PackageManager.PERMISSION_GRANTED) {
3524 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 + Binder.getCallingPid()
3526 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003527 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003528 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 throw new SecurityException(msg);
3530 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003531
Dianne Hackborn139748f2012-09-24 11:36:57 -07003532 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003533 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 long callingId = Binder.clearCallingIdentity();
3535 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003536 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003538 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003540 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 } catch (RemoteException e) {
3542 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003543 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003544 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 return;
3546 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003547 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003548 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3549 }
3550 } finally {
3551 Binder.restoreCallingIdentity(callingId);
3552 }
3553 }
3554
3555 public void killAllBackgroundProcesses() {
3556 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3557 != PackageManager.PERMISSION_GRANTED) {
3558 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3559 + Binder.getCallingPid()
3560 + ", uid=" + Binder.getCallingUid()
3561 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3562 Slog.w(TAG, msg);
3563 throw new SecurityException(msg);
3564 }
3565
3566 long callingId = Binder.clearCallingIdentity();
3567 try {
3568 synchronized(this) {
3569 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3570 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3571 final int NA = apps.size();
3572 for (int ia=0; ia<NA; ia++) {
3573 ProcessRecord app = apps.valueAt(ia);
3574 if (app.persistent) {
3575 // we don't kill persistent processes
3576 continue;
3577 }
3578 if (app.removed) {
3579 procs.add(app);
3580 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3581 app.removed = true;
3582 procs.add(app);
3583 }
3584 }
3585 }
3586
3587 int N = procs.size();
3588 for (int i=0; i<N; i++) {
3589 removeProcessLocked(procs.get(i), false, true, "kill all background");
3590 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003591 }
3592 } finally {
3593 Binder.restoreCallingIdentity(callingId);
3594 }
3595 }
3596
Dianne Hackborn1676c852012-09-10 14:52:30 -07003597 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003598 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3599 != PackageManager.PERMISSION_GRANTED) {
3600 String msg = "Permission Denial: forceStopPackage() from pid="
3601 + Binder.getCallingPid()
3602 + ", uid=" + Binder.getCallingUid()
3603 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003604 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003605 throw new SecurityException(msg);
3606 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003607 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003608 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003609 long callingId = Binder.clearCallingIdentity();
3610 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003611 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003612 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003613 int[] users = userId == UserHandle.USER_ALL
3614 ? getUsersLocked() : new int[] { userId };
3615 for (int user : users) {
3616 int pkgUid = -1;
3617 try {
3618 pkgUid = pm.getPackageUid(packageName, user);
3619 } catch (RemoteException e) {
3620 }
3621 if (pkgUid == -1) {
3622 Slog.w(TAG, "Invalid packageName: " + packageName);
3623 continue;
3624 }
3625 try {
3626 pm.setPackageStoppedState(packageName, true, user);
3627 } catch (RemoteException e) {
3628 } catch (IllegalArgumentException e) {
3629 Slog.w(TAG, "Failed trying to unstop package "
3630 + packageName + ": " + e);
3631 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003632 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003633 forceStopPackageLocked(packageName, pkgUid);
3634 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 }
3637 } finally {
3638 Binder.restoreCallingIdentity(callingId);
3639 }
3640 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003641
3642 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003643 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003644 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003645 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003646 if (pkg == null) {
3647 return;
3648 }
3649 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003650 if (appid < 0) {
3651 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003652 return;
3653 }
3654 int callerUid = Binder.getCallingUid();
3655 // Only the system server can kill an application
3656 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003657 // Post an aysnc message to kill the application
3658 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003659 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003660 msg.arg2 = 0;
3661 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003662 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003663 } else {
3664 throw new SecurityException(callerUid + " cannot kill pkg: " +
3665 pkg);
3666 }
3667 }
3668
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003669 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003670 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003671
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003672 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003673 final int uid = Binder.getCallingUid();
3674 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003675 try {
3676 synchronized (this) {
3677 // Only allow this from foreground processes, so that background
3678 // applications can't abuse it to prevent system UI from being shown.
3679 if (uid >= Process.FIRST_APPLICATION_UID) {
3680 ProcessRecord proc;
3681 synchronized (mPidsSelfLocked) {
3682 proc = mPidsSelfLocked.get(pid);
3683 }
3684 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3685 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3686 + " from background process " + proc);
3687 return;
3688 }
3689 }
3690 closeSystemDialogsLocked(reason);
3691 }
3692 } finally {
3693 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003694 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003695 }
3696
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003697 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003698 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003699 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3700 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003701 if (reason != null) {
3702 intent.putExtra("reason", reason);
3703 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003704 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003705
Dianne Hackborne302a162012-05-15 14:58:32 -07003706 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3707 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003708 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003709 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003710 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003711 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003712 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003713
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003714 broadcastIntentLocked(null, null, intent, null,
3715 null, 0, null, null, null, false, false, -1,
3716 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003717 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003718
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003719 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003720 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003721 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003722 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3723 for (int i=pids.length-1; i>=0; i--) {
3724 infos[i] = new Debug.MemoryInfo();
3725 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003726 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003727 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003728 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003729
Dianne Hackbornb437e092011-08-05 17:50:29 -07003730 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003731 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003732 long[] pss = new long[pids.length];
3733 for (int i=pids.length-1; i>=0; i--) {
3734 pss[i] = Debug.getPss(pids[i]);
3735 }
3736 return pss;
3737 }
3738
Christopher Tate5e1ab332009-09-01 20:32:49 -07003739 public void killApplicationProcess(String processName, int uid) {
3740 if (processName == null) {
3741 return;
3742 }
3743
3744 int callerUid = Binder.getCallingUid();
3745 // Only the system server can kill an application
3746 if (callerUid == Process.SYSTEM_UID) {
3747 synchronized (this) {
3748 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003749 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003750 try {
3751 app.thread.scheduleSuicide();
3752 } catch (RemoteException e) {
3753 // If the other end already died, then our work here is done.
3754 }
3755 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003756 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003757 + processName + " / " + uid);
3758 }
3759 }
3760 } else {
3761 throw new SecurityException(callerUid + " cannot kill app process: " +
3762 processName);
3763 }
3764 }
3765
Dianne Hackborn03abb812010-01-04 18:43:19 -08003766 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003767 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3768 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3770 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003771 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003772 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3773 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003776 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 broadcastIntentLocked(null, null, intent,
3778 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003779 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003780 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003781 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003782
3783 private void forceStopUserLocked(int userId) {
3784 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3785 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003786 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3787 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003788 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3789 broadcastIntentLocked(null, null, intent,
3790 null, null, 0, null, null, null,
3791 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003792 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003793 }
3794
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003795 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003796 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3797 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003798 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799
Dianne Hackborn03abb812010-01-04 18:43:19 -08003800 // Remove all processes this package may have touched: all with the
3801 // same UID (except for the system or root user), and all whose name
3802 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003803 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003804 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3805 final int NA = apps.size();
3806 for (int ia=0; ia<NA; ia++) {
3807 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003808 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003809 // we don't kill persistent processes
3810 continue;
3811 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003812 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003813 if (doit) {
3814 procs.add(app);
3815 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003816 continue;
3817 }
3818
3819 // Skip process if it doesn't meet our oom adj requirement.
3820 if (app.setAdj < minOomAdj) {
3821 continue;
3822 }
3823
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003824 // If no package is specified, we call all processes under the
3825 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003826 if (packageName == null) {
3827 if (app.userId != userId) {
3828 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003829 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003830 // Package has been specified, we want to hit all processes
3831 // that match it. We need to qualify this by the processes
3832 // that are running under the specified app and user ID.
3833 } else {
3834 if (UserHandle.getAppId(app.uid) != appId) {
3835 continue;
3836 }
3837 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3838 continue;
3839 }
3840 if (!app.pkgList.contains(packageName)) {
3841 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003842 }
3843 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003844
3845 // Process has passed all conditions, kill it!
3846 if (!doit) {
3847 return true;
3848 }
3849 app.removed = true;
3850 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003851 }
3852 }
3853
3854 int N = procs.size();
3855 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003856 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003857 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003858 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003859 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003860
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003861 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003862 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003863 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003864 int i;
3865 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003867 if (userId == UserHandle.USER_ALL && name == null) {
3868 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3869 }
3870
3871 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003873 appId = UserHandle.getAppId(
3874 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 } catch (RemoteException e) {
3876 }
3877 }
3878
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003879 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003880 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003881 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3882 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003883 } else {
3884 Slog.i(TAG, "Force stopping user " + userId);
3885 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003886
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003887 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3888 while (badApps.hasNext()) {
3889 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003890 for (i=ba.size()-1; i>=0; i--) {
3891 boolean remove = false;
3892 final int entUid = ba.keyAt(i);
3893 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003894 if (userId == UserHandle.USER_ALL) {
3895 if (UserHandle.getAppId(entUid) == appId) {
3896 remove = true;
3897 }
3898 } else {
3899 if (entUid == UserHandle.getUid(userId, appId)) {
3900 remove = true;
3901 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003902 }
3903 } else if (UserHandle.getUserId(entUid) == userId) {
3904 remove = true;
3905 }
3906 if (remove) {
3907 ba.removeAt(i);
3908 }
3909 }
3910 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003911 badApps.remove();
3912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 }
3914 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003915
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003916 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003917 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003918 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003920 TaskRecord lastTask = null;
3921 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003922 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003923 final boolean samePackage = r.packageName.equals(name)
3924 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003925 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003926 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003927 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003928 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003929 if (r.finishing) {
3930 // If this activity is just finishing, then it is not
3931 // interesting as far as something to stop.
3932 continue;
3933 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003934 return true;
3935 }
3936 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003937 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003938 if (samePackage) {
3939 if (r.app != null) {
3940 r.app.removed = true;
3941 }
3942 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003944 lastTask = r.task;
3945 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003946 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003947 i--;
3948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
3950 }
3951
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003952 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3953 if (!doit) {
3954 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003956 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003958
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003959 if (name == null) {
3960 // Remove all sticky broadcasts from this user.
3961 mStickyBroadcasts.remove(userId);
3962 }
3963
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003964 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003965 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3966 userId, providers)) {
3967 if (!doit) {
3968 return true;
3969 }
3970 didSomething = true;
3971 }
3972 N = providers.size();
3973 for (i=0; i<N; i++) {
3974 removeDyingProviderLocked(null, providers.get(i), true);
3975 }
3976
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003977 if (name == null) {
3978 // Remove pending intents. For now we only do this when force
3979 // stopping users, because we have some problems when doing this
3980 // for packages -- app widgets are not currently cleaned up for
3981 // such packages, so they can be left with bad pending intents.
3982 if (mIntentSenderRecords.size() > 0) {
3983 Iterator<WeakReference<PendingIntentRecord>> it
3984 = mIntentSenderRecords.values().iterator();
3985 while (it.hasNext()) {
3986 WeakReference<PendingIntentRecord> wpir = it.next();
3987 if (wpir == null) {
3988 it.remove();
3989 continue;
3990 }
3991 PendingIntentRecord pir = wpir.get();
3992 if (pir == null) {
3993 it.remove();
3994 continue;
3995 }
3996 if (name == null) {
3997 // Stopping user, remove all objects for the user.
3998 if (pir.key.userId != userId) {
3999 // Not the same user, skip it.
4000 continue;
4001 }
4002 } else {
4003 if (UserHandle.getAppId(pir.uid) != appId) {
4004 // Different app id, skip it.
4005 continue;
4006 }
4007 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
4008 // Different user, skip it.
4009 continue;
4010 }
4011 if (!pir.key.packageName.equals(name)) {
4012 // Different package, skip it.
4013 continue;
4014 }
4015 }
4016 if (!doit) {
4017 return true;
4018 }
4019 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004020 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004021 pir.canceled = true;
4022 if (pir.key.activity != null) {
4023 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004024 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004025 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004026 }
4027 }
4028
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004029 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004030 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004031 AttributeCache ac = AttributeCache.instance();
4032 if (ac != null) {
4033 ac.removePackage(name);
4034 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004035 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004036 if (mBooted) {
4037 mMainStack.resumeTopActivityLocked(null);
4038 mMainStack.scheduleIdleLocked();
4039 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004040 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004041
4042 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 }
4044
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004045 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004046 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004048 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004049 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004050 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 + "/" + uid + ")");
4052
4053 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004054 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004055 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004056 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4057 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004058 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 boolean needRestart = false;
4061 if (app.pid > 0 && app.pid != MY_PID) {
4062 int pid = app.pid;
4063 synchronized (mPidsSelfLocked) {
4064 mPidsSelfLocked.remove(pid);
4065 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4066 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004067 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004068 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004069 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004070 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004072 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004074 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 } else {
4076 needRestart = true;
4077 }
4078 }
4079 } else {
4080 mRemovedProcesses.add(app);
4081 }
4082
4083 return needRestart;
4084 }
4085
4086 private final void processStartTimedOutLocked(ProcessRecord app) {
4087 final int pid = app.pid;
4088 boolean gone = false;
4089 synchronized (mPidsSelfLocked) {
4090 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4091 if (knownApp != null && knownApp.thread == null) {
4092 mPidsSelfLocked.remove(pid);
4093 gone = true;
4094 }
4095 }
4096
4097 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004098 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004099 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4100 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004101 mProcessNames.remove(app.processName, app.uid);
4102 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004103 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004104 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4105 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004106 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004107 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004108 // Take care of any launching providers waiting for this process.
4109 checkAppInLaunchingProvidersLocked(app, true);
4110 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004111 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004112 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004113 app.processName, app.setAdj, "start timeout");
4114 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004115 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004116 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004117 try {
4118 IBackupManager bm = IBackupManager.Stub.asInterface(
4119 ServiceManager.getService(Context.BACKUP_SERVICE));
4120 bm.agentDisconnected(app.info.packageName);
4121 } catch (RemoteException e) {
4122 // Can't happen; the backup manager is local
4123 }
4124 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004125 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004127 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 }
4132 }
4133
4134 private final boolean attachApplicationLocked(IApplicationThread thread,
4135 int pid) {
4136
4137 // Find the application record that is being attached... either via
4138 // the pid if we are running in multiple processes, or just pull the
4139 // next app record if we are emulating process with anonymous threads.
4140 ProcessRecord app;
4141 if (pid != MY_PID && pid >= 0) {
4142 synchronized (mPidsSelfLocked) {
4143 app = mPidsSelfLocked.get(pid);
4144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 } else {
4146 app = null;
4147 }
4148
4149 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004150 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004152 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004154 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 } else {
4156 try {
4157 thread.scheduleExit();
4158 } catch (Exception e) {
4159 // Ignore exceptions.
4160 }
4161 }
4162 return false;
4163 }
4164
4165 // If this application record is still attached to a previous
4166 // process, clean it up now.
4167 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004168 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
4171 // Tell the process all about itself.
4172
Joe Onorato8a9b2202010-02-26 18:56:32 -08004173 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 TAG, "Binding process pid " + pid + " to record " + app);
4175
4176 String processName = app.processName;
4177 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004178 AppDeathRecipient adr = new AppDeathRecipient(
4179 app, pid, thread);
4180 thread.asBinder().linkToDeath(adr, 0);
4181 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 } catch (RemoteException e) {
4183 app.resetPackageList();
4184 startProcessLocked(app, "link fail", processName);
4185 return false;
4186 }
4187
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004188 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189
4190 app.thread = thread;
4191 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004192 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4193 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 app.forcingToForeground = null;
4195 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004196 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 app.debugging = false;
4198
4199 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4200
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004201 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004202 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004204 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004205 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004206 }
4207
Joe Onorato8a9b2202010-02-26 18:56:32 -08004208 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 TAG, "New app record " + app
4210 + " thread=" + thread.asBinder() + " pid=" + pid);
4211 try {
4212 int testMode = IApplicationThread.DEBUG_OFF;
4213 if (mDebugApp != null && mDebugApp.equals(processName)) {
4214 testMode = mWaitForDebugger
4215 ? IApplicationThread.DEBUG_WAIT
4216 : IApplicationThread.DEBUG_ON;
4217 app.debugging = true;
4218 if (mDebugTransient) {
4219 mDebugApp = mOrigDebugApp;
4220 mWaitForDebugger = mOrigWaitForDebugger;
4221 }
4222 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004223 String profileFile = app.instrumentationProfileFile;
4224 ParcelFileDescriptor profileFd = null;
4225 boolean profileAutoStop = false;
4226 if (mProfileApp != null && mProfileApp.equals(processName)) {
4227 mProfileProc = app;
4228 profileFile = mProfileFile;
4229 profileFd = mProfileFd;
4230 profileAutoStop = mAutoStopProfiler;
4231 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004232 boolean enableOpenGlTrace = false;
4233 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4234 enableOpenGlTrace = true;
4235 mOpenGlTraceApp = null;
4236 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004237
Christopher Tate181fafa2009-05-14 11:12:14 -07004238 // If the app is being launched for restore or full backup, set it up specially
4239 boolean isRestrictedBackupMode = false;
4240 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4241 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004242 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004243 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4244 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004245
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004246 ensurePackageDexOpt(app.instrumentationInfo != null
4247 ? app.instrumentationInfo.packageName
4248 : app.info.packageName);
4249 if (app.instrumentationClass != null) {
4250 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004251 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004252 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004253 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004254 ApplicationInfo appInfo = app.instrumentationInfo != null
4255 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004256 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004257 if (profileFd != null) {
4258 profileFd = profileFd.dup();
4259 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004260 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004261 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004262 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4263 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004264 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004265 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004266 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004267 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 } catch (Exception e) {
4269 // todo: Yikes! What should we do? For now we will try to
4270 // start another process, but that could easily get us in
4271 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004272 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273
4274 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004275 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 startProcessLocked(app, "bind fail", processName);
4277 return false;
4278 }
4279
4280 // Remove this record from the list of starting applications.
4281 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004282 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4283 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 mProcessesOnHold.remove(app);
4285
4286 boolean badApp = false;
4287 boolean didSomething = false;
4288
4289 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004290 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004291 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004292 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 && processName.equals(hr.processName)) {
4294 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004295 if (mHeadless) {
4296 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4297 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 didSomething = true;
4299 }
4300 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004301 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 + hr.intent.getComponent().flattenToShortString(), e);
4303 badApp = true;
4304 }
4305 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004306 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 }
4308 }
4309
4310 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004311 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004313 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004314 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 badApp = true;
4316 }
4317 }
4318
Christopher Tatef46723b2012-01-26 14:19:24 -08004319 // Check if a next-broadcast receiver is in this process...
4320 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004322 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004323 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004324 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 }
4327 }
4328
Christopher Tate181fafa2009-05-14 11:12:14 -07004329 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004330 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004331 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004332 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004333 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004334 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4335 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4336 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004337 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004338 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004339 e.printStackTrace();
4340 }
4341 }
4342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004343 if (badApp) {
4344 // todo: Also need to kill application to deal with all
4345 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004346 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 return false;
4348 }
4349
4350 if (!didSomething) {
4351 updateOomAdjLocked();
4352 }
4353
4354 return true;
4355 }
4356
4357 public final void attachApplication(IApplicationThread thread) {
4358 synchronized (this) {
4359 int callingPid = Binder.getCallingPid();
4360 final long origId = Binder.clearCallingIdentity();
4361 attachApplicationLocked(thread, callingPid);
4362 Binder.restoreCallingIdentity(origId);
4363 }
4364 }
4365
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004366 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004368 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4369 if (stopProfiling) {
4370 synchronized (this) {
4371 if (mProfileProc == r.app) {
4372 if (mProfileFd != null) {
4373 try {
4374 mProfileFd.close();
4375 } catch (IOException e) {
4376 }
4377 clearProfilerLocked();
4378 }
4379 }
4380 }
4381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 Binder.restoreCallingIdentity(origId);
4383 }
4384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004385 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004386 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004387 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004389
4390 synchronized (this) {
4391 updateEventDispatchingLocked();
4392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394
Dianne Hackborn661cd522011-08-22 00:26:20 -07004395 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004396 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004397 mWindowManager.showBootMessage(msg, always);
4398 }
4399
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004400 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004401 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004402 final long token = Binder.clearCallingIdentity();
4403 try {
4404 synchronized (this) {
4405 if (mLockScreenShown) {
4406 mLockScreenShown = false;
4407 comeOutOfSleepIfNeededLocked();
4408 }
4409 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004410 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004411 } finally {
4412 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004413 }
4414 }
4415
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004416 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004417 IntentFilter pkgFilter = new IntentFilter();
4418 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4419 pkgFilter.addDataScheme("package");
4420 mContext.registerReceiver(new BroadcastReceiver() {
4421 @Override
4422 public void onReceive(Context context, Intent intent) {
4423 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4424 if (pkgs != null) {
4425 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004426 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004427 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4428 setResultCode(Activity.RESULT_OK);
4429 return;
4430 }
4431 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004432 }
4433 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004434 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004435 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004436
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004437 synchronized (this) {
4438 // Ensure that any processes we had put on hold are now started
4439 // up.
4440 final int NP = mProcessesOnHold.size();
4441 if (NP > 0) {
4442 ArrayList<ProcessRecord> procs =
4443 new ArrayList<ProcessRecord>(mProcessesOnHold);
4444 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004445 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4446 + procs.get(ip));
4447 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004448 }
4449 }
4450
4451 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004452 // Start looking for apps that are abusing wake locks.
4453 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004454 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004455 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004456 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004457 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004458 for (int i=0; i<mStartedUsers.size(); i++) {
4459 UserStartedState uss = mStartedUsers.valueAt(i);
4460 if (uss.mState == UserStartedState.STATE_BOOTING) {
4461 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004462 final int userId = mStartedUsers.keyAt(i);
4463 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4464 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4465 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004466 null, null, 0, null, null,
4467 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004468 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004469 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004470 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004471 }
4472 }
4473 }
4474
4475 final void ensureBootCompleted() {
4476 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004477 boolean enableScreen;
4478 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004479 booting = mBooting;
4480 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004481 enableScreen = !mBooted;
4482 mBooted = true;
4483 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004484
4485 if (booting) {
4486 finishBooting();
4487 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004488
4489 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004490 enableScreenAfterBoot();
4491 }
4492 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004493
4494 public final void activityResumed(IBinder token) {
4495 final long origId = Binder.clearCallingIdentity();
4496 mMainStack.activityResumed(token);
4497 Binder.restoreCallingIdentity(origId);
4498 }
4499
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004500 public final void activityPaused(IBinder token) {
4501 final long origId = Binder.clearCallingIdentity();
4502 mMainStack.activityPaused(token, false);
4503 Binder.restoreCallingIdentity(origId);
4504 }
4505
4506 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4507 CharSequence description) {
4508 if (localLOGV) Slog.v(
4509 TAG, "Activity stopped: token=" + token);
4510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004511 // Refuse possible leaked file descriptors
4512 if (icicle != null && icicle.hasFileDescriptors()) {
4513 throw new IllegalArgumentException("File descriptors passed in Bundle");
4514 }
4515
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004516 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517
4518 final long origId = Binder.clearCallingIdentity();
4519
4520 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004521 r = mMainStack.isInStackLocked(token);
4522 if (r != null) {
4523 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
4525 }
4526
4527 if (r != null) {
4528 sendPendingThumbnail(r, null, null, null, false);
4529 }
4530
4531 trimApplications();
4532
4533 Binder.restoreCallingIdentity(origId);
4534 }
4535
4536 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004537 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004538 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 }
4540
4541 public String getCallingPackage(IBinder token) {
4542 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004543 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004544 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 }
4546 }
4547
4548 public ComponentName getCallingActivity(IBinder token) {
4549 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004550 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 return r != null ? r.intent.getComponent() : null;
4552 }
4553 }
4554
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004555 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004556 ActivityRecord r = mMainStack.isInStackLocked(token);
4557 if (r == null) {
4558 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004560 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
4562
4563 public ComponentName getActivityClassForToken(IBinder token) {
4564 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004565 ActivityRecord r = mMainStack.isInStackLocked(token);
4566 if (r == null) {
4567 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004569 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 }
4571 }
4572
4573 public String getPackageForToken(IBinder token) {
4574 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004575 ActivityRecord r = mMainStack.isInStackLocked(token);
4576 if (r == null) {
4577 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004579 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581 }
4582
4583 public IIntentSender getIntentSender(int type,
4584 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004585 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004586 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004587 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004589 if (intents != null) {
4590 if (intents.length < 1) {
4591 throw new IllegalArgumentException("Intents array length must be >= 1");
4592 }
4593 for (int i=0; i<intents.length; i++) {
4594 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004595 if (intent != null) {
4596 if (intent.hasFileDescriptors()) {
4597 throw new IllegalArgumentException("File descriptors passed in Intent");
4598 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004599 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004600 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4601 throw new IllegalArgumentException(
4602 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4603 }
4604 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004605 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004606 }
4607 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004608 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004609 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004610 }
4611 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004612 if (options != null) {
4613 if (options.hasFileDescriptors()) {
4614 throw new IllegalArgumentException("File descriptors passed in options");
4615 }
4616 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004618 synchronized(this) {
4619 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004620 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004621 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004622 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004623 "getIntentSender", null);
4624 if (origUserId == UserHandle.USER_CURRENT) {
4625 // We don't want to evaluate this until the pending intent is
4626 // actually executed. However, we do want to always do the
4627 // security checking for it above.
4628 userId = UserHandle.USER_CURRENT;
4629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004631 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004632 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004633 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4634 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 String msg = "Permission Denial: getIntentSender() from pid="
4636 + Binder.getCallingPid()
4637 + ", uid=" + Binder.getCallingUid()
4638 + ", (need uid=" + uid + ")"
4639 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004640 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 throw new SecurityException(msg);
4642 }
4643 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004644
4645 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004646 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004648 } catch (RemoteException e) {
4649 throw new SecurityException(e);
4650 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004651 }
4652 }
4653
Dianne Hackborn41203752012-08-31 14:05:51 -07004654 IIntentSender getIntentSenderLocked(int type, String packageName,
4655 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004656 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4657 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004658 if (DEBUG_MU)
4659 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004660 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004661 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004662 activity = mMainStack.isInStackLocked(token);
4663 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004664 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004666 if (activity.finishing) {
4667 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004668 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004669 }
4670
4671 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4672 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4673 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4674 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4675 |PendingIntent.FLAG_UPDATE_CURRENT);
4676
4677 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4678 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004679 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004680 WeakReference<PendingIntentRecord> ref;
4681 ref = mIntentSenderRecords.get(key);
4682 PendingIntentRecord rec = ref != null ? ref.get() : null;
4683 if (rec != null) {
4684 if (!cancelCurrent) {
4685 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004686 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004687 rec.key.requestIntent.replaceExtras(intents != null ?
4688 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004689 }
4690 if (intents != null) {
4691 intents[intents.length-1] = rec.key.requestIntent;
4692 rec.key.allIntents = intents;
4693 rec.key.allResolvedTypes = resolvedTypes;
4694 } else {
4695 rec.key.allIntents = null;
4696 rec.key.allResolvedTypes = null;
4697 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 return rec;
4700 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004701 rec.canceled = true;
4702 mIntentSenderRecords.remove(key);
4703 }
4704 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 return rec;
4706 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004707 rec = new PendingIntentRecord(this, key, callingUid);
4708 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004709 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004710 if (activity.pendingResults == null) {
4711 activity.pendingResults
4712 = new HashSet<WeakReference<PendingIntentRecord>>();
4713 }
4714 activity.pendingResults.add(rec.ref);
4715 }
4716 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004717 }
4718
4719 public void cancelIntentSender(IIntentSender sender) {
4720 if (!(sender instanceof PendingIntentRecord)) {
4721 return;
4722 }
4723 synchronized(this) {
4724 PendingIntentRecord rec = (PendingIntentRecord)sender;
4725 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004726 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004727 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4728 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 String msg = "Permission Denial: cancelIntentSender() from pid="
4730 + Binder.getCallingPid()
4731 + ", uid=" + Binder.getCallingUid()
4732 + " is not allowed to cancel packges "
4733 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004734 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 throw new SecurityException(msg);
4736 }
4737 } catch (RemoteException e) {
4738 throw new SecurityException(e);
4739 }
4740 cancelIntentSenderLocked(rec, true);
4741 }
4742 }
4743
4744 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4745 rec.canceled = true;
4746 mIntentSenderRecords.remove(rec.key);
4747 if (cleanActivity && rec.key.activity != null) {
4748 rec.key.activity.pendingResults.remove(rec.ref);
4749 }
4750 }
4751
4752 public String getPackageForIntentSender(IIntentSender pendingResult) {
4753 if (!(pendingResult instanceof PendingIntentRecord)) {
4754 return null;
4755 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004756 try {
4757 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4758 return res.key.packageName;
4759 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 }
4761 return null;
4762 }
4763
Christopher Tatec4a07d12012-04-06 14:19:13 -07004764 public int getUidForIntentSender(IIntentSender sender) {
4765 if (sender instanceof PendingIntentRecord) {
4766 try {
4767 PendingIntentRecord res = (PendingIntentRecord)sender;
4768 return res.uid;
4769 } catch (ClassCastException e) {
4770 }
4771 }
4772 return -1;
4773 }
4774
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004775 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4776 if (!(pendingResult instanceof PendingIntentRecord)) {
4777 return false;
4778 }
4779 try {
4780 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4781 if (res.key.allIntents == null) {
4782 return false;
4783 }
4784 for (int i=0; i<res.key.allIntents.length; i++) {
4785 Intent intent = res.key.allIntents[i];
4786 if (intent.getPackage() != null && intent.getComponent() != null) {
4787 return false;
4788 }
4789 }
4790 return true;
4791 } catch (ClassCastException e) {
4792 }
4793 return false;
4794 }
4795
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004796 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4797 if (!(pendingResult instanceof PendingIntentRecord)) {
4798 return false;
4799 }
4800 try {
4801 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4802 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4803 return true;
4804 }
4805 return false;
4806 } catch (ClassCastException e) {
4807 }
4808 return false;
4809 }
4810
Dianne Hackborn81038902012-11-26 17:04:09 -08004811 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4812 if (!(pendingResult instanceof PendingIntentRecord)) {
4813 return null;
4814 }
4815 try {
4816 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4817 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4818 } catch (ClassCastException e) {
4819 }
4820 return null;
4821 }
4822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 public void setProcessLimit(int max) {
4824 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4825 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004826 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004827 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004828 mProcessLimitOverride = max;
4829 }
4830 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 }
4832
4833 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004834 synchronized (this) {
4835 return mProcessLimitOverride;
4836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 }
4838
4839 void foregroundTokenDied(ForegroundToken token) {
4840 synchronized (ActivityManagerService.this) {
4841 synchronized (mPidsSelfLocked) {
4842 ForegroundToken cur
4843 = mForegroundProcesses.get(token.pid);
4844 if (cur != token) {
4845 return;
4846 }
4847 mForegroundProcesses.remove(token.pid);
4848 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4849 if (pr == null) {
4850 return;
4851 }
4852 pr.forcingToForeground = null;
4853 pr.foregroundServices = false;
4854 }
4855 updateOomAdjLocked();
4856 }
4857 }
4858
4859 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4860 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4861 "setProcessForeground()");
4862 synchronized(this) {
4863 boolean changed = false;
4864
4865 synchronized (mPidsSelfLocked) {
4866 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004867 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004868 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004869 return;
4870 }
4871 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4872 if (oldToken != null) {
4873 oldToken.token.unlinkToDeath(oldToken, 0);
4874 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004875 if (pr != null) {
4876 pr.forcingToForeground = null;
4877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 changed = true;
4879 }
4880 if (isForeground && token != null) {
4881 ForegroundToken newToken = new ForegroundToken() {
4882 public void binderDied() {
4883 foregroundTokenDied(this);
4884 }
4885 };
4886 newToken.pid = pid;
4887 newToken.token = token;
4888 try {
4889 token.linkToDeath(newToken, 0);
4890 mForegroundProcesses.put(pid, newToken);
4891 pr.forcingToForeground = token;
4892 changed = true;
4893 } catch (RemoteException e) {
4894 // If the process died while doing this, we will later
4895 // do the cleanup with the process death link.
4896 }
4897 }
4898 }
4899
4900 if (changed) {
4901 updateOomAdjLocked();
4902 }
4903 }
4904 }
4905
4906 // =========================================================
4907 // PERMISSIONS
4908 // =========================================================
4909
4910 static class PermissionController extends IPermissionController.Stub {
4911 ActivityManagerService mActivityManagerService;
4912 PermissionController(ActivityManagerService activityManagerService) {
4913 mActivityManagerService = activityManagerService;
4914 }
4915
4916 public boolean checkPermission(String permission, int pid, int uid) {
4917 return mActivityManagerService.checkPermission(permission, pid,
4918 uid) == PackageManager.PERMISSION_GRANTED;
4919 }
4920 }
4921
4922 /**
4923 * This can be called with or without the global lock held.
4924 */
4925 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004926 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 // We might be performing an operation on behalf of an indirect binder
4928 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4929 // client identity accordingly before proceeding.
4930 Identity tlsIdentity = sCallerIdentity.get();
4931 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004932 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004933 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4934 uid = tlsIdentity.uid;
4935 pid = tlsIdentity.pid;
4936 }
4937
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004938 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939 return PackageManager.PERMISSION_GRANTED;
4940 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004941
4942 return ActivityManager.checkComponentPermission(permission, uid,
4943 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 }
4945
4946 /**
4947 * As the only public entry point for permissions checking, this method
4948 * can enforce the semantic that requesting a check on a null global
4949 * permission is automatically denied. (Internally a null permission
4950 * string is used when calling {@link #checkComponentPermission} in cases
4951 * when only uid-based security is needed.)
4952 *
4953 * This can be called with or without the global lock held.
4954 */
4955 public int checkPermission(String permission, int pid, int uid) {
4956 if (permission == null) {
4957 return PackageManager.PERMISSION_DENIED;
4958 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004959 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 /**
4963 * Binder IPC calls go through the public entry point.
4964 * This can be called with or without the global lock held.
4965 */
4966 int checkCallingPermission(String permission) {
4967 return checkPermission(permission,
4968 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004969 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 }
4971
4972 /**
4973 * This can be called with or without the global lock held.
4974 */
4975 void enforceCallingPermission(String permission, String func) {
4976 if (checkCallingPermission(permission)
4977 == PackageManager.PERMISSION_GRANTED) {
4978 return;
4979 }
4980
4981 String msg = "Permission Denial: " + func + " from pid="
4982 + Binder.getCallingPid()
4983 + ", uid=" + Binder.getCallingUid()
4984 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004985 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 throw new SecurityException(msg);
4987 }
4988
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004989 /**
4990 * Determine if UID is holding permissions required to access {@link Uri} in
4991 * the given {@link ProviderInfo}. Final permission checking is always done
4992 * in {@link ContentProvider}.
4993 */
4994 private final boolean checkHoldingPermissionsLocked(
4995 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004996 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4997 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004998
4999 if (pi.applicationInfo.uid == uid) {
5000 return true;
5001 } else if (!pi.exported) {
5002 return false;
5003 }
5004
5005 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5006 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005008 // check if target holds top-level <provider> permissions
5009 if (!readMet && pi.readPermission != null
5010 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5011 readMet = true;
5012 }
5013 if (!writeMet && pi.writePermission != null
5014 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5015 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005017
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005018 // track if unprotected read/write is allowed; any denied
5019 // <path-permission> below removes this ability
5020 boolean allowDefaultRead = pi.readPermission == null;
5021 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005022
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005023 // check if target holds any <path-permission> that match uri
5024 final PathPermission[] pps = pi.pathPermissions;
5025 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005026 final String path = uri.getPath();
5027 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005028 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005029 i--;
5030 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005031 if (pp.match(path)) {
5032 if (!readMet) {
5033 final String pprperm = pp.getReadPermission();
5034 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5035 + pprperm + " for " + pp.getPath()
5036 + ": match=" + pp.match(path)
5037 + " check=" + pm.checkUidPermission(pprperm, uid));
5038 if (pprperm != null) {
5039 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5040 readMet = true;
5041 } else {
5042 allowDefaultRead = false;
5043 }
5044 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005045 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005046 if (!writeMet) {
5047 final String ppwperm = pp.getWritePermission();
5048 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5049 + ppwperm + " for " + pp.getPath()
5050 + ": match=" + pp.match(path)
5051 + " check=" + pm.checkUidPermission(ppwperm, uid));
5052 if (ppwperm != null) {
5053 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5054 writeMet = true;
5055 } else {
5056 allowDefaultWrite = false;
5057 }
5058 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005059 }
5060 }
5061 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005062 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005063
5064 // grant unprotected <provider> read/write, if not blocked by
5065 // <path-permission> above
5066 if (allowDefaultRead) readMet = true;
5067 if (allowDefaultWrite) writeMet = true;
5068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 } catch (RemoteException e) {
5070 return false;
5071 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005072
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005073 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 }
5075
5076 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5077 int modeFlags) {
5078 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005079 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 return true;
5081 }
5082 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5083 if (perms == null) return false;
5084 UriPermission perm = perms.get(uri);
5085 if (perm == null) return false;
5086 return (modeFlags&perm.modeFlags) == modeFlags;
5087 }
5088
5089 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005090 enforceNotIsolatedCaller("checkUriPermission");
5091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 // Another redirected-binder-call permissions check as in
5093 // {@link checkComponentPermission}.
5094 Identity tlsIdentity = sCallerIdentity.get();
5095 if (tlsIdentity != null) {
5096 uid = tlsIdentity.uid;
5097 pid = tlsIdentity.pid;
5098 }
5099
5100 // Our own process gets to do everything.
5101 if (pid == MY_PID) {
5102 return PackageManager.PERMISSION_GRANTED;
5103 }
5104 synchronized(this) {
5105 return checkUriPermissionLocked(uri, uid, modeFlags)
5106 ? PackageManager.PERMISSION_GRANTED
5107 : PackageManager.PERMISSION_DENIED;
5108 }
5109 }
5110
Dianne Hackborn39792d22010-08-19 18:01:52 -07005111 /**
5112 * Check if the targetPkg can be granted permission to access uri by
5113 * the callingUid using the given modeFlags. Throws a security exception
5114 * if callingUid is not allowed to do this. Returns the uid of the target
5115 * if the URI permission grant should be performed; returns -1 if it is not
5116 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005117 * If you already know the uid of the target, you can supply it in
5118 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005119 */
5120 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005121 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005122 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5123 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5124 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005125 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 }
5127
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005128 if (targetPkg != null) {
5129 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5130 "Checking grant " + targetPkg + " permission to " + uri);
5131 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005132
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005133 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005134
5135 // If this is not a content: uri, we can't do anything with it.
5136 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005137 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005138 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005139 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141
5142 String name = uri.getAuthority();
5143 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005144 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005145 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 if (cpr != null) {
5147 pi = cpr.info;
5148 } else {
5149 try {
5150 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005151 PackageManager.GET_URI_PERMISSION_PATTERNS,
5152 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 } catch (RemoteException ex) {
5154 }
5155 }
5156 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005157 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005158 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 }
5160
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005161 int targetUid = lastTargetUid;
5162 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005163 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005164 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005165 if (targetUid < 0) {
5166 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5167 "Can't grant URI permission no uid for: " + targetPkg);
5168 return -1;
5169 }
5170 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005171 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 }
5174
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005175 if (targetUid >= 0) {
5176 // First... does the target actually need this permission?
5177 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5178 // No need to grant the target this permission.
5179 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5180 "Target " + targetPkg + " already has full permission to " + uri);
5181 return -1;
5182 }
5183 } else {
5184 // First... there is no target package, so can anyone access it?
5185 boolean allowed = pi.exported;
5186 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5187 if (pi.readPermission != null) {
5188 allowed = false;
5189 }
5190 }
5191 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5192 if (pi.writePermission != null) {
5193 allowed = false;
5194 }
5195 }
5196 if (allowed) {
5197 return -1;
5198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 }
5200
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005201 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 if (!pi.grantUriPermissions) {
5203 throw new SecurityException("Provider " + pi.packageName
5204 + "/" + pi.name
5205 + " does not allow granting of Uri permissions (uri "
5206 + uri + ")");
5207 }
5208 if (pi.uriPermissionPatterns != null) {
5209 final int N = pi.uriPermissionPatterns.length;
5210 boolean allowed = false;
5211 for (int i=0; i<N; i++) {
5212 if (pi.uriPermissionPatterns[i] != null
5213 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5214 allowed = true;
5215 break;
5216 }
5217 }
5218 if (!allowed) {
5219 throw new SecurityException("Provider " + pi.packageName
5220 + "/" + pi.name
5221 + " does not allow granting of permission to path of Uri "
5222 + uri);
5223 }
5224 }
5225
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005226 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005228 if (callingUid != Process.myUid()) {
5229 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5230 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5231 throw new SecurityException("Uid " + callingUid
5232 + " does not have permission to uri " + uri);
5233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005234 }
5235 }
5236
Dianne Hackborn39792d22010-08-19 18:01:52 -07005237 return targetUid;
5238 }
5239
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005240 public int checkGrantUriPermission(int callingUid, String targetPkg,
5241 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005242 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005243 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005244 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005245 }
5246 }
5247
Dianne Hackborn39792d22010-08-19 18:01:52 -07005248 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5249 Uri uri, int modeFlags, UriPermissionOwner owner) {
5250 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5251 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5252 if (modeFlags == 0) {
5253 return;
5254 }
5255
5256 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257 // to the uri, and the target doesn't. Let's now give this to
5258 // the target.
5259
Joe Onorato8a9b2202010-02-26 18:56:32 -08005260 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005261 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005263 HashMap<Uri, UriPermission> targetUris
5264 = mGrantedUriPermissions.get(targetUid);
5265 if (targetUris == null) {
5266 targetUris = new HashMap<Uri, UriPermission>();
5267 mGrantedUriPermissions.put(targetUid, targetUris);
5268 }
5269
5270 UriPermission perm = targetUris.get(uri);
5271 if (perm == null) {
5272 perm = new UriPermission(targetUid, uri);
5273 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005274 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005276 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005277 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005279 } else {
5280 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5281 perm.readOwners.add(owner);
5282 owner.addReadPermission(perm);
5283 }
5284 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5285 perm.writeOwners.add(owner);
5286 owner.addWritePermission(perm);
5287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 }
5289 }
5290
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005291 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5292 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005293 if (targetPkg == null) {
5294 throw new NullPointerException("targetPkg");
5295 }
5296
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005297 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005298 if (targetUid < 0) {
5299 return;
5300 }
5301
5302 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5303 }
5304
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005305 static class NeededUriGrants extends ArrayList<Uri> {
5306 final String targetPkg;
5307 final int targetUid;
5308 final int flags;
5309
5310 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5311 targetPkg = _targetPkg;
5312 targetUid = _targetUid;
5313 flags = _flags;
5314 }
5315 }
5316
Dianne Hackborn39792d22010-08-19 18:01:52 -07005317 /**
5318 * Like checkGrantUriPermissionLocked, but takes an Intent.
5319 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005320 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5321 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005322 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005323 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5324 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005325 + " from " + intent + "; flags=0x"
5326 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5327
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005328 if (targetPkg == null) {
5329 throw new NullPointerException("targetPkg");
5330 }
5331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005332 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005333 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 }
5335 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005336 ClipData clip = intent.getClipData();
5337 if (data == null && clip == null) {
5338 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005339 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005340 if (data != null) {
5341 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5342 mode, needed != null ? needed.targetUid : -1);
5343 if (target > 0) {
5344 if (needed == null) {
5345 needed = new NeededUriGrants(targetPkg, target, mode);
5346 }
5347 needed.add(data);
5348 }
5349 }
5350 if (clip != null) {
5351 for (int i=0; i<clip.getItemCount(); i++) {
5352 Uri uri = clip.getItemAt(i).getUri();
5353 if (uri != null) {
5354 int target = -1;
5355 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5356 mode, needed != null ? needed.targetUid : -1);
5357 if (target > 0) {
5358 if (needed == null) {
5359 needed = new NeededUriGrants(targetPkg, target, mode);
5360 }
5361 needed.add(uri);
5362 }
5363 } else {
5364 Intent clipIntent = clip.getItemAt(i).getIntent();
5365 if (clipIntent != null) {
5366 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5367 callingUid, targetPkg, clipIntent, mode, needed);
5368 if (newNeeded != null) {
5369 needed = newNeeded;
5370 }
5371 }
5372 }
5373 }
5374 }
5375
5376 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005377 }
5378
5379 /**
5380 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5381 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005382 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5383 UriPermissionOwner owner) {
5384 if (needed != null) {
5385 for (int i=0; i<needed.size(); i++) {
5386 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5387 needed.get(i), needed.flags, owner);
5388 }
5389 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005390 }
5391
5392 void grantUriPermissionFromIntentLocked(int callingUid,
5393 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005394 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005395 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005396 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 return;
5398 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005399
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005400 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005401 }
5402
5403 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5404 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005405 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005406 synchronized(this) {
5407 final ProcessRecord r = getRecordForAppLocked(caller);
5408 if (r == null) {
5409 throw new SecurityException("Unable to find app for caller "
5410 + caller
5411 + " when granting permission to uri " + uri);
5412 }
5413 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005414 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 }
5416 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005417 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 }
5419
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005420 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421 null);
5422 }
5423 }
5424
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005425 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5427 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5428 HashMap<Uri, UriPermission> perms
5429 = mGrantedUriPermissions.get(perm.uid);
5430 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005431 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005432 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433 perms.remove(perm.uri);
5434 if (perms.size() == 0) {
5435 mGrantedUriPermissions.remove(perm.uid);
5436 }
5437 }
5438 }
5439 }
5440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5442 int modeFlags) {
5443 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5444 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5445 if (modeFlags == 0) {
5446 return;
5447 }
5448
Joe Onorato8a9b2202010-02-26 18:56:32 -08005449 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005450 "Revoking all granted permissions to " + uri);
5451
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005452 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453
5454 final String authority = uri.getAuthority();
5455 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005456 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005457 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 if (cpr != null) {
5459 pi = cpr.info;
5460 } else {
5461 try {
5462 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005463 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 } catch (RemoteException ex) {
5465 }
5466 }
5467 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005468 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 return;
5470 }
5471
5472 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005473 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 // Right now, if you are not the original owner of the permission,
5475 // you are not allowed to revoke it.
5476 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5477 throw new SecurityException("Uid " + callingUid
5478 + " does not have permission to uri " + uri);
5479 //}
5480 }
5481
5482 // Go through all of the permissions and remove any that match.
5483 final List<String> SEGMENTS = uri.getPathSegments();
5484 if (SEGMENTS != null) {
5485 final int NS = SEGMENTS.size();
5486 int N = mGrantedUriPermissions.size();
5487 for (int i=0; i<N; i++) {
5488 HashMap<Uri, UriPermission> perms
5489 = mGrantedUriPermissions.valueAt(i);
5490 Iterator<UriPermission> it = perms.values().iterator();
5491 toploop:
5492 while (it.hasNext()) {
5493 UriPermission perm = it.next();
5494 Uri targetUri = perm.uri;
5495 if (!authority.equals(targetUri.getAuthority())) {
5496 continue;
5497 }
5498 List<String> targetSegments = targetUri.getPathSegments();
5499 if (targetSegments == null) {
5500 continue;
5501 }
5502 if (targetSegments.size() < NS) {
5503 continue;
5504 }
5505 for (int j=0; j<NS; j++) {
5506 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5507 continue toploop;
5508 }
5509 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005510 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005511 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 perm.clearModes(modeFlags);
5513 if (perm.modeFlags == 0) {
5514 it.remove();
5515 }
5516 }
5517 if (perms.size() == 0) {
5518 mGrantedUriPermissions.remove(
5519 mGrantedUriPermissions.keyAt(i));
5520 N--;
5521 i--;
5522 }
5523 }
5524 }
5525 }
5526
5527 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5528 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005529 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 synchronized(this) {
5531 final ProcessRecord r = getRecordForAppLocked(caller);
5532 if (r == null) {
5533 throw new SecurityException("Unable to find app for caller "
5534 + caller
5535 + " when revoking permission to uri " + uri);
5536 }
5537 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005538 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 return;
5540 }
5541
5542 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5543 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5544 if (modeFlags == 0) {
5545 return;
5546 }
5547
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005548 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549
5550 final String authority = uri.getAuthority();
5551 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005552 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 if (cpr != null) {
5554 pi = cpr.info;
5555 } else {
5556 try {
5557 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005558 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005559 } catch (RemoteException ex) {
5560 }
5561 }
5562 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005563 Slog.w(TAG, "No content provider found for permission revoke: "
5564 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 return;
5566 }
5567
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005568 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 }
5570 }
5571
Dianne Hackborn7e269642010-08-25 19:50:20 -07005572 @Override
5573 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005574 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005575 synchronized(this) {
5576 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5577 return owner.getExternalTokenLocked();
5578 }
5579 }
5580
5581 @Override
5582 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5583 Uri uri, int modeFlags) {
5584 synchronized(this) {
5585 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5586 if (owner == null) {
5587 throw new IllegalArgumentException("Unknown owner: " + token);
5588 }
5589 if (fromUid != Binder.getCallingUid()) {
5590 if (Binder.getCallingUid() != Process.myUid()) {
5591 // Only system code can grant URI permissions on behalf
5592 // of other users.
5593 throw new SecurityException("nice try");
5594 }
5595 }
5596 if (targetPkg == null) {
5597 throw new IllegalArgumentException("null target");
5598 }
5599 if (uri == null) {
5600 throw new IllegalArgumentException("null uri");
5601 }
5602
5603 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5604 }
5605 }
5606
5607 @Override
5608 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5609 synchronized(this) {
5610 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5611 if (owner == null) {
5612 throw new IllegalArgumentException("Unknown owner: " + token);
5613 }
5614
5615 if (uri == null) {
5616 owner.removeUriPermissionsLocked(mode);
5617 } else {
5618 owner.removeUriPermissionLocked(uri, mode);
5619 }
5620 }
5621 }
5622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5624 synchronized (this) {
5625 ProcessRecord app =
5626 who != null ? getRecordForAppLocked(who) : null;
5627 if (app == null) return;
5628
5629 Message msg = Message.obtain();
5630 msg.what = WAIT_FOR_DEBUGGER_MSG;
5631 msg.obj = app;
5632 msg.arg1 = waiting ? 1 : 0;
5633 mHandler.sendMessage(msg);
5634 }
5635 }
5636
5637 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005638 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5639 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005641 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005642 outInfo.threshold = homeAppMem;
5643 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5644 outInfo.hiddenAppThreshold = hiddenAppMem;
5645 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005646 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005647 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5648 ProcessList.VISIBLE_APP_ADJ);
5649 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5650 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 }
5652
5653 // =========================================================
5654 // TASK MANAGEMENT
5655 // =========================================================
5656
5657 public List getTasks(int maxNum, int flags,
5658 IThumbnailReceiver receiver) {
5659 ArrayList list = new ArrayList();
5660
5661 PendingThumbnailsRecord pending = null;
5662 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005663 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664
5665 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005666 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5668 + ", receiver=" + receiver);
5669
5670 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5671 != PackageManager.PERMISSION_GRANTED) {
5672 if (receiver != null) {
5673 // If the caller wants to wait for pending thumbnails,
5674 // it ain't gonna get them.
5675 try {
5676 receiver.finished();
5677 } catch (RemoteException ex) {
5678 }
5679 }
5680 String msg = "Permission Denial: getTasks() from pid="
5681 + Binder.getCallingPid()
5682 + ", uid=" + Binder.getCallingUid()
5683 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005684 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 throw new SecurityException(msg);
5686 }
5687
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005688 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005689 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005690 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005691 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 TaskRecord curTask = null;
5693 int numActivities = 0;
5694 int numRunning = 0;
5695 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005696 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005698 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699
5700 // Initialize state for next task if needed.
5701 if (top == null ||
5702 (top.state == ActivityState.INITIALIZING
5703 && top.task == r.task)) {
5704 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 curTask = r.task;
5706 numActivities = numRunning = 0;
5707 }
5708
5709 // Add 'r' into the current task.
5710 numActivities++;
5711 if (r.app != null && r.app.thread != null) {
5712 numRunning++;
5713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714
Joe Onorato8a9b2202010-02-26 18:56:32 -08005715 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005716 TAG, r.intent.getComponent().flattenToShortString()
5717 + ": task=" + r.task);
5718
5719 // If the next one is a different task, generate a new
5720 // TaskInfo entry for what we have.
5721 if (next == null || next.task != curTask) {
5722 ActivityManager.RunningTaskInfo ci
5723 = new ActivityManager.RunningTaskInfo();
5724 ci.id = curTask.taskId;
5725 ci.baseActivity = r.intent.getComponent();
5726 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005727 if (top.thumbHolder != null) {
5728 ci.description = top.thumbHolder.lastDescription;
5729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 ci.numActivities = numActivities;
5731 ci.numRunning = numRunning;
5732 //System.out.println(
5733 // "#" + maxNum + ": " + " descr=" + ci.description);
5734 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005735 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 TAG, "State=" + top.state + "Idle=" + top.idle
5737 + " app=" + top.app
5738 + " thr=" + (top.app != null ? top.app.thread : null));
5739 if (top.state == ActivityState.RESUMED
5740 || top.state == ActivityState.PAUSING) {
5741 if (top.idle && top.app != null
5742 && top.app.thread != null) {
5743 topRecord = top;
5744 topThumbnail = top.app.thread;
5745 } else {
5746 top.thumbnailNeeded = true;
5747 }
5748 }
5749 if (pending == null) {
5750 pending = new PendingThumbnailsRecord(receiver);
5751 }
5752 pending.pendingRecords.add(top);
5753 }
5754 list.add(ci);
5755 maxNum--;
5756 top = null;
5757 }
5758 }
5759
5760 if (pending != null) {
5761 mPendingThumbnails.add(pending);
5762 }
5763 }
5764
Joe Onorato8a9b2202010-02-26 18:56:32 -08005765 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766
5767 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005768 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005770 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005772 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005773 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 }
5775 }
5776
5777 if (pending == null && receiver != null) {
5778 // In this case all thumbnails were available and the client
5779 // is being asked to be told when the remaining ones come in...
5780 // which is unusually, since the top-most currently running
5781 // activity should never have a canned thumbnail! Oh well.
5782 try {
5783 receiver.finished();
5784 } catch (RemoteException ex) {
5785 }
5786 }
5787
5788 return list;
5789 }
5790
5791 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005792 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005793 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5794 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 synchronized (this) {
5797 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5798 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005799 final boolean detailed = checkCallingPermission(
5800 android.Manifest.permission.GET_DETAILED_TASKS)
5801 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005803 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 final int N = mRecentTasks.size();
5806 ArrayList<ActivityManager.RecentTaskInfo> res
5807 = new ArrayList<ActivityManager.RecentTaskInfo>(
5808 maxNum < N ? maxNum : N);
5809 for (int i=0; i<N && maxNum > 0; i++) {
5810 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005811 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005812 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005813 // Return the entry if desired by the caller. We always return
5814 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005815 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005816 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5817 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005818
Dianne Hackborn905577f2011-09-07 18:31:28 -07005819 if (i == 0
5820 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 || (tr.intent == null)
5822 || ((tr.intent.getFlags()
5823 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5824 ActivityManager.RecentTaskInfo rti
5825 = new ActivityManager.RecentTaskInfo();
5826 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005827 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 rti.baseIntent = new Intent(
5829 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005830 if (!detailed) {
5831 rti.baseIntent.replaceExtras((Bundle)null);
5832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005834 rti.description = tr.lastDescription;
5835
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005836 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5837 // Check whether this activity is currently available.
5838 try {
5839 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005840 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005841 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005842 continue;
5843 }
5844 } else if (rti.baseIntent != null) {
5845 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005846 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005847 continue;
5848 }
5849 }
5850 } catch (RemoteException e) {
5851 // Will never happen.
5852 }
5853 }
5854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 res.add(rti);
5856 maxNum--;
5857 }
5858 }
5859 return res;
5860 }
5861 }
5862
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005863 private TaskRecord taskForIdLocked(int id) {
5864 final int N = mRecentTasks.size();
5865 for (int i=0; i<N; i++) {
5866 TaskRecord tr = mRecentTasks.get(i);
5867 if (tr.taskId == id) {
5868 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005869 }
5870 }
5871 return null;
5872 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005873
5874 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5875 synchronized (this) {
5876 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5877 "getTaskThumbnails()");
5878 TaskRecord tr = taskForIdLocked(id);
5879 if (tr != null) {
5880 return mMainStack.getTaskThumbnailsLocked(tr);
5881 }
5882 }
5883 return null;
5884 }
5885
Dianne Hackborn15491c62012-09-19 10:59:14 -07005886 public Bitmap getTaskTopThumbnail(int id) {
5887 synchronized (this) {
5888 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5889 "getTaskTopThumbnail()");
5890 TaskRecord tr = taskForIdLocked(id);
5891 if (tr != null) {
5892 return mMainStack.getTaskTopThumbnailLocked(tr);
5893 }
5894 }
5895 return null;
5896 }
5897
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005898 public boolean removeSubTask(int taskId, int subTaskIndex) {
5899 synchronized (this) {
5900 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5901 "removeSubTask()");
5902 long ident = Binder.clearCallingIdentity();
5903 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005904 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5905 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005906 } finally {
5907 Binder.restoreCallingIdentity(ident);
5908 }
5909 }
5910 }
5911
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005912 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5913 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005914 Intent baseIntent = new Intent(
5915 tr.intent != null ? tr.intent : tr.affinityIntent);
5916 ComponentName component = baseIntent.getComponent();
5917 if (component == null) {
5918 Slog.w(TAG, "Now component for base intent of task: " + tr);
5919 return;
5920 }
5921
5922 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005923 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005924
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005925 if (killProcesses) {
5926 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005927 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005928 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005929 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5930 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5931 for (int i=0; i<uids.size(); i++) {
5932 ProcessRecord proc = uids.valueAt(i);
5933 if (proc.userId != tr.userId) {
5934 continue;
5935 }
5936 if (!proc.pkgList.contains(pkg)) {
5937 continue;
5938 }
5939 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005940 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005941 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005942
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005943 // Kill the running processes.
5944 for (int i=0; i<procs.size(); i++) {
5945 ProcessRecord pr = procs.get(i);
5946 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5947 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005948 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005949 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005950 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005951 Process.killProcessQuiet(pr.pid);
5952 } else {
5953 pr.waitingToKill = "remove task";
5954 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005955 }
5956 }
5957 }
5958
5959 public boolean removeTask(int taskId, int flags) {
5960 synchronized (this) {
5961 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5962 "removeTask()");
5963 long ident = Binder.clearCallingIdentity();
5964 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005965 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5966 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005967 if (r != null) {
5968 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005969 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005970 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005971 } else {
5972 TaskRecord tr = null;
5973 int i=0;
5974 while (i < mRecentTasks.size()) {
5975 TaskRecord t = mRecentTasks.get(i);
5976 if (t.taskId == taskId) {
5977 tr = t;
5978 break;
5979 }
5980 i++;
5981 }
5982 if (tr != null) {
5983 if (tr.numActivities <= 0) {
5984 // Caller is just removing a recent task that is
5985 // not actively running. That is easy!
5986 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005987 cleanUpRemovedTaskLocked(tr, flags);
5988 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005989 } else {
5990 Slog.w(TAG, "removeTask: task " + taskId
5991 + " does not have activities to remove, "
5992 + " but numActivities=" + tr.numActivities
5993 + ": " + tr);
5994 }
5995 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005996 }
5997 } finally {
5998 Binder.restoreCallingIdentity(ident);
5999 }
6000 }
6001 return false;
6002 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6005 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006006 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 TaskRecord jt = startTask;
6008
6009 // First look backwards
6010 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006011 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 if (r.task != jt) {
6013 jt = r.task;
6014 if (affinity.equals(jt.affinity)) {
6015 return j;
6016 }
6017 }
6018 }
6019
6020 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006021 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 jt = startTask;
6023 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006024 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 if (r.task != jt) {
6026 if (affinity.equals(jt.affinity)) {
6027 return j;
6028 }
6029 jt = r.task;
6030 }
6031 }
6032
6033 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006034 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 return N-1;
6036 }
6037
6038 return -1;
6039 }
6040
6041 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006042 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006044 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6046 "moveTaskToFront()");
6047
6048 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006049 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6050 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006051 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006052 return;
6053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 final long origId = Binder.clearCallingIdentity();
6055 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006056 TaskRecord tr = taskForIdLocked(task);
6057 if (tr != null) {
6058 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6059 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006061 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6062 // Caller wants the home activity moved with it. To accomplish this,
6063 // we'll just move the home task to the top first.
6064 mMainStack.moveHomeToFrontLocked();
6065 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006066 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006067 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006069 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6070 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006072 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6073 mMainStack.mUserLeaving = true;
6074 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006075 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6076 // Caller wants the home activity moved with it. To accomplish this,
6077 // we'll just move the home task to the top first.
6078 mMainStack.moveHomeToFrontLocked();
6079 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006080 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 return;
6082 }
6083 }
6084 } finally {
6085 Binder.restoreCallingIdentity(origId);
6086 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006087 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089 }
6090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 public void moveTaskToBack(int task) {
6092 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6093 "moveTaskToBack()");
6094
6095 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006096 if (mMainStack.mResumedActivity != null
6097 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006098 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6099 Binder.getCallingUid(), "Task to back")) {
6100 return;
6101 }
6102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006104 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 Binder.restoreCallingIdentity(origId);
6106 }
6107 }
6108
6109 /**
6110 * Moves an activity, and all of the other activities within the same task, to the bottom
6111 * of the history stack. The activity's order within the task is unchanged.
6112 *
6113 * @param token A reference to the activity we wish to move
6114 * @param nonRoot If false then this only works if the activity is the root
6115 * of a task; if true it will work for any activity in a task.
6116 * @return Returns true if the move completed, false if not.
6117 */
6118 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006119 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 synchronized(this) {
6121 final long origId = Binder.clearCallingIdentity();
6122 int taskId = getTaskForActivityLocked(token, !nonRoot);
6123 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006124 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 }
6126 Binder.restoreCallingIdentity(origId);
6127 }
6128 return false;
6129 }
6130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 public void moveTaskBackwards(int task) {
6132 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6133 "moveTaskBackwards()");
6134
6135 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006136 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6137 Binder.getCallingUid(), "Task backwards")) {
6138 return;
6139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 final long origId = Binder.clearCallingIdentity();
6141 moveTaskBackwardsLocked(task);
6142 Binder.restoreCallingIdentity(origId);
6143 }
6144 }
6145
6146 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006147 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149
6150 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6151 synchronized(this) {
6152 return getTaskForActivityLocked(token, onlyRoot);
6153 }
6154 }
6155
6156 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006157 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 TaskRecord lastTask = null;
6159 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006160 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006161 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 if (!onlyRoot || lastTask != r.task) {
6163 return r.task.taskId;
6164 }
6165 return -1;
6166 }
6167 lastTask = r.task;
6168 }
6169
6170 return -1;
6171 }
6172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 // =========================================================
6174 // THUMBNAILS
6175 // =========================================================
6176
6177 public void reportThumbnail(IBinder token,
6178 Bitmap thumbnail, CharSequence description) {
6179 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6180 final long origId = Binder.clearCallingIdentity();
6181 sendPendingThumbnail(null, token, thumbnail, description, true);
6182 Binder.restoreCallingIdentity(origId);
6183 }
6184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006185 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 Bitmap thumbnail, CharSequence description, boolean always) {
6187 TaskRecord task = null;
6188 ArrayList receivers = null;
6189
6190 //System.out.println("Send pending thumbnail: " + r);
6191
6192 synchronized(this) {
6193 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006194 r = mMainStack.isInStackLocked(token);
6195 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 return;
6197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006199 if (thumbnail == null && r.thumbHolder != null) {
6200 thumbnail = r.thumbHolder.lastThumbnail;
6201 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 }
6203 if (thumbnail == null && !always) {
6204 // If there is no thumbnail, and this entry is not actually
6205 // going away, then abort for now and pick up the next
6206 // thumbnail we get.
6207 return;
6208 }
6209 task = r.task;
6210
6211 int N = mPendingThumbnails.size();
6212 int i=0;
6213 while (i<N) {
6214 PendingThumbnailsRecord pr =
6215 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6216 //System.out.println("Looking in " + pr.pendingRecords);
6217 if (pr.pendingRecords.remove(r)) {
6218 if (receivers == null) {
6219 receivers = new ArrayList();
6220 }
6221 receivers.add(pr);
6222 if (pr.pendingRecords.size() == 0) {
6223 pr.finished = true;
6224 mPendingThumbnails.remove(i);
6225 N--;
6226 continue;
6227 }
6228 }
6229 i++;
6230 }
6231 }
6232
6233 if (receivers != null) {
6234 final int N = receivers.size();
6235 for (int i=0; i<N; i++) {
6236 try {
6237 PendingThumbnailsRecord pr =
6238 (PendingThumbnailsRecord)receivers.get(i);
6239 pr.receiver.newThumbnail(
6240 task != null ? task.taskId : -1, thumbnail, description);
6241 if (pr.finished) {
6242 pr.receiver.finished();
6243 }
6244 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006245 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 }
6247 }
6248 }
6249 }
6250
6251 // =========================================================
6252 // CONTENT PROVIDERS
6253 // =========================================================
6254
Jeff Brown10e89712011-07-08 18:52:57 -07006255 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6256 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006258 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006259 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006260 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 } catch (RemoteException ex) {
6262 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006263 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006264 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6265 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006267 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 for (int i=0; i<N; i++) {
6269 ProviderInfo cpi =
6270 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006271 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6272 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006273 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006274 // This is a singleton provider, but a user besides the
6275 // default user is asking to initialize a process it runs
6276 // in... well, no, it doesn't actually run in this process,
6277 // it runs in the process of the default user. Get rid of it.
6278 providers.remove(i);
6279 N--;
6280 continue;
6281 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006282
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006283 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006284 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006286 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006287 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006289 if (DEBUG_MU)
6290 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 app.pubProviders.put(cpi.name, cpr);
6292 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006293 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 }
6295 }
6296 return providers;
6297 }
6298
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006299 /**
6300 * Check if {@link ProcessRecord} has a possible chance at accessing the
6301 * given {@link ProviderInfo}. Final permission checking is always done
6302 * in {@link ContentProvider}.
6303 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006305 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006307 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006309 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006310 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return null;
6312 }
6313 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006314 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 == PackageManager.PERMISSION_GRANTED) {
6316 return null;
6317 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006318
6319 PathPermission[] pps = cpi.pathPermissions;
6320 if (pps != null) {
6321 int i = pps.length;
6322 while (i > 0) {
6323 i--;
6324 PathPermission pp = pps[i];
6325 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006326 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006327 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006328 return null;
6329 }
6330 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006331 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006332 == PackageManager.PERMISSION_GRANTED) {
6333 return null;
6334 }
6335 }
6336 }
6337
Dianne Hackbornb424b632010-08-18 15:59:05 -07006338 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6339 if (perms != null) {
6340 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6341 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6342 return null;
6343 }
6344 }
6345 }
6346
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006347 String msg;
6348 if (!cpi.exported) {
6349 msg = "Permission Denial: opening provider " + cpi.name
6350 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6351 + ", uid=" + callingUid + ") that is not exported from uid "
6352 + cpi.applicationInfo.uid;
6353 } else {
6354 msg = "Permission Denial: opening provider " + cpi.name
6355 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6356 + ", uid=" + callingUid + ") requires "
6357 + cpi.readPermission + " or " + cpi.writePermission;
6358 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006359 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 return msg;
6361 }
6362
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006363 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6364 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006365 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006366 for (int i=0; i<r.conProviders.size(); i++) {
6367 ContentProviderConnection conn = r.conProviders.get(i);
6368 if (conn.provider == cpr) {
6369 if (DEBUG_PROVIDER) Slog.v(TAG,
6370 "Adding provider requested by "
6371 + r.processName + " from process "
6372 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6373 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6374 if (stable) {
6375 conn.stableCount++;
6376 conn.numStableIncs++;
6377 } else {
6378 conn.unstableCount++;
6379 conn.numUnstableIncs++;
6380 }
6381 return conn;
6382 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006383 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006384 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6385 if (stable) {
6386 conn.stableCount = 1;
6387 conn.numStableIncs = 1;
6388 } else {
6389 conn.unstableCount = 1;
6390 conn.numUnstableIncs = 1;
6391 }
6392 cpr.connections.add(conn);
6393 r.conProviders.add(conn);
6394 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006395 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006396 cpr.addExternalProcessHandleLocked(externalProcessToken);
6397 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006398 }
6399
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006400 boolean decProviderCountLocked(ContentProviderConnection conn,
6401 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6402 if (conn != null) {
6403 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006404 if (DEBUG_PROVIDER) Slog.v(TAG,
6405 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006406 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006407 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006408 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6409 if (stable) {
6410 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006411 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006412 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006413 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006414 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6415 cpr.connections.remove(conn);
6416 conn.client.conProviders.remove(conn);
6417 return true;
6418 }
6419 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006420 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006421 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006422 return false;
6423 }
6424
Amith Yamasani742a6712011-05-04 14:49:28 -07006425 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006426 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006428 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 ProviderInfo cpi = null;
6430
6431 synchronized(this) {
6432 ProcessRecord r = null;
6433 if (caller != null) {
6434 r = getRecordForAppLocked(caller);
6435 if (r == null) {
6436 throw new SecurityException(
6437 "Unable to find app for caller " + caller
6438 + " (pid=" + Binder.getCallingPid()
6439 + ") when getting content provider " + name);
6440 }
6441 }
6442
6443 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006444 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006445 boolean providerRunning = cpr != null;
6446 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006448 String msg;
6449 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6450 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
6452
6453 if (r != null && cpr.canRunHere(r)) {
6454 // This provider has been published or is in the process
6455 // of being published... but it is also allowed to run
6456 // in the caller's process, so don't make a connection
6457 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006458 ContentProviderHolder holder = cpr.newHolder(null);
6459 // don't give caller the provider object, it needs
6460 // to make its own.
6461 holder.provider = null;
6462 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 }
6464
6465 final long origId = Binder.clearCallingIdentity();
6466
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006467 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006469 conn = incProviderCountLocked(r, cpr, token, stable);
6470 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006471 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006472 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006473 // make sure to count it as being accessed and thus
6474 // back up on the LRU list. This is good because
6475 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006476 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006477 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006478 }
6479
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006480 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006481 if (false) {
6482 if (cpr.name.flattenToShortString().equals(
6483 "com.android.providers.calendar/.CalendarProvider2")) {
6484 Slog.v(TAG, "****************** KILLING "
6485 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006486 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006487 }
6488 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006489 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006490 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6491 // NOTE: there is still a race here where a signal could be
6492 // pending on the process even though we managed to update its
6493 // adj level. Not sure what to do about this, but at least
6494 // the race is now smaller.
6495 if (!success) {
6496 // Uh oh... it looks like the provider's process
6497 // has been killed on us. We need to wait for a new
6498 // process to be started, and make sure its death
6499 // doesn't kill our process.
6500 Slog.i(TAG,
6501 "Existing provider " + cpr.name.flattenToShortString()
6502 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006503 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006504 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006505 if (!lastRef) {
6506 // This wasn't the last ref our process had on
6507 // the provider... we have now been killed, bail.
6508 return null;
6509 }
6510 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006511 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 }
6514
6515 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006518 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006519 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006521 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006522 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006523 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 } catch (RemoteException ex) {
6525 }
6526 if (cpi == null) {
6527 return null;
6528 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006529 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6530 cpi.name, cpi.flags);
6531 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006532 userId = 0;
6533 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006534 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006535
Dianne Hackbornb424b632010-08-18 15:59:05 -07006536 String msg;
6537 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6538 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006541 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006542 && !cpi.processName.equals("system")) {
6543 // If this content provider does not run in the system
6544 // process, and the system is not yet ready to run other
6545 // processes, then fail fast instead of hanging.
6546 throw new IllegalArgumentException(
6547 "Attempt to launch content provider before system ready");
6548 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006549
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006550 // Make sure that the user who owns this provider is started. If not,
6551 // we don't want to allow it to run.
6552 if (mStartedUsers.get(userId) == null) {
6553 Slog.w(TAG, "Unable to launch app "
6554 + cpi.applicationInfo.packageName + "/"
6555 + cpi.applicationInfo.uid + " for provider "
6556 + name + ": user " + userId + " is stopped");
6557 return null;
6558 }
6559
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006560 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006561 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 final boolean firstClass = cpr == null;
6563 if (firstClass) {
6564 try {
6565 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006566 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 getApplicationInfo(
6568 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006569 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006570 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006571 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 + cpi.name);
6573 return null;
6574 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006575 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006576 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 } catch (RemoteException ex) {
6578 // pm is in same process, this will never happen.
6579 }
6580 }
6581
6582 if (r != null && cpr.canRunHere(r)) {
6583 // If this is a multiprocess provider, then just return its
6584 // info and allow the caller to instantiate it. Only do
6585 // this if the provider is the same user as the caller's
6586 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006587 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 }
6589
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006590 if (DEBUG_PROVIDER) {
6591 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006592 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006593 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 }
6595
6596 // This is single process, and our app is now connecting to it.
6597 // See if we are already in the process of launching this
6598 // provider.
6599 final int N = mLaunchingProviders.size();
6600 int i;
6601 for (i=0; i<N; i++) {
6602 if (mLaunchingProviders.get(i) == cpr) {
6603 break;
6604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 }
6606
6607 // If the provider is not already being launched, then get it
6608 // started.
6609 if (i >= N) {
6610 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006611
6612 try {
6613 // Content provider is now in use, its package can't be stopped.
6614 try {
6615 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006616 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006617 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006618 } catch (IllegalArgumentException e) {
6619 Slog.w(TAG, "Failed trying to unstop package "
6620 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006621 }
6622
6623 ProcessRecord proc = startProcessLocked(cpi.processName,
6624 cpr.appInfo, false, 0, "content provider",
6625 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006626 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006627 if (proc == null) {
6628 Slog.w(TAG, "Unable to launch app "
6629 + cpi.applicationInfo.packageName + "/"
6630 + cpi.applicationInfo.uid + " for provider "
6631 + name + ": process is bad");
6632 return null;
6633 }
6634 cpr.launchingApp = proc;
6635 mLaunchingProviders.add(cpr);
6636 } finally {
6637 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 }
6640
6641 // Make sure the provider is published (the same provider class
6642 // may be published under multiple names).
6643 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006644 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006646
Amith Yamasani742a6712011-05-04 14:49:28 -07006647 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006648 conn = incProviderCountLocked(r, cpr, token, stable);
6649 if (conn != null) {
6650 conn.waiting = true;
6651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 }
6653 }
6654
6655 // Wait for the provider to be published...
6656 synchronized (cpr) {
6657 while (cpr.provider == null) {
6658 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006659 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006660 + cpi.applicationInfo.packageName + "/"
6661 + cpi.applicationInfo.uid + " for provider "
6662 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006663 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006664 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 cpi.applicationInfo.packageName,
6666 cpi.applicationInfo.uid, name);
6667 return null;
6668 }
6669 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006670 if (DEBUG_MU) {
6671 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6672 + cpr.launchingApp);
6673 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006674 if (conn != null) {
6675 conn.waiting = true;
6676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 cpr.wait();
6678 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006679 } finally {
6680 if (conn != null) {
6681 conn.waiting = false;
6682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 }
6684 }
6685 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006686 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 }
6688
6689 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006690 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006691 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 if (caller == null) {
6693 String msg = "null IApplicationThread when getting content provider "
6694 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006695 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 throw new SecurityException(msg);
6697 }
6698
Dianne Hackborn139748f2012-09-24 11:36:57 -07006699 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006700 false, true, "getContentProvider", null);
6701 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
6703
Jeff Sharkey6d515712012-09-20 16:06:08 -07006704 public ContentProviderHolder getContentProviderExternal(
6705 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006706 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6707 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006708 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006709 false, true, "getContentProvider", null);
6710 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006711 }
6712
Dianne Hackborn41203752012-08-31 14:05:51 -07006713 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6714 IBinder token, int userId) {
6715 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717
6718 /**
6719 * Drop a content provider from a ProcessRecord's bookkeeping
6720 * @param cpr
6721 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006722 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006723 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006725 ContentProviderConnection conn;
6726 try {
6727 conn = (ContentProviderConnection)connection;
6728 } catch (ClassCastException e) {
6729 String msg ="removeContentProvider: " + connection
6730 + " not a ContentProviderConnection";
6731 Slog.w(TAG, msg);
6732 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006734 if (conn == null) {
6735 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006737 if (decProviderCountLocked(conn, null, null, stable)) {
6738 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 }
6741 }
6742
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006743 public void removeContentProviderExternal(String name, IBinder token) {
6744 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6745 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006746 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006747 }
6748
Dianne Hackborn41203752012-08-31 14:05:51 -07006749 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006751 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 if(cpr == null) {
6753 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006754 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 return;
6756 }
6757
6758 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006759 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006760 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006761 if (localCpr.hasExternalProcessHandles()) {
6762 if (localCpr.removeExternalProcessHandleLocked(token)) {
6763 updateOomAdjLocked();
6764 } else {
6765 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6766 + " with no external reference for token: "
6767 + token + ".");
6768 }
6769 } else {
6770 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6771 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 }
6774 }
6775
6776 public final void publishContentProviders(IApplicationThread caller,
6777 List<ContentProviderHolder> providers) {
6778 if (providers == null) {
6779 return;
6780 }
6781
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006782 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006783 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006785 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006786 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 if (r == null) {
6788 throw new SecurityException(
6789 "Unable to find app for caller " + caller
6790 + " (pid=" + Binder.getCallingPid()
6791 + ") when publishing content providers");
6792 }
6793
6794 final long origId = Binder.clearCallingIdentity();
6795
6796 final int N = providers.size();
6797 for (int i=0; i<N; i++) {
6798 ContentProviderHolder src = providers.get(i);
6799 if (src == null || src.info == null || src.provider == null) {
6800 continue;
6801 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006802 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006803 if (DEBUG_MU)
6804 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006806 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006807 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006808 String names[] = dst.info.authority.split(";");
6809 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006810 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 }
6812
6813 int NL = mLaunchingProviders.size();
6814 int j;
6815 for (j=0; j<NL; j++) {
6816 if (mLaunchingProviders.get(j) == dst) {
6817 mLaunchingProviders.remove(j);
6818 j--;
6819 NL--;
6820 }
6821 }
6822 synchronized (dst) {
6823 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006824 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006825 dst.notifyAll();
6826 }
6827 updateOomAdjLocked(r);
6828 }
6829 }
6830
6831 Binder.restoreCallingIdentity(origId);
6832 }
6833 }
6834
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006835 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6836 ContentProviderConnection conn;
6837 try {
6838 conn = (ContentProviderConnection)connection;
6839 } catch (ClassCastException e) {
6840 String msg ="refContentProvider: " + connection
6841 + " not a ContentProviderConnection";
6842 Slog.w(TAG, msg);
6843 throw new IllegalArgumentException(msg);
6844 }
6845 if (conn == null) {
6846 throw new NullPointerException("connection is null");
6847 }
6848
6849 synchronized (this) {
6850 if (stable > 0) {
6851 conn.numStableIncs += stable;
6852 }
6853 stable = conn.stableCount + stable;
6854 if (stable < 0) {
6855 throw new IllegalStateException("stableCount < 0: " + stable);
6856 }
6857
6858 if (unstable > 0) {
6859 conn.numUnstableIncs += unstable;
6860 }
6861 unstable = conn.unstableCount + unstable;
6862 if (unstable < 0) {
6863 throw new IllegalStateException("unstableCount < 0: " + unstable);
6864 }
6865
6866 if ((stable+unstable) <= 0) {
6867 throw new IllegalStateException("ref counts can't go to zero here: stable="
6868 + stable + " unstable=" + unstable);
6869 }
6870 conn.stableCount = stable;
6871 conn.unstableCount = unstable;
6872 return !conn.dead;
6873 }
6874 }
6875
6876 public void unstableProviderDied(IBinder connection) {
6877 ContentProviderConnection conn;
6878 try {
6879 conn = (ContentProviderConnection)connection;
6880 } catch (ClassCastException e) {
6881 String msg ="refContentProvider: " + connection
6882 + " not a ContentProviderConnection";
6883 Slog.w(TAG, msg);
6884 throw new IllegalArgumentException(msg);
6885 }
6886 if (conn == null) {
6887 throw new NullPointerException("connection is null");
6888 }
6889
6890 // Safely retrieve the content provider associated with the connection.
6891 IContentProvider provider;
6892 synchronized (this) {
6893 provider = conn.provider.provider;
6894 }
6895
6896 if (provider == null) {
6897 // Um, yeah, we're way ahead of you.
6898 return;
6899 }
6900
6901 // Make sure the caller is being honest with us.
6902 if (provider.asBinder().pingBinder()) {
6903 // Er, no, still looks good to us.
6904 synchronized (this) {
6905 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6906 + " says " + conn + " died, but we don't agree");
6907 return;
6908 }
6909 }
6910
6911 // Well look at that! It's dead!
6912 synchronized (this) {
6913 if (conn.provider.provider != provider) {
6914 // But something changed... good enough.
6915 return;
6916 }
6917
6918 ProcessRecord proc = conn.provider.proc;
6919 if (proc == null || proc.thread == null) {
6920 // Seems like the process is already cleaned up.
6921 return;
6922 }
6923
6924 // As far as we're concerned, this is just like receiving a
6925 // death notification... just a bit prematurely.
6926 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6927 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006928 final long ident = Binder.clearCallingIdentity();
6929 try {
6930 appDiedLocked(proc, proc.pid, proc.thread);
6931 } finally {
6932 Binder.restoreCallingIdentity(ident);
6933 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006934 }
6935 }
6936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006938 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006939 synchronized (mSelf) {
6940 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6941 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006942 if (providers != null) {
6943 for (int i=providers.size()-1; i>=0; i--) {
6944 ProviderInfo pi = (ProviderInfo)providers.get(i);
6945 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6946 Slog.w(TAG, "Not installing system proc provider " + pi.name
6947 + ": not system .apk");
6948 providers.remove(i);
6949 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006950 }
6951 }
6952 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006953 if (providers != null) {
6954 mSystemThread.installSystemProviders(providers);
6955 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006956
6957 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006958
6959 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 }
6961
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006962 /**
6963 * Allows app to retrieve the MIME type of a URI without having permission
6964 * to access its content provider.
6965 *
6966 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6967 *
6968 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6969 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6970 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006971 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006972 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006973 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006974 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006975 final String name = uri.getAuthority();
6976 final long ident = Binder.clearCallingIdentity();
6977 ContentProviderHolder holder = null;
6978
6979 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006980 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006981 if (holder != null) {
6982 return holder.provider.getType(uri);
6983 }
6984 } catch (RemoteException e) {
6985 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6986 return null;
6987 } finally {
6988 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006989 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006990 }
6991 Binder.restoreCallingIdentity(ident);
6992 }
6993
6994 return null;
6995 }
6996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 // =========================================================
6998 // GLOBAL MANAGEMENT
6999 // =========================================================
7000
7001 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007002 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007003 String proc = customProcess != null ? customProcess : info.processName;
7004 BatteryStatsImpl.Uid.Proc ps = null;
7005 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007006 int uid = info.uid;
7007 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007008 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007009 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7010 uid = 0;
7011 while (true) {
7012 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7013 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7014 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7015 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007016 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007017 mNextIsolatedProcessUid++;
7018 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7019 // No process for this uid, use it.
7020 break;
7021 }
7022 stepsLeft--;
7023 if (stepsLeft <= 0) {
7024 return null;
7025 }
7026 }
7027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 synchronized (stats) {
7029 ps = stats.getProcessStatsLocked(info.uid, proc);
7030 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007031 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 }
7033
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007034 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7035 ProcessRecord app;
7036 if (!isolated) {
7037 app = getProcessRecordLocked(info.processName, info.uid);
7038 } else {
7039 app = null;
7040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041
7042 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007043 app = newProcessRecordLocked(null, info, null, isolated);
7044 mProcessNames.put(info.processName, app.uid, app);
7045 if (isolated) {
7046 mIsolatedProcesses.put(app.uid, app);
7047 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007048 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 }
7050
Dianne Hackborne7f97212011-02-24 14:40:20 -08007051 // This package really, really can not be stopped.
7052 try {
7053 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007054 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007055 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007056 } catch (IllegalArgumentException e) {
7057 Slog.w(TAG, "Failed trying to unstop package "
7058 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007059 }
7060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7062 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7063 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007064 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007065 }
7066 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7067 mPersistentStartingProcesses.add(app);
7068 startProcessLocked(app, "added application", app.processName);
7069 }
7070
7071 return app;
7072 }
7073
7074 public void unhandledBack() {
7075 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7076 "unhandledBack()");
7077
7078 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007079 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007080 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007081 TAG, "Performing unhandledBack(): stack size = " + count);
7082 if (count > 1) {
7083 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007084 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007085 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007086 Binder.restoreCallingIdentity(origId);
7087 }
7088 }
7089 }
7090
7091 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007092 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007093 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007095 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 ParcelFileDescriptor pfd = null;
7097 if (cph != null) {
7098 // We record the binder invoker's uid in thread-local storage before
7099 // going to the content provider to open the file. Later, in the code
7100 // that handles all permissions checks, we look for this uid and use
7101 // that rather than the Activity Manager's own uid. The effect is that
7102 // we do the check against the caller's permissions even though it looks
7103 // to the content provider like the Activity Manager itself is making
7104 // the request.
7105 sCallerIdentity.set(new Identity(
7106 Binder.getCallingPid(), Binder.getCallingUid()));
7107 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08007108 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 } catch (FileNotFoundException e) {
7110 // do nothing; pfd will be returned null
7111 } finally {
7112 // Ensure that whatever happens, we clean up the identity state
7113 sCallerIdentity.remove();
7114 }
7115
7116 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007117 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007119 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 }
7121 return pfd;
7122 }
7123
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007124 // Actually is sleeping or shutting down or whatever else in the future
7125 // is an inactive state.
7126 public boolean isSleeping() {
7127 return mSleeping || mShuttingDown;
7128 }
7129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007131 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7132 != PackageManager.PERMISSION_GRANTED) {
7133 throw new SecurityException("Requires permission "
7134 + android.Manifest.permission.DEVICE_POWER);
7135 }
7136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007138 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007139 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007141 if (!mSleeping) {
7142 mSleeping = true;
7143 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007144
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007145 // Initialize the wake times of all processes.
7146 checkExcessivePowerUsageLocked(false);
7147 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7148 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7149 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 }
7152 }
7153
Dianne Hackborn55280a92009-05-07 15:53:46 -07007154 public boolean shutdown(int timeout) {
7155 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7156 != PackageManager.PERMISSION_GRANTED) {
7157 throw new SecurityException("Requires permission "
7158 + android.Manifest.permission.SHUTDOWN);
7159 }
7160
7161 boolean timedout = false;
7162
7163 synchronized(this) {
7164 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007165 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007166
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007167 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007168 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007169 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007170 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007171 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007172 long delay = endTime - System.currentTimeMillis();
7173 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007174 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007175 timedout = true;
7176 break;
7177 }
7178 try {
7179 this.wait();
7180 } catch (InterruptedException e) {
7181 }
7182 }
7183 }
7184 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007185
7186 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007187 mUsageStatsService.shutdown();
7188 mBatteryStatsService.shutdown();
7189
7190 return timedout;
7191 }
7192
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007193 public final void activitySlept(IBinder token) {
7194 if (localLOGV) Slog.v(
7195 TAG, "Activity slept: token=" + token);
7196
7197 ActivityRecord r = null;
7198
7199 final long origId = Binder.clearCallingIdentity();
7200
7201 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007202 r = mMainStack.isInStackLocked(token);
7203 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007204 mMainStack.activitySleptLocked(r);
7205 }
7206 }
7207
7208 Binder.restoreCallingIdentity(origId);
7209 }
7210
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007211 private void comeOutOfSleepIfNeededLocked() {
7212 if (!mWentToSleep && !mLockScreenShown) {
7213 if (mSleeping) {
7214 mSleeping = false;
7215 mMainStack.awakeFromSleepingLocked();
7216 mMainStack.resumeTopActivityLocked(null);
7217 }
7218 }
7219 }
7220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007222 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7223 != PackageManager.PERMISSION_GRANTED) {
7224 throw new SecurityException("Requires permission "
7225 + android.Manifest.permission.DEVICE_POWER);
7226 }
7227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007229 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007230 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007231 comeOutOfSleepIfNeededLocked();
7232 }
7233 }
7234
Jeff Brownc042ee22012-05-08 13:03:42 -07007235 private void updateEventDispatchingLocked() {
7236 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7237 }
7238
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007239 public void setLockScreenShown(boolean shown) {
7240 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7241 != PackageManager.PERMISSION_GRANTED) {
7242 throw new SecurityException("Requires permission "
7243 + android.Manifest.permission.DEVICE_POWER);
7244 }
7245
7246 synchronized(this) {
7247 mLockScreenShown = shown;
7248 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 }
7250 }
7251
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007252 public void stopAppSwitches() {
7253 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7254 != PackageManager.PERMISSION_GRANTED) {
7255 throw new SecurityException("Requires permission "
7256 + android.Manifest.permission.STOP_APP_SWITCHES);
7257 }
7258
7259 synchronized(this) {
7260 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7261 + APP_SWITCH_DELAY_TIME;
7262 mDidAppSwitch = false;
7263 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7264 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7265 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7266 }
7267 }
7268
7269 public void resumeAppSwitches() {
7270 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7271 != PackageManager.PERMISSION_GRANTED) {
7272 throw new SecurityException("Requires permission "
7273 + android.Manifest.permission.STOP_APP_SWITCHES);
7274 }
7275
7276 synchronized(this) {
7277 // Note that we don't execute any pending app switches... we will
7278 // let those wait until either the timeout, or the next start
7279 // activity request.
7280 mAppSwitchesAllowedTime = 0;
7281 }
7282 }
7283
7284 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7285 String name) {
7286 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7287 return true;
7288 }
7289
7290 final int perm = checkComponentPermission(
7291 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007292 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007293 if (perm == PackageManager.PERMISSION_GRANTED) {
7294 return true;
7295 }
7296
Joe Onorato8a9b2202010-02-26 18:56:32 -08007297 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007298 return false;
7299 }
7300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 public void setDebugApp(String packageName, boolean waitForDebugger,
7302 boolean persistent) {
7303 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7304 "setDebugApp()");
7305
7306 // Note that this is not really thread safe if there are multiple
7307 // callers into it at the same time, but that's not a situation we
7308 // care about.
7309 if (persistent) {
7310 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007311 Settings.Global.putString(
7312 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007314 Settings.Global.putInt(
7315 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 waitForDebugger ? 1 : 0);
7317 }
7318
7319 synchronized (this) {
7320 if (!persistent) {
7321 mOrigDebugApp = mDebugApp;
7322 mOrigWaitForDebugger = mWaitForDebugger;
7323 }
7324 mDebugApp = packageName;
7325 mWaitForDebugger = waitForDebugger;
7326 mDebugTransient = !persistent;
7327 if (packageName != null) {
7328 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007329 forceStopPackageLocked(packageName, -1, false, false, true, true,
7330 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 Binder.restoreCallingIdentity(origId);
7332 }
7333 }
7334 }
7335
Siva Velusamy92a8b222012-03-09 16:24:04 -08007336 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7337 synchronized (this) {
7338 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7339 if (!isDebuggable) {
7340 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7341 throw new SecurityException("Process not debuggable: " + app.packageName);
7342 }
7343 }
7344
7345 mOpenGlTraceApp = processName;
7346 }
7347 }
7348
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007349 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7350 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7351 synchronized (this) {
7352 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7353 if (!isDebuggable) {
7354 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7355 throw new SecurityException("Process not debuggable: " + app.packageName);
7356 }
7357 }
7358 mProfileApp = processName;
7359 mProfileFile = profileFile;
7360 if (mProfileFd != null) {
7361 try {
7362 mProfileFd.close();
7363 } catch (IOException e) {
7364 }
7365 mProfileFd = null;
7366 }
7367 mProfileFd = profileFd;
7368 mProfileType = 0;
7369 mAutoStopProfiler = autoStopProfiler;
7370 }
7371 }
7372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 public void setAlwaysFinish(boolean enabled) {
7374 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7375 "setAlwaysFinish()");
7376
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007377 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007378 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007379 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007380
7381 synchronized (this) {
7382 mAlwaysFinishActivities = enabled;
7383 }
7384 }
7385
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007386 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007388 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007390 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391 }
7392 }
7393
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007394 public boolean isUserAMonkey() {
7395 // For now the fact that there is a controller implies
7396 // we have a monkey.
7397 synchronized (this) {
7398 return mController != null;
7399 }
7400 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007401
7402 public void requestBugReport() {
7403 // No permission check because this can't do anything harmful --
7404 // it will just eventually cause the user to be presented with
7405 // a UI to select where the bug report goes.
7406 SystemProperties.set("ctl.start", "bugreport");
7407 }
7408
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007409 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7410 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7411 != PackageManager.PERMISSION_GRANTED) {
7412 throw new SecurityException("Requires permission "
7413 + android.Manifest.permission.FILTER_EVENTS);
7414 }
7415
7416 ProcessRecord proc;
7417
7418 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7419 synchronized (this) {
7420 synchronized (mPidsSelfLocked) {
7421 proc = mPidsSelfLocked.get(pid);
7422 }
7423 if (proc != null) {
7424 if (proc.debugging) {
7425 return -1;
7426 }
7427
7428 if (mDidDexOpt) {
7429 // Give more time since we were dexopting.
7430 mDidDexOpt = false;
7431 return -1;
7432 }
7433
7434 if (proc.instrumentationClass != null) {
7435 Bundle info = new Bundle();
7436 info.putString("shortMsg", "keyDispatchingTimedOut");
7437 info.putString("longMsg", "Timed out while dispatching key event");
7438 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7439 proc = null;
7440 }
7441 }
7442 }
7443
7444 if (proc != null) {
7445 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7446 if (proc.instrumentationClass != null || proc.usingWrapper) {
7447 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7448 }
7449 }
7450
7451 return KEY_DISPATCHING_TIMEOUT;
7452 }
7453
Jeff Sharkeya4620792011-05-20 15:29:23 -07007454 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007455 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7456 "registerProcessObserver()");
7457 synchronized (this) {
7458 mProcessObservers.register(observer);
7459 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007460 }
7461
7462 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007463 synchronized (this) {
7464 mProcessObservers.unregister(observer);
7465 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007466 }
7467
Daniel Sandler69a48172010-06-23 16:29:36 -04007468 public void setImmersive(IBinder token, boolean immersive) {
7469 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007470 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007471 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007472 throw new IllegalArgumentException();
7473 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007474 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007475
7476 // update associated state if we're frontmost
7477 if (r == mFocusedActivity) {
7478 if (DEBUG_IMMERSIVE) {
7479 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7480 }
7481 applyUpdateLockStateLocked(r);
7482 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007483 }
7484 }
7485
7486 public boolean isImmersive(IBinder token) {
7487 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007488 ActivityRecord r = mMainStack.isInStackLocked(token);
7489 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007490 throw new IllegalArgumentException();
7491 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007492 return r.immersive;
7493 }
7494 }
7495
7496 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007497 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007498 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007499 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007500 return (r != null) ? r.immersive : false;
7501 }
7502 }
7503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 public final void enterSafeMode() {
7505 synchronized(this) {
7506 // It only makes sense to do this before the system is ready
7507 // and started launching other packages.
7508 if (!mSystemReady) {
7509 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007510 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 } catch (RemoteException e) {
7512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 }
7514 }
7515 }
7516
Jeff Brownb09abc12011-01-13 21:08:27 -08007517 public final void showSafeModeOverlay() {
7518 View v = LayoutInflater.from(mContext).inflate(
7519 com.android.internal.R.layout.safe_mode, null);
7520 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7521 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7522 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7523 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007524 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007525 lp.format = v.getBackground().getOpacity();
7526 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7527 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007528 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007529 ((WindowManager)mContext.getSystemService(
7530 Context.WINDOW_SERVICE)).addView(v, lp);
7531 }
7532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 public void noteWakeupAlarm(IIntentSender sender) {
7534 if (!(sender instanceof PendingIntentRecord)) {
7535 return;
7536 }
7537 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7538 synchronized (stats) {
7539 if (mBatteryStatsService.isOnBattery()) {
7540 mBatteryStatsService.enforceCallingPermission();
7541 PendingIntentRecord rec = (PendingIntentRecord)sender;
7542 int MY_UID = Binder.getCallingUid();
7543 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7544 BatteryStatsImpl.Uid.Pkg pkg =
7545 stats.getPackageStatsLocked(uid, rec.key.packageName);
7546 pkg.incWakeupsLocked();
7547 }
7548 }
7549 }
7550
Dianne Hackborn64825172011-03-02 21:32:58 -08007551 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007553 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007555 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 // XXX Note: don't acquire main activity lock here, because the window
7557 // manager calls in with its locks held.
7558
7559 boolean killed = false;
7560 synchronized (mPidsSelfLocked) {
7561 int[] types = new int[pids.length];
7562 int worstType = 0;
7563 for (int i=0; i<pids.length; i++) {
7564 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7565 if (proc != null) {
7566 int type = proc.setAdj;
7567 types[i] = type;
7568 if (type > worstType) {
7569 worstType = type;
7570 }
7571 }
7572 }
7573
Dianne Hackborn64825172011-03-02 21:32:58 -08007574 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007576 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7577 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007578 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007580
7581 // If this is not a secure call, don't let it kill processes that
7582 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007583 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7584 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007585 }
7586
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007587 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 for (int i=0; i<pids.length; i++) {
7589 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7590 if (proc == null) {
7591 continue;
7592 }
7593 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007594 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007595 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007596 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007597 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007599 proc.killedBackground = true;
7600 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 }
7602 }
7603 }
7604 return killed;
7605 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007606
7607 @Override
7608 public boolean killProcessesBelowForeground(String reason) {
7609 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7610 throw new SecurityException("killProcessesBelowForeground() only available to system");
7611 }
7612
7613 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7614 }
7615
7616 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7617 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7618 throw new SecurityException("killProcessesBelowAdj() only available to system");
7619 }
7620
7621 boolean killed = false;
7622 synchronized (mPidsSelfLocked) {
7623 final int size = mPidsSelfLocked.size();
7624 for (int i = 0; i < size; i++) {
7625 final int pid = mPidsSelfLocked.keyAt(i);
7626 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7627 if (proc == null) continue;
7628
7629 final int adj = proc.setAdj;
7630 if (adj > belowAdj && !proc.killedBackground) {
7631 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007632 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7633 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007634 killed = true;
7635 proc.killedBackground = true;
7636 Process.killProcessQuiet(pid);
7637 }
7638 }
7639 }
7640 return killed;
7641 }
7642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 public final void startRunning(String pkg, String cls, String action,
7644 String data) {
7645 synchronized(this) {
7646 if (mStartRunning) {
7647 return;
7648 }
7649 mStartRunning = true;
7650 mTopComponent = pkg != null && cls != null
7651 ? new ComponentName(pkg, cls) : null;
7652 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7653 mTopData = data;
7654 if (!mSystemReady) {
7655 return;
7656 }
7657 }
7658
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007659 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 }
7661
7662 private void retrieveSettings() {
7663 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007664 String debugApp = Settings.Global.getString(
7665 resolver, Settings.Global.DEBUG_APP);
7666 boolean waitForDebugger = Settings.Global.getInt(
7667 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7668 boolean alwaysFinishActivities = Settings.Global.getInt(
7669 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670
7671 Configuration configuration = new Configuration();
7672 Settings.System.getConfiguration(resolver, configuration);
7673
7674 synchronized (this) {
7675 mDebugApp = mOrigDebugApp = debugApp;
7676 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7677 mAlwaysFinishActivities = alwaysFinishActivities;
7678 // This happens before any activities are started, so we can
7679 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007680 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007681 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 }
7683 }
7684
7685 public boolean testIsSystemReady() {
7686 // no need to synchronize(this) just to read & return the value
7687 return mSystemReady;
7688 }
7689
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007690 private static File getCalledPreBootReceiversFile() {
7691 File dataDir = Environment.getDataDirectory();
7692 File systemDir = new File(dataDir, "system");
7693 File fname = new File(systemDir, "called_pre_boots.dat");
7694 return fname;
7695 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007696
7697 static final int LAST_DONE_VERSION = 10000;
7698
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007699 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7700 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7701 File file = getCalledPreBootReceiversFile();
7702 FileInputStream fis = null;
7703 try {
7704 fis = new FileInputStream(file);
7705 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007706 int fvers = dis.readInt();
7707 if (fvers == LAST_DONE_VERSION) {
7708 String vers = dis.readUTF();
7709 String codename = dis.readUTF();
7710 String build = dis.readUTF();
7711 if (android.os.Build.VERSION.RELEASE.equals(vers)
7712 && android.os.Build.VERSION.CODENAME.equals(codename)
7713 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7714 int num = dis.readInt();
7715 while (num > 0) {
7716 num--;
7717 String pkg = dis.readUTF();
7718 String cls = dis.readUTF();
7719 lastDoneReceivers.add(new ComponentName(pkg, cls));
7720 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007721 }
7722 }
7723 } catch (FileNotFoundException e) {
7724 } catch (IOException e) {
7725 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7726 } finally {
7727 if (fis != null) {
7728 try {
7729 fis.close();
7730 } catch (IOException e) {
7731 }
7732 }
7733 }
7734 return lastDoneReceivers;
7735 }
7736
7737 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7738 File file = getCalledPreBootReceiversFile();
7739 FileOutputStream fos = null;
7740 DataOutputStream dos = null;
7741 try {
7742 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7743 fos = new FileOutputStream(file);
7744 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007745 dos.writeInt(LAST_DONE_VERSION);
7746 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007747 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007748 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007749 dos.writeInt(list.size());
7750 for (int i=0; i<list.size(); i++) {
7751 dos.writeUTF(list.get(i).getPackageName());
7752 dos.writeUTF(list.get(i).getClassName());
7753 }
7754 } catch (IOException e) {
7755 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7756 file.delete();
7757 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007758 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007759 if (dos != null) {
7760 try {
7761 dos.close();
7762 } catch (IOException e) {
7763 // TODO Auto-generated catch block
7764 e.printStackTrace();
7765 }
7766 }
7767 }
7768 }
7769
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007770 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 synchronized(this) {
7772 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007773 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 return;
7775 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007776
7777 // Check to see if there are any update receivers to run.
7778 if (!mDidUpdate) {
7779 if (mWaitingUpdate) {
7780 return;
7781 }
7782 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7783 List<ResolveInfo> ris = null;
7784 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007785 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007786 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007787 } catch (RemoteException e) {
7788 }
7789 if (ris != null) {
7790 for (int i=ris.size()-1; i>=0; i--) {
7791 if ((ris.get(i).activityInfo.applicationInfo.flags
7792 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7793 ris.remove(i);
7794 }
7795 }
7796 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007797
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007798 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007799
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007800 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007801 for (int i=0; i<ris.size(); i++) {
7802 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007803 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7804 if (lastDoneReceivers.contains(comp)) {
7805 ris.remove(i);
7806 i--;
7807 }
7808 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007809
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007810 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007811 for (int i=0; i<ris.size(); i++) {
7812 ActivityInfo ai = ris.get(i).activityInfo;
7813 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7814 doneReceivers.add(comp);
7815 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007816 for (int j=0; j<users.length; j++) {
7817 IIntentReceiver finisher = null;
7818 if (i == ris.size()-1 && j == users.length-1) {
7819 finisher = new IIntentReceiver.Stub() {
7820 public void performReceive(Intent intent, int resultCode,
7821 String data, Bundle extras, boolean ordered,
7822 boolean sticky, int sendingUser) {
7823 // The raw IIntentReceiver interface is called
7824 // with the AM lock held, so redispatch to
7825 // execute our code without the lock.
7826 mHandler.post(new Runnable() {
7827 public void run() {
7828 synchronized (ActivityManagerService.this) {
7829 mDidUpdate = true;
7830 }
7831 writeLastDonePreBootReceivers(doneReceivers);
7832 showBootMessage(mContext.getText(
7833 R.string.android_upgrading_complete),
7834 false);
7835 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007836 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007837 });
7838 }
7839 };
7840 }
7841 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7842 + " for user " + users[j]);
7843 broadcastIntentLocked(null, null, intent, null, finisher,
7844 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7845 users[j]);
7846 if (finisher != null) {
7847 mWaitingUpdate = true;
7848 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007849 }
7850 }
7851 }
7852 if (mWaitingUpdate) {
7853 return;
7854 }
7855 mDidUpdate = true;
7856 }
7857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007858 mSystemReady = true;
7859 if (!mStartRunning) {
7860 return;
7861 }
7862 }
7863
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007864 ArrayList<ProcessRecord> procsToKill = null;
7865 synchronized(mPidsSelfLocked) {
7866 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7867 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7868 if (!isAllowedWhileBooting(proc.info)){
7869 if (procsToKill == null) {
7870 procsToKill = new ArrayList<ProcessRecord>();
7871 }
7872 procsToKill.add(proc);
7873 }
7874 }
7875 }
7876
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007877 synchronized(this) {
7878 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007879 for (int i=procsToKill.size()-1; i>=0; i--) {
7880 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007881 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007882 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007883 }
7884 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007885
7886 // Now that we have cleaned up any update processes, we
7887 // are ready to start launching real processes and know that
7888 // we won't trample on them any more.
7889 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007890 }
7891
Joe Onorato8a9b2202010-02-26 18:56:32 -08007892 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007893 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 SystemClock.uptimeMillis());
7895
7896 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007897 // Make sure we have no pre-ready processes sitting around.
7898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7900 ResolveInfo ri = mContext.getPackageManager()
7901 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007902 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 CharSequence errorMsg = null;
7904 if (ri != null) {
7905 ActivityInfo ai = ri.activityInfo;
7906 ApplicationInfo app = ai.applicationInfo;
7907 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7908 mTopAction = Intent.ACTION_FACTORY_TEST;
7909 mTopData = null;
7910 mTopComponent = new ComponentName(app.packageName,
7911 ai.name);
7912 } else {
7913 errorMsg = mContext.getResources().getText(
7914 com.android.internal.R.string.factorytest_not_system);
7915 }
7916 } else {
7917 errorMsg = mContext.getResources().getText(
7918 com.android.internal.R.string.factorytest_no_action);
7919 }
7920 if (errorMsg != null) {
7921 mTopAction = null;
7922 mTopData = null;
7923 mTopComponent = null;
7924 Message msg = Message.obtain();
7925 msg.what = SHOW_FACTORY_ERROR_MSG;
7926 msg.getData().putCharSequence("msg", errorMsg);
7927 mHandler.sendMessage(msg);
7928 }
7929 }
7930 }
7931
7932 retrieveSettings();
7933
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007934 if (goingCallback != null) goingCallback.run();
7935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 synchronized (this) {
7937 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7938 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007939 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007940 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 if (apps != null) {
7942 int N = apps.size();
7943 int i;
7944 for (i=0; i<N; i++) {
7945 ApplicationInfo info
7946 = (ApplicationInfo)apps.get(i);
7947 if (info != null &&
7948 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007949 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 }
7951 }
7952 }
7953 } catch (RemoteException ex) {
7954 // pm is in same process, this will never happen.
7955 }
7956 }
7957
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007958 // Start up initial activity.
7959 mBooting = true;
7960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007962 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007963 Message msg = Message.obtain();
7964 msg.what = SHOW_UID_ERROR_MSG;
7965 mHandler.sendMessage(msg);
7966 }
7967 } catch (RemoteException e) {
7968 }
7969
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007970 long ident = Binder.clearCallingIdentity();
7971 try {
7972 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007973 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
7974 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007975 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7976 broadcastIntentLocked(null, null, intent,
7977 null, null, 0, null, null, null,
7978 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07007979 intent = new Intent(Intent.ACTION_USER_STARTING);
7980 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
7981 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
7982 broadcastIntentLocked(null, null, intent,
7983 null, new IIntentReceiver.Stub() {
7984 @Override
7985 public void performReceive(Intent intent, int resultCode, String data,
7986 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
7987 throws RemoteException {
7988 }
7989 }, 0, null, null,
7990 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08007991 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007992 } finally {
7993 Binder.restoreCallingIdentity(ident);
7994 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007995 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007996 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 }
7998 }
7999
Dan Egnorb7f03672009-12-09 16:22:32 -08008000 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008001 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008002 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008003 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008004 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 startAppProblemLocked(app);
8006 app.stopFreezingAllLocked();
8007 return handleAppCrashLocked(app);
8008 }
8009
Dan Egnorb7f03672009-12-09 16:22:32 -08008010 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008011 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008012 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008013 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008014 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8015 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 startAppProblemLocked(app);
8017 app.stopFreezingAllLocked();
8018 }
8019
8020 /**
8021 * Generate a process error record, suitable for attachment to a ProcessRecord.
8022 *
8023 * @param app The ProcessRecord in which the error occurred.
8024 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8025 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008026 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008027 * @param shortMsg Short message describing the crash.
8028 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008029 * @param stackTrace Full crash stack trace, may be null.
8030 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 * @return Returns a fully-formed AppErrorStateInfo record.
8032 */
8033 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008034 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 report.condition = condition;
8038 report.processName = app.processName;
8039 report.pid = app.pid;
8040 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008041 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 report.shortMsg = shortMsg;
8043 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008044 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008045
8046 return report;
8047 }
8048
Dan Egnor42471dd2010-01-07 17:25:22 -08008049 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 synchronized (this) {
8051 app.crashing = false;
8052 app.crashingReport = null;
8053 app.notResponding = false;
8054 app.notRespondingReport = null;
8055 if (app.anrDialog == fromDialog) {
8056 app.anrDialog = null;
8057 }
8058 if (app.waitDialog == fromDialog) {
8059 app.waitDialog = null;
8060 }
8061 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008062 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008063 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008064 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008065 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008066 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 }
8069 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008070
Dan Egnorb7f03672009-12-09 16:22:32 -08008071 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008072 if (mHeadless) {
8073 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8074 return false;
8075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 long now = SystemClock.uptimeMillis();
8077
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008078 Long crashTime;
8079 if (!app.isolated) {
8080 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8081 } else {
8082 crashTime = null;
8083 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008084 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008086 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008088 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008089 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008090 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8091 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008093 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008095 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8096 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008097 }
8098 }
8099 if (!app.persistent) {
8100 // We don't want to start this process again until the user
8101 // explicitly does so... but for persistent process, we really
8102 // need to keep it running. If a persistent process is actually
8103 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008104 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008106 if (!app.isolated) {
8107 // XXX We don't have a way to mark isolated processes
8108 // as bad, since they don't have a peristent identity.
8109 mBadProcesses.put(app.info.processName, app.uid, now);
8110 mProcessCrashTimes.remove(app.info.processName, app.uid);
8111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008112 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008114 // Don't let services in this process be restarted and potentially
8115 // annoy the user repeatedly. Unless it is persistent, since those
8116 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008117 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008118 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008119 return false;
8120 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008121 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008122 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008123 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008124 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008125 // If the top running activity is from this crashing
8126 // process, then terminate it to avoid getting in a loop.
8127 Slog.w(TAG, " Force finishing activity "
8128 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008129 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008130 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008131 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008132 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008133 // stopped, to avoid a situation where one will get
8134 // re-start our crashing activity once it gets resumed again.
8135 index--;
8136 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008137 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008138 if (r.state == ActivityState.RESUMED
8139 || r.state == ActivityState.PAUSING
8140 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008141 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008142 Slog.w(TAG, " Force finishing activity "
8143 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008144 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008145 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008146 }
8147 }
8148 }
8149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 }
8151
8152 // Bump up the crash count of any services currently running in the proc.
8153 if (app.services.size() != 0) {
8154 // Any services running in the application need to be placed
8155 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008156 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008158 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 sr.crashCount++;
8160 }
8161 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008162
8163 // If the crashing process is what we consider to be the "home process" and it has been
8164 // replaced by a third-party app, clear the package preferred activities from packages
8165 // with a home activity running in the process to prevent a repeatedly crashing app
8166 // from blocking the user to manually clear the list.
8167 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8168 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8169 Iterator it = mHomeProcess.activities.iterator();
8170 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008171 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008172 if (r.isHomeActivity) {
8173 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8174 try {
8175 ActivityThread.getPackageManager()
8176 .clearPackagePreferredActivities(r.packageName);
8177 } catch (RemoteException c) {
8178 // pm is in same process, this will never happen.
8179 }
8180 }
8181 }
8182 }
8183
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008184 if (!app.isolated) {
8185 // XXX Can't keep track of crash times for isolated processes,
8186 // because they don't have a perisistent identity.
8187 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8188 }
8189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 return true;
8191 }
8192
8193 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008194 if (app.userId == mCurrentUserId) {
8195 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8196 mContext, app.info.packageName, app.info.flags);
8197 } else {
8198 // If this app is not running under the current user, then we
8199 // can't give it a report button because that would require
8200 // launching the report UI under a different user.
8201 app.errorReportReceiver = null;
8202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 skipCurrentReceiverLocked(app);
8204 }
8205
8206 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008207 for (BroadcastQueue queue : mBroadcastQueues) {
8208 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 }
8210 }
8211
Dan Egnor60d87622009-12-16 16:32:58 -08008212 /**
8213 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8214 * The application process will exit immediately after this call returns.
8215 * @param app object of the crashing app, null for the system server
8216 * @param crashInfo describing the exception
8217 */
8218 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008219 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008220 final String processName = app == null ? "system_server"
8221 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008222
8223 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008224 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008225 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008226 crashInfo.exceptionClassName,
8227 crashInfo.exceptionMessage,
8228 crashInfo.throwFileName,
8229 crashInfo.throwLineNumber);
8230
Jeff Sharkeya353d262011-10-28 11:12:06 -07008231 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008232
8233 crashApplication(r, crashInfo);
8234 }
8235
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008236 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008237 IBinder app,
8238 int violationMask,
8239 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008240 ProcessRecord r = findAppProcess(app, "StrictMode");
8241 if (r == null) {
8242 return;
8243 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008244
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008245 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008246 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008247 boolean logIt = true;
8248 synchronized (mAlreadyLoggedViolatedStacks) {
8249 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8250 logIt = false;
8251 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008252 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008253 // the relative pain numbers, without logging all
8254 // the stack traces repeatedly. We'd want to do
8255 // likewise in the client code, which also does
8256 // dup suppression, before the Binder call.
8257 } else {
8258 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8259 mAlreadyLoggedViolatedStacks.clear();
8260 }
8261 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8262 }
8263 }
8264 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008265 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008266 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008267 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008268
8269 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8270 AppErrorResult result = new AppErrorResult();
8271 synchronized (this) {
8272 final long origId = Binder.clearCallingIdentity();
8273
8274 Message msg = Message.obtain();
8275 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8276 HashMap<String, Object> data = new HashMap<String, Object>();
8277 data.put("result", result);
8278 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008279 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008280 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008281 msg.obj = data;
8282 mHandler.sendMessage(msg);
8283
8284 Binder.restoreCallingIdentity(origId);
8285 }
8286 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008287 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008288 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008289 }
8290
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008291 // Depending on the policy in effect, there could be a bunch of
8292 // these in quick succession so we try to batch these together to
8293 // minimize disk writes, number of dropbox entries, and maximize
8294 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008295 private void logStrictModeViolationToDropBox(
8296 ProcessRecord process,
8297 StrictMode.ViolationInfo info) {
8298 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008299 return;
8300 }
8301 final boolean isSystemApp = process == null ||
8302 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8303 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008304 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008305 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8306 final DropBoxManager dbox = (DropBoxManager)
8307 mContext.getSystemService(Context.DROPBOX_SERVICE);
8308
8309 // Exit early if the dropbox isn't configured to accept this report type.
8310 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8311
8312 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008313 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008314 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8315 synchronized (sb) {
8316 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008317 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008318 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8319 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008320 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8321 if (info.violationNumThisLoop != 0) {
8322 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8323 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008324 if (info.numAnimationsRunning != 0) {
8325 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8326 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008327 if (info.broadcastIntentAction != null) {
8328 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8329 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008330 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008331 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008332 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008333 if (info.numInstances != -1) {
8334 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8335 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008336 if (info.tags != null) {
8337 for (String tag : info.tags) {
8338 sb.append("Span-Tag: ").append(tag).append("\n");
8339 }
8340 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008341 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008342 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8343 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008344 }
8345 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008346
8347 // Only buffer up to ~64k. Various logging bits truncate
8348 // things at 128k.
8349 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008350 }
8351
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008352 // Flush immediately if the buffer's grown too large, or this
8353 // is a non-system app. Non-system apps are isolated with a
8354 // different tag & policy and not batched.
8355 //
8356 // Batching is useful during internal testing with
8357 // StrictMode settings turned up high. Without batching,
8358 // thousands of separate files could be created on boot.
8359 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008360 new Thread("Error dump: " + dropboxTag) {
8361 @Override
8362 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008363 String report;
8364 synchronized (sb) {
8365 report = sb.toString();
8366 sb.delete(0, sb.length());
8367 sb.trimToSize();
8368 }
8369 if (report.length() != 0) {
8370 dbox.addText(dropboxTag, report);
8371 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008372 }
8373 }.start();
8374 return;
8375 }
8376
8377 // System app batching:
8378 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008379 // An existing dropbox-writing thread is outstanding, so
8380 // we don't need to start it up. The existing thread will
8381 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008382 return;
8383 }
8384
8385 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8386 // (After this point, we shouldn't access AMS internal data structures.)
8387 new Thread("Error dump: " + dropboxTag) {
8388 @Override
8389 public void run() {
8390 // 5 second sleep to let stacks arrive and be batched together
8391 try {
8392 Thread.sleep(5000); // 5 seconds
8393 } catch (InterruptedException e) {}
8394
8395 String errorReport;
8396 synchronized (mStrictModeBuffer) {
8397 errorReport = mStrictModeBuffer.toString();
8398 if (errorReport.length() == 0) {
8399 return;
8400 }
8401 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8402 mStrictModeBuffer.trimToSize();
8403 }
8404 dbox.addText(dropboxTag, errorReport);
8405 }
8406 }.start();
8407 }
8408
Dan Egnor60d87622009-12-16 16:32:58 -08008409 /**
8410 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8411 * @param app object of the crashing app, null for the system server
8412 * @param tag reported by the caller
8413 * @param crashInfo describing the context of the error
8414 * @return true if the process should exit immediately (WTF is fatal)
8415 */
8416 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008417 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008418 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008419 final String processName = app == null ? "system_server"
8420 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008421
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008422 EventLog.writeEvent(EventLogTags.AM_WTF,
8423 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008424 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008425 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008426 tag, crashInfo.exceptionMessage);
8427
Jeff Sharkeya353d262011-10-28 11:12:06 -07008428 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008429
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008430 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008431 Settings.Global.getInt(mContext.getContentResolver(),
8432 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008433 crashApplication(r, crashInfo);
8434 return true;
8435 } else {
8436 return false;
8437 }
8438 }
8439
8440 /**
8441 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8442 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8443 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008444 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008445 if (app == null) {
8446 return null;
8447 }
8448
8449 synchronized (this) {
8450 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8451 final int NA = apps.size();
8452 for (int ia=0; ia<NA; ia++) {
8453 ProcessRecord p = apps.valueAt(ia);
8454 if (p.thread != null && p.thread.asBinder() == app) {
8455 return p;
8456 }
8457 }
8458 }
8459
Dianne Hackborncb44d962011-03-10 17:02:27 -08008460 Slog.w(TAG, "Can't find mystery application for " + reason
8461 + " from pid=" + Binder.getCallingPid()
8462 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008463 return null;
8464 }
8465 }
8466
8467 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008468 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8469 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008470 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008471 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8472 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008473 // Watchdog thread ends up invoking this function (with
8474 // a null ProcessRecord) to add the stack file to dropbox.
8475 // Do not acquire a lock on this (am) in such cases, as it
8476 // could cause a potential deadlock, if and when watchdog
8477 // is invoked due to unavailability of lock on am and it
8478 // would prevent watchdog from killing system_server.
8479 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008480 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008481 return;
8482 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008483 // Note: ProcessRecord 'process' is guarded by the service
8484 // instance. (notably process.pkgList, which could otherwise change
8485 // concurrently during execution of this method)
8486 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008487 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008488 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008489 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008490 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8491 for (String pkg : process.pkgList) {
8492 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008493 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008494 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008495 if (pi != null) {
8496 sb.append(" v").append(pi.versionCode);
8497 if (pi.versionName != null) {
8498 sb.append(" (").append(pi.versionName).append(")");
8499 }
8500 }
8501 } catch (RemoteException e) {
8502 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008503 }
Dan Egnora455d192010-03-12 08:52:28 -08008504 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008505 }
Dan Egnora455d192010-03-12 08:52:28 -08008506 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008507 }
8508
8509 private static String processClass(ProcessRecord process) {
8510 if (process == null || process.pid == MY_PID) {
8511 return "system_server";
8512 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8513 return "system_app";
8514 } else {
8515 return "data_app";
8516 }
8517 }
8518
8519 /**
8520 * Write a description of an error (crash, WTF, ANR) to the drop box.
8521 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8522 * @param process which caused the error, null means the system server
8523 * @param activity which triggered the error, null if unknown
8524 * @param parent activity related to the error, null if unknown
8525 * @param subject line related to the error, null if absent
8526 * @param report in long form describing the error, null if absent
8527 * @param logFile to include in the report, null if none
8528 * @param crashInfo giving an application stack trace, null if absent
8529 */
8530 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008531 ProcessRecord process, String processName, ActivityRecord activity,
8532 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008533 final String report, final File logFile,
8534 final ApplicationErrorReport.CrashInfo crashInfo) {
8535 // NOTE -- this must never acquire the ActivityManagerService lock,
8536 // otherwise the watchdog may be prevented from resetting the system.
8537
8538 final String dropboxTag = processClass(process) + "_" + eventType;
8539 final DropBoxManager dbox = (DropBoxManager)
8540 mContext.getSystemService(Context.DROPBOX_SERVICE);
8541
8542 // Exit early if the dropbox isn't configured to accept this report type.
8543 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8544
8545 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008546 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008547 if (activity != null) {
8548 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8549 }
8550 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8551 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8552 }
8553 if (parent != null && parent != activity) {
8554 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8555 }
8556 if (subject != null) {
8557 sb.append("Subject: ").append(subject).append("\n");
8558 }
8559 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008560 if (Debug.isDebuggerConnected()) {
8561 sb.append("Debugger: Connected\n");
8562 }
Dan Egnora455d192010-03-12 08:52:28 -08008563 sb.append("\n");
8564
8565 // Do the rest in a worker thread to avoid blocking the caller on I/O
8566 // (After this point, we shouldn't access AMS internal data structures.)
8567 Thread worker = new Thread("Error dump: " + dropboxTag) {
8568 @Override
8569 public void run() {
8570 if (report != null) {
8571 sb.append(report);
8572 }
8573 if (logFile != null) {
8574 try {
8575 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8576 } catch (IOException e) {
8577 Slog.e(TAG, "Error reading " + logFile, e);
8578 }
8579 }
8580 if (crashInfo != null && crashInfo.stackTrace != null) {
8581 sb.append(crashInfo.stackTrace);
8582 }
8583
Jeff Sharkey625239a2012-09-26 22:03:49 -07008584 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8585 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008586 if (lines > 0) {
8587 sb.append("\n");
8588
8589 // Merge several logcat streams, and take the last N lines
8590 InputStreamReader input = null;
8591 try {
8592 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8593 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8594 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8595
8596 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8597 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8598 input = new InputStreamReader(logcat.getInputStream());
8599
8600 int num;
8601 char[] buf = new char[8192];
8602 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8603 } catch (IOException e) {
8604 Slog.e(TAG, "Error running logcat", e);
8605 } finally {
8606 if (input != null) try { input.close(); } catch (IOException e) {}
8607 }
8608 }
8609
8610 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008611 }
Dan Egnora455d192010-03-12 08:52:28 -08008612 };
8613
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008614 if (process == null) {
8615 // If process is null, we are being called from some internal code
8616 // and may be about to die -- run this synchronously.
8617 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008618 } else {
8619 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008620 }
8621 }
8622
8623 /**
8624 * Bring up the "unexpected error" dialog box for a crashing app.
8625 * Deal with edge cases (intercepts from instrumented applications,
8626 * ActivityController, error intent receivers, that sort of thing).
8627 * @param r the application crashing
8628 * @param crashInfo describing the failure
8629 */
8630 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008631 long timeMillis = System.currentTimeMillis();
8632 String shortMsg = crashInfo.exceptionClassName;
8633 String longMsg = crashInfo.exceptionMessage;
8634 String stackTrace = crashInfo.stackTrace;
8635 if (shortMsg != null && longMsg != null) {
8636 longMsg = shortMsg + ": " + longMsg;
8637 } else if (shortMsg != null) {
8638 longMsg = shortMsg;
8639 }
8640
Dan Egnor60d87622009-12-16 16:32:58 -08008641 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008643 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 try {
8645 String name = r != null ? r.processName : null;
8646 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008647 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008648 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008649 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 + " at watcher's request");
8651 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008652 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 }
8654 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008655 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 }
8657 }
8658
8659 final long origId = Binder.clearCallingIdentity();
8660
8661 // If this process is running instrumentation, finish it.
8662 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008663 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008665 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8666 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 Bundle info = new Bundle();
8668 info.putString("shortMsg", shortMsg);
8669 info.putString("longMsg", longMsg);
8670 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8671 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008672 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008673 }
8674
Dan Egnor60d87622009-12-16 16:32:58 -08008675 // If we can't identify the process or it's already exceeded its crash quota,
8676 // quit right away without showing a crash dialog.
8677 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008679 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 }
8681
8682 Message msg = Message.obtain();
8683 msg.what = SHOW_ERROR_MSG;
8684 HashMap data = new HashMap();
8685 data.put("result", result);
8686 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 msg.obj = data;
8688 mHandler.sendMessage(msg);
8689
8690 Binder.restoreCallingIdentity(origId);
8691 }
8692
8693 int res = result.get();
8694
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008695 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008697 if (r != null && !r.isolated) {
8698 // XXX Can't keep track of crash time for isolated processes,
8699 // since they don't have a persistent identity.
8700 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 SystemClock.uptimeMillis());
8702 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008703 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008704 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008705 }
8706 }
8707
8708 if (appErrorIntent != null) {
8709 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008710 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008711 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008712 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008716
8717 Intent createAppErrorIntentLocked(ProcessRecord r,
8718 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8719 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008720 if (report == null) {
8721 return null;
8722 }
8723 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8724 result.setComponent(r.errorReportReceiver);
8725 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8726 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8727 return result;
8728 }
8729
Dan Egnorb7f03672009-12-09 16:22:32 -08008730 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8731 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008732 if (r.errorReportReceiver == null) {
8733 return null;
8734 }
8735
8736 if (!r.crashing && !r.notResponding) {
8737 return null;
8738 }
8739
Dan Egnorb7f03672009-12-09 16:22:32 -08008740 ApplicationErrorReport report = new ApplicationErrorReport();
8741 report.packageName = r.info.packageName;
8742 report.installerPackageName = r.errorReportReceiver.getPackageName();
8743 report.processName = r.processName;
8744 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008745 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008746
Dan Egnorb7f03672009-12-09 16:22:32 -08008747 if (r.crashing) {
8748 report.type = ApplicationErrorReport.TYPE_CRASH;
8749 report.crashInfo = crashInfo;
8750 } else if (r.notResponding) {
8751 report.type = ApplicationErrorReport.TYPE_ANR;
8752 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008753
Dan Egnorb7f03672009-12-09 16:22:32 -08008754 report.anrInfo.activity = r.notRespondingReport.tag;
8755 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8756 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008757 }
8758
Dan Egnorb7f03672009-12-09 16:22:32 -08008759 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008760 }
8761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008763 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 // assume our apps are happy - lazy create the list
8765 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8766
Dianne Hackborn0c380492012-08-20 17:23:30 -07008767 final boolean allUsers = ActivityManager.checkUidPermission(
8768 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8769 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8770 int userId = UserHandle.getUserId(Binder.getCallingUid());
8771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 synchronized (this) {
8773
8774 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008775 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8776 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008777 if (!allUsers && app.userId != userId) {
8778 continue;
8779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8781 // This one's in trouble, so we'll generate a report for it
8782 // crashes are higher priority (in case there's a crash *and* an anr)
8783 ActivityManager.ProcessErrorStateInfo report = null;
8784 if (app.crashing) {
8785 report = app.crashingReport;
8786 } else if (app.notResponding) {
8787 report = app.notRespondingReport;
8788 }
8789
8790 if (report != null) {
8791 if (errList == null) {
8792 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8793 }
8794 errList.add(report);
8795 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008796 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008797 " crashing = " + app.crashing +
8798 " notResponding = " + app.notResponding);
8799 }
8800 }
8801 }
8802 }
8803
8804 return errList;
8805 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008806
8807 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008808 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008809 if (currApp != null) {
8810 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8811 }
8812 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008813 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8814 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008815 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8816 if (currApp != null) {
8817 currApp.lru = 0;
8818 }
8819 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008820 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008821 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8822 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8823 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8824 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8825 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8826 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8827 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8828 } else {
8829 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8830 }
8831 }
8832
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008833 private void fillInProcMemInfo(ProcessRecord app,
8834 ActivityManager.RunningAppProcessInfo outInfo) {
8835 outInfo.pid = app.pid;
8836 outInfo.uid = app.info.uid;
8837 if (mHeavyWeightProcess == app) {
8838 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8839 }
8840 if (app.persistent) {
8841 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8842 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008843 if (app.hasActivities) {
8844 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8845 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008846 outInfo.lastTrimLevel = app.trimMemoryLevel;
8847 int adj = app.curAdj;
8848 outInfo.importance = oomAdjToImportance(adj, outInfo);
8849 outInfo.importanceReasonCode = app.adjTypeCode;
8850 }
8851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008853 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 // Lazy instantiation of list
8855 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008856 final boolean allUsers = ActivityManager.checkUidPermission(
8857 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8858 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8859 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008860 synchronized (this) {
8861 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008862 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8863 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008864 if (!allUsers && app.userId != userId) {
8865 continue;
8866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8868 // Generate process state info for running application
8869 ActivityManager.RunningAppProcessInfo currApp =
8870 new ActivityManager.RunningAppProcessInfo(app.processName,
8871 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008872 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008873 if (app.adjSource instanceof ProcessRecord) {
8874 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008875 currApp.importanceReasonImportance = oomAdjToImportance(
8876 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008877 } else if (app.adjSource instanceof ActivityRecord) {
8878 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008879 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8880 }
8881 if (app.adjTarget instanceof ComponentName) {
8882 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8883 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008884 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 // + " lru=" + currApp.lru);
8886 if (runList == null) {
8887 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8888 }
8889 runList.add(currApp);
8890 }
8891 }
8892 }
8893 return runList;
8894 }
8895
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008896 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008897 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008898 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8899 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8900 if (runningApps != null && runningApps.size() > 0) {
8901 Set<String> extList = new HashSet<String>();
8902 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8903 if (app.pkgList != null) {
8904 for (String pkg : app.pkgList) {
8905 extList.add(pkg);
8906 }
8907 }
8908 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008909 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008910 for (String pkg : extList) {
8911 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008912 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008913 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8914 retList.add(info);
8915 }
8916 } catch (RemoteException e) {
8917 }
8918 }
8919 }
8920 return retList;
8921 }
8922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008924 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8925 enforceNotIsolatedCaller("getMyMemoryState");
8926 synchronized (this) {
8927 ProcessRecord proc;
8928 synchronized (mPidsSelfLocked) {
8929 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8930 }
8931 fillInProcMemInfo(proc, outInfo);
8932 }
8933 }
8934
8935 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 if (checkCallingPermission(android.Manifest.permission.DUMP)
8938 != PackageManager.PERMISSION_GRANTED) {
8939 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8940 + Binder.getCallingPid()
8941 + ", uid=" + Binder.getCallingUid()
8942 + " without permission "
8943 + android.Manifest.permission.DUMP);
8944 return;
8945 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008946
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008948 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008950
8951 int opti = 0;
8952 while (opti < args.length) {
8953 String opt = args[opti];
8954 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8955 break;
8956 }
8957 opti++;
8958 if ("-a".equals(opt)) {
8959 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008960 } else if ("-c".equals(opt)) {
8961 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008962 } else if ("-h".equals(opt)) {
8963 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008964 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008965 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008966 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008967 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8969 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008970 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008971 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008972 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008973 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008974 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008976 pw.println(" all: dump all activities");
8977 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008978 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008979 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8980 pw.println(" a partial substring in a component name, a");
8981 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008982 pw.println(" -a: include all available server state.");
8983 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 } else {
8986 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008987 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008988 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008989
8990 long origId = Binder.clearCallingIdentity();
8991 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 // Is the caller requesting to dump a particular piece of data?
8993 if (opti < args.length) {
8994 String cmd = args[opti];
8995 opti++;
8996 if ("activities".equals(cmd) || "a".equals(cmd)) {
8997 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009000 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009001 String[] newArgs;
9002 String name;
9003 if (opti >= args.length) {
9004 name = null;
9005 newArgs = EMPTY_STRING_ARRAY;
9006 } else {
9007 name = args[opti];
9008 opti++;
9009 newArgs = new String[args.length - opti];
9010 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9011 args.length - opti);
9012 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009014 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 String[] newArgs;
9018 String name;
9019 if (opti >= args.length) {
9020 name = null;
9021 newArgs = EMPTY_STRING_ARRAY;
9022 } else {
9023 name = args[opti];
9024 opti++;
9025 newArgs = new String[args.length - opti];
9026 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9027 args.length - opti);
9028 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009030 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009033 String[] newArgs;
9034 String name;
9035 if (opti >= args.length) {
9036 name = null;
9037 newArgs = EMPTY_STRING_ARRAY;
9038 } else {
9039 name = args[opti];
9040 opti++;
9041 newArgs = new String[args.length - opti];
9042 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9043 args.length - opti);
9044 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009045 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009046 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009047 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009048 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9049 synchronized (this) {
9050 dumpOomLocked(fd, pw, args, opti, true);
9051 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009052 } else if ("provider".equals(cmd)) {
9053 String[] newArgs;
9054 String name;
9055 if (opti >= args.length) {
9056 name = null;
9057 newArgs = EMPTY_STRING_ARRAY;
9058 } else {
9059 name = args[opti];
9060 opti++;
9061 newArgs = new String[args.length - opti];
9062 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9063 }
9064 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9065 pw.println("No providers match: " + name);
9066 pw.println("Use -h for help.");
9067 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9069 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009071 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009073 String[] newArgs;
9074 String name;
9075 if (opti >= args.length) {
9076 name = null;
9077 newArgs = EMPTY_STRING_ARRAY;
9078 } else {
9079 name = args[opti];
9080 opti++;
9081 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009082 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9083 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009084 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009085 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009086 pw.println("No services match: " + name);
9087 pw.println("Use -h for help.");
9088 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009089 } else if ("package".equals(cmd)) {
9090 String[] newArgs;
9091 if (opti >= args.length) {
9092 pw.println("package: no package name specified");
9093 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094 } else {
9095 dumpPackage = args[opti];
9096 opti++;
9097 newArgs = new String[args.length - opti];
9098 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9099 args.length - opti);
9100 args = newArgs;
9101 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009102 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009103 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9105 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009106 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009108 } else {
9109 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009110 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9111 pw.println("Bad activity command, or no activities match: " + cmd);
9112 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009113 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009114 }
9115 if (!more) {
9116 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009117 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009118 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009119 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009120
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 // No piece of data specified, dump everything.
9122 synchronized (this) {
9123 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009124 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009125 if (needSep) {
9126 pw.println(" ");
9127 }
9128 if (dumpAll) {
9129 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009130 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009132 if (needSep) {
9133 pw.println(" ");
9134 }
9135 if (dumpAll) {
9136 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009137 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009139 if (needSep) {
9140 pw.println(" ");
9141 }
9142 if (dumpAll) {
9143 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009144 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009145 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009146 if (needSep) {
9147 pw.println(" ");
9148 }
9149 if (dumpAll) {
9150 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009152 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009153 if (needSep) {
9154 pw.println(" ");
9155 }
9156 if (dumpAll) {
9157 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009159 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009161 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009162 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009163
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009165 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009166 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9167 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009168 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9169 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009170 pw.println(" ");
9171 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009172 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9173 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009174 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009177 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009178 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009179 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009180 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009183 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009184 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009185 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009186 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9187 pw.println(" ");
9188 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009189 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009191 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009192 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009193 pw.println(" ");
9194 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009195 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009196 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009199 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009200 if (mMainStack.mPausingActivity != null) {
9201 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009202 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009203 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009205 if (dumpAll) {
9206 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9207 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009208 pw.println(" mDismissKeyguardOnNextActivity: "
9209 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009211
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009212 if (mRecentTasks.size() > 0) {
9213 pw.println();
9214 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009215
9216 final int N = mRecentTasks.size();
9217 for (int i=0; i<N; i++) {
9218 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009219 if (dumpPackage != null) {
9220 if (tr.realActivity == null ||
9221 !dumpPackage.equals(tr.realActivity)) {
9222 continue;
9223 }
9224 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009225 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9226 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009227 if (dumpAll) {
9228 mRecentTasks.get(i).dump(pw, " ");
9229 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 }
9231 }
9232
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009233 if (dumpAll) {
9234 pw.println(" ");
9235 pw.println(" mCurTask: " + mCurTask);
9236 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237
9238 return true;
9239 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009240
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009241 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009242 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 boolean needSep = false;
9244 int numPers = 0;
9245
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9247
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9250 final int NA = procs.size();
9251 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009252 ProcessRecord r = procs.valueAt(ia);
9253 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9254 continue;
9255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009256 if (!needSep) {
9257 pw.println(" All known processes:");
9258 needSep = true;
9259 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009260 pw.print(r.persistent ? " *PERS*" : " *APP*");
9261 pw.print(" UID "); pw.print(procs.keyAt(ia));
9262 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 r.dump(pw, " ");
9264 if (r.persistent) {
9265 numPers++;
9266 }
9267 }
9268 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009270
9271 if (mIsolatedProcesses.size() > 0) {
9272 if (needSep) pw.println(" ");
9273 needSep = true;
9274 pw.println(" Isolated process list (sorted by uid):");
9275 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9276 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9277 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9278 continue;
9279 }
9280 pw.println(String.format("%sIsolated #%2d: %s",
9281 " ", i, r.toString()));
9282 }
9283 }
9284
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009285 if (mLruProcesses.size() > 0) {
9286 if (needSep) pw.println(" ");
9287 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009288 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009289 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009290 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009291 needSep = true;
9292 }
9293
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 if (dumpAll) {
9295 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009296 boolean printed = false;
9297 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9298 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9299 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9300 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009302 if (!printed) {
9303 if (needSep) pw.println(" ");
9304 needSep = true;
9305 pw.println(" PID mappings:");
9306 printed = true;
9307 }
9308 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9309 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009310 }
9311 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009312 }
9313
9314 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009315 synchronized (mPidsSelfLocked) {
9316 boolean printed = false;
9317 for (int i=0; i<mForegroundProcesses.size(); i++) {
9318 ProcessRecord r = mPidsSelfLocked.get(
9319 mForegroundProcesses.valueAt(i).pid);
9320 if (dumpPackage != null && (r == null
9321 || !dumpPackage.equals(r.info.packageName))) {
9322 continue;
9323 }
9324 if (!printed) {
9325 if (needSep) pw.println(" ");
9326 needSep = true;
9327 pw.println(" Foreground Processes:");
9328 printed = true;
9329 }
9330 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9331 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009333 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009334 }
9335
9336 if (mPersistentStartingProcesses.size() > 0) {
9337 if (needSep) pw.println(" ");
9338 needSep = true;
9339 pw.println(" Persisent processes that are starting:");
9340 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009341 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009344 if (mRemovedProcesses.size() > 0) {
9345 if (needSep) pw.println(" ");
9346 needSep = true;
9347 pw.println(" Processes that are being removed:");
9348 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009349 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009350 }
9351
9352 if (mProcessesOnHold.size() > 0) {
9353 if (needSep) pw.println(" ");
9354 needSep = true;
9355 pw.println(" Processes that are on old until the system is ready:");
9356 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009357 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009359
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009360 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361
9362 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009363 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009364 long now = SystemClock.uptimeMillis();
9365 for (Map.Entry<String, SparseArray<Long>> procs
9366 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009367 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009368 SparseArray<Long> uids = procs.getValue();
9369 final int N = uids.size();
9370 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009371 int puid = uids.keyAt(i);
9372 ProcessRecord r = mProcessNames.get(pname, puid);
9373 if (dumpPackage != null && (r == null
9374 || !dumpPackage.equals(r.info.packageName))) {
9375 continue;
9376 }
9377 if (!printed) {
9378 if (needSep) pw.println(" ");
9379 needSep = true;
9380 pw.println(" Time since processes crashed:");
9381 printed = true;
9382 }
9383 pw.print(" Process "); pw.print(pname);
9384 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009385 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009386 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9387 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009388 }
9389 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009392 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009393 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009394 for (Map.Entry<String, SparseArray<Long>> procs
9395 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009396 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009397 SparseArray<Long> uids = procs.getValue();
9398 final int N = uids.size();
9399 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009400 int puid = uids.keyAt(i);
9401 ProcessRecord r = mProcessNames.get(pname, puid);
9402 if (dumpPackage != null && (r == null
9403 || !dumpPackage.equals(r.info.packageName))) {
9404 continue;
9405 }
9406 if (!printed) {
9407 if (needSep) pw.println(" ");
9408 needSep = true;
9409 pw.println(" Bad processes:");
9410 }
9411 pw.print(" Bad process "); pw.print(pname);
9412 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009413 pw.print(": crashed at time ");
9414 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415 }
9416 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009420 pw.println(" mStartedUsers:");
9421 for (int i=0; i<mStartedUsers.size(); i++) {
9422 UserStartedState uss = mStartedUsers.valueAt(i);
9423 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009424 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009425 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009426 pw.print(" mStartedUserArray: [");
9427 for (int i=0; i<mStartedUserArray.length; i++) {
9428 if (i > 0) pw.print(", ");
9429 pw.print(mStartedUserArray[i]);
9430 }
9431 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009432 pw.print(" mUserLru: [");
9433 for (int i=0; i<mUserLru.size(); i++) {
9434 if (i > 0) pw.print(", ");
9435 pw.print(mUserLru.get(i));
9436 }
9437 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009438 if (dumpAll) {
9439 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9440 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009441 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009442 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009443 if (dumpAll) {
9444 StringBuilder sb = new StringBuilder(128);
9445 sb.append(" mPreviousProcessVisibleTime: ");
9446 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9447 pw.println(sb);
9448 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009449 if (mHeavyWeightProcess != null) {
9450 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9451 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009453 if (dumpAll) {
9454 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009455 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009456 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009457 for (Map.Entry<String, Integer> entry
9458 : mCompatModePackages.getPackages().entrySet()) {
9459 String pkg = entry.getKey();
9460 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9462 continue;
9463 }
9464 if (!printed) {
9465 pw.println(" mScreenCompatPackages:");
9466 printed = true;
9467 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009468 pw.print(" "); pw.print(pkg); pw.print(": ");
9469 pw.print(mode); pw.println();
9470 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009471 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009472 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009473 if (mSleeping || mWentToSleep || mLockScreenShown) {
9474 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9475 + " mLockScreenShown " + mLockScreenShown);
9476 }
9477 if (mShuttingDown) {
9478 pw.println(" mShuttingDown=" + mShuttingDown);
9479 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009480 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9481 || mOrigWaitForDebugger) {
9482 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9483 + " mDebugTransient=" + mDebugTransient
9484 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9485 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009486 if (mOpenGlTraceApp != null) {
9487 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9488 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009489 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9490 || mProfileFd != null) {
9491 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9492 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9493 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9494 + mAutoStopProfiler);
9495 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009496 if (mAlwaysFinishActivities || mController != null) {
9497 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9498 + " mController=" + mController);
9499 }
9500 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009501 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009503 + " mProcessesReady=" + mProcessesReady
9504 + " mSystemReady=" + mSystemReady);
9505 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009506 + " mBooted=" + mBooted
9507 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009508 pw.print(" mLastPowerCheckRealtime=");
9509 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9510 pw.println("");
9511 pw.print(" mLastPowerCheckUptime=");
9512 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9513 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009514 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9515 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009516 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009517 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9518 + " mNumHiddenProcs=" + mNumHiddenProcs
9519 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009520 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009521 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522
9523 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 }
9525
Dianne Hackborn287952c2010-09-22 22:34:31 -07009526 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009527 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009528 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009530 long now = SystemClock.uptimeMillis();
9531 for (int i=0; i<mProcessesToGc.size(); i++) {
9532 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009533 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9534 continue;
9535 }
9536 if (!printed) {
9537 if (needSep) pw.println(" ");
9538 needSep = true;
9539 pw.println(" Processes that are waiting to GC:");
9540 printed = true;
9541 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009542 pw.print(" Process "); pw.println(proc);
9543 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9544 pw.print(", last gced=");
9545 pw.print(now-proc.lastRequestedGc);
9546 pw.print(" ms ago, last lowMem=");
9547 pw.print(now-proc.lastLowMemory);
9548 pw.println(" ms ago");
9549
9550 }
9551 }
9552 return needSep;
9553 }
9554
9555 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9556 int opti, boolean dumpAll) {
9557 boolean needSep = false;
9558
9559 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009560 if (needSep) pw.println(" ");
9561 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009562 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009563 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009564 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009565 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9566 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9567 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9568 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9569 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009570 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009571 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009572 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009573 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009574 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009575 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009576
9577 if (needSep) pw.println(" ");
9578 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009579 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009580 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009581 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009582 needSep = true;
9583 }
9584
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009585 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009586
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009587 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009588 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009589 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009590 if (mHeavyWeightProcess != null) {
9591 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9592 }
9593
9594 return true;
9595 }
9596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 /**
9598 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009599 * - no provider specified: dump all the providers
9600 * - a flattened component name that matched an existing provider was specified as the
9601 * first arg: dump that one provider
9602 * - the first arg isn't the flattened component name of an existing provider:
9603 * dump all providers whose component contains the first arg as a substring
9604 */
9605 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9606 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009607 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009608 }
9609
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009610 static class ItemMatcher {
9611 ArrayList<ComponentName> components;
9612 ArrayList<String> strings;
9613 ArrayList<Integer> objects;
9614 boolean all;
9615
9616 ItemMatcher() {
9617 all = true;
9618 }
9619
9620 void build(String name) {
9621 ComponentName componentName = ComponentName.unflattenFromString(name);
9622 if (componentName != null) {
9623 if (components == null) {
9624 components = new ArrayList<ComponentName>();
9625 }
9626 components.add(componentName);
9627 all = false;
9628 } else {
9629 int objectId = 0;
9630 // Not a '/' separated full component name; maybe an object ID?
9631 try {
9632 objectId = Integer.parseInt(name, 16);
9633 if (objects == null) {
9634 objects = new ArrayList<Integer>();
9635 }
9636 objects.add(objectId);
9637 all = false;
9638 } catch (RuntimeException e) {
9639 // Not an integer; just do string match.
9640 if (strings == null) {
9641 strings = new ArrayList<String>();
9642 }
9643 strings.add(name);
9644 all = false;
9645 }
9646 }
9647 }
9648
9649 int build(String[] args, int opti) {
9650 for (; opti<args.length; opti++) {
9651 String name = args[opti];
9652 if ("--".equals(name)) {
9653 return opti+1;
9654 }
9655 build(name);
9656 }
9657 return opti;
9658 }
9659
9660 boolean match(Object object, ComponentName comp) {
9661 if (all) {
9662 return true;
9663 }
9664 if (components != null) {
9665 for (int i=0; i<components.size(); i++) {
9666 if (components.get(i).equals(comp)) {
9667 return true;
9668 }
9669 }
9670 }
9671 if (objects != null) {
9672 for (int i=0; i<objects.size(); i++) {
9673 if (System.identityHashCode(object) == objects.get(i)) {
9674 return true;
9675 }
9676 }
9677 }
9678 if (strings != null) {
9679 String flat = comp.flattenToString();
9680 for (int i=0; i<strings.size(); i++) {
9681 if (flat.contains(strings.get(i))) {
9682 return true;
9683 }
9684 }
9685 }
9686 return false;
9687 }
9688 }
9689
Dianne Hackborn625ac272010-09-17 18:29:22 -07009690 /**
9691 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009692 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009693 * - the cmd arg isn't the flattened component name of an existing activity:
9694 * dump all activity whose component contains the cmd as a substring
9695 * - A hex number of the ActivityRecord object instance.
9696 */
9697 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9698 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009699 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009700
9701 if ("all".equals(name)) {
9702 synchronized (this) {
9703 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009704 activities.add(r1);
9705 }
9706 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009707 } else if ("top".equals(name)) {
9708 synchronized (this) {
9709 final int N = mMainStack.mHistory.size();
9710 if (N > 0) {
9711 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9712 }
9713 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009714 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009715 ItemMatcher matcher = new ItemMatcher();
9716 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009717
9718 synchronized (this) {
9719 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009720 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009721 activities.add(r1);
9722 }
9723 }
9724 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009725 }
9726
9727 if (activities.size() <= 0) {
9728 return false;
9729 }
9730
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009731 String[] newArgs = new String[args.length - opti];
9732 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9733
Dianne Hackborn30d71892010-12-11 10:37:55 -08009734 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009735 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009736 for (int i=activities.size()-1; i>=0; i--) {
9737 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009738 if (needSep) {
9739 pw.println();
9740 }
9741 needSep = true;
9742 synchronized (this) {
9743 if (lastTask != r.task) {
9744 lastTask = r.task;
9745 pw.print("TASK "); pw.print(lastTask.affinity);
9746 pw.print(" id="); pw.println(lastTask.taskId);
9747 if (dumpAll) {
9748 lastTask.dump(pw, " ");
9749 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009750 }
9751 }
9752 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009753 }
9754 return true;
9755 }
9756
9757 /**
9758 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9759 * there is a thread associated with the activity.
9760 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009761 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009762 final ActivityRecord r, String[] args, boolean dumpAll) {
9763 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009764 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9766 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9767 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009768 if (r.app != null) pw.println(r.app.pid);
9769 else pw.println("(not running)");
9770 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009771 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009772 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009773 }
9774 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009775 // flush anything that is already in the PrintWriter since the thread is going
9776 // to write to the file descriptor directly
9777 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009778 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009779 TransferPipe tp = new TransferPipe();
9780 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009781 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9782 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009783 tp.go(fd);
9784 } finally {
9785 tp.kill();
9786 }
9787 } catch (IOException e) {
9788 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009789 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009791 }
9792 }
9793 }
9794
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009795 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009796 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009797 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009798 boolean onlyHistory = false;
9799
9800 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009801 if (opti < args.length && "-s".equals(args[opti])) {
9802 dumpAll = false;
9803 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009804 onlyHistory = true;
9805 dumpPackage = null;
9806 }
9807
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009808 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009809 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009810 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009811 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009812 Iterator it = mRegisteredReceivers.values().iterator();
9813 while (it.hasNext()) {
9814 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009815 if (dumpPackage != null && (r.app == null ||
9816 !dumpPackage.equals(r.app.info.packageName))) {
9817 continue;
9818 }
9819 if (!printed) {
9820 pw.println(" Registered Receivers:");
9821 needSep = true;
9822 printed = true;
9823 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009824 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 r.dump(pw, " ");
9826 }
9827 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009828
9829 if (mReceiverResolver.dump(pw, needSep ?
9830 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9831 " ", dumpPackage, false)) {
9832 needSep = true;
9833 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009834 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009835
9836 for (BroadcastQueue q : mBroadcastQueues) {
9837 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009839
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009840 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009841
Dianne Hackborn786b4402012-08-27 15:14:02 -07009842 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009843 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9844 if (needSep) {
9845 pw.println();
9846 }
9847 needSep = true;
9848 pw.print(" Sticky broadcasts for user ");
9849 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9850 StringBuilder sb = new StringBuilder(128);
9851 for (Map.Entry<String, ArrayList<Intent>> ent
9852 : mStickyBroadcasts.valueAt(user).entrySet()) {
9853 pw.print(" * Sticky action "); pw.print(ent.getKey());
9854 if (dumpAll) {
9855 pw.println(":");
9856 ArrayList<Intent> intents = ent.getValue();
9857 final int N = intents.size();
9858 for (int i=0; i<N; i++) {
9859 sb.setLength(0);
9860 sb.append(" Intent: ");
9861 intents.get(i).toShortString(sb, false, true, false, false);
9862 pw.println(sb.toString());
9863 Bundle bundle = intents.get(i).getExtras();
9864 if (bundle != null) {
9865 pw.print(" ");
9866 pw.println(bundle.toString());
9867 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009868 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009869 } else {
9870 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 }
9872 }
9873 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009874 }
9875
Dianne Hackborn786b4402012-08-27 15:14:02 -07009876 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009878 for (BroadcastQueue queue : mBroadcastQueues) {
9879 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9880 + queue.mBroadcastsScheduled);
9881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009882 pw.println(" mHandler:");
9883 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009884 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009885 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009886
9887 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009888 }
9889
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009890 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009891 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009892 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009893
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009894 ItemMatcher matcher = new ItemMatcher();
9895 matcher.build(args, opti);
9896
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009897 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009898
9899 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009900
9901 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009902 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009903 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009904 ContentProviderRecord r = mLaunchingProviders.get(i);
9905 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9906 continue;
9907 }
9908 if (!printed) {
9909 if (needSep) pw.println(" ");
9910 needSep = true;
9911 pw.println(" Launching content providers:");
9912 printed = true;
9913 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009914 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009915 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009916 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009917 }
9918
9919 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009920 if (needSep) pw.println();
9921 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009922 pw.println("Granted Uri Permissions:");
9923 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9924 int uid = mGrantedUriPermissions.keyAt(i);
9925 HashMap<Uri, UriPermission> perms
9926 = mGrantedUriPermissions.valueAt(i);
9927 pw.print(" * UID "); pw.print(uid);
9928 pw.println(" holds:");
9929 for (UriPermission perm : perms.values()) {
9930 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009931 if (dumpAll) {
9932 perm.dump(pw, " ");
9933 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009934 }
9935 }
9936 needSep = true;
9937 }
9938
9939 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009940 }
9941
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009942 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009943 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009944 boolean needSep = false;
9945
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009946 if (mIntentSenderRecords.size() > 0) {
9947 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009948 Iterator<WeakReference<PendingIntentRecord>> it
9949 = mIntentSenderRecords.values().iterator();
9950 while (it.hasNext()) {
9951 WeakReference<PendingIntentRecord> ref = it.next();
9952 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009953 if (dumpPackage != null && (rec == null
9954 || !dumpPackage.equals(rec.key.packageName))) {
9955 continue;
9956 }
9957 if (!printed) {
9958 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9959 printed = true;
9960 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009961 needSep = true;
9962 if (rec != null) {
9963 pw.print(" * "); pw.println(rec);
9964 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009967 } else {
9968 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009969 }
9970 }
9971 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009972
9973 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009974 }
9975
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009976 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009977 String prefix, String label, boolean complete, boolean brief, boolean client,
9978 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009979 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009980 boolean needNL = false;
9981 final String innerPrefix = prefix + " ";
9982 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009983 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009984 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009985 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9986 continue;
9987 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009988 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009989 if (needNL) {
9990 pw.println(" ");
9991 needNL = false;
9992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009993 if (lastTask != r.task) {
9994 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009995 pw.print(prefix);
9996 pw.print(full ? "* " : " ");
9997 pw.println(lastTask);
9998 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009999 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010000 } else if (complete) {
10001 // Complete + brief == give a summary. Isn't that obvious?!?
10002 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010003 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010004 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010005 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010007 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010008 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10009 pw.print(" #"); pw.print(i); pw.print(": ");
10010 pw.println(r);
10011 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010012 r.dump(pw, innerPrefix);
10013 } else if (complete) {
10014 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010015 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010016 if (r.app != null) {
10017 pw.print(innerPrefix); pw.println(r.app);
10018 }
10019 }
10020 if (client && r.app != null && r.app.thread != null) {
10021 // flush anything that is already in the PrintWriter since the thread is going
10022 // to write to the file descriptor directly
10023 pw.flush();
10024 try {
10025 TransferPipe tp = new TransferPipe();
10026 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010027 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10028 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010029 // Short timeout, since blocking here can
10030 // deadlock with the application.
10031 tp.go(fd, 2000);
10032 } finally {
10033 tp.kill();
10034 }
10035 } catch (IOException e) {
10036 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10037 } catch (RemoteException e) {
10038 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10039 }
10040 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 }
10043 }
10044
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010045 private static String buildOomTag(String prefix, String space, int val, int base) {
10046 if (val == base) {
10047 if (space == null) return prefix;
10048 return prefix + " ";
10049 }
10050 return prefix + "+" + Integer.toString(val-base);
10051 }
10052
10053 private static final int dumpProcessList(PrintWriter pw,
10054 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010055 String prefix, String normalLabel, String persistentLabel,
10056 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010057 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010058 final int N = list.size()-1;
10059 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010061 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10062 continue;
10063 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010064 pw.println(String.format("%s%s #%2d: %s",
10065 prefix, (r.persistent ? persistentLabel : normalLabel),
10066 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010067 if (r.persistent) {
10068 numPers++;
10069 }
10070 }
10071 return numPers;
10072 }
10073
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010074 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010075 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010076 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010077 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010078
Dianne Hackborn905577f2011-09-07 18:31:28 -070010079 ArrayList<Pair<ProcessRecord, Integer>> list
10080 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10081 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010082 ProcessRecord r = origList.get(i);
10083 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10084 continue;
10085 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010086 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10087 }
10088
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010089 if (list.size() <= 0) {
10090 return false;
10091 }
10092
Dianne Hackborn905577f2011-09-07 18:31:28 -070010093 Comparator<Pair<ProcessRecord, Integer>> comparator
10094 = new Comparator<Pair<ProcessRecord, Integer>>() {
10095 @Override
10096 public int compare(Pair<ProcessRecord, Integer> object1,
10097 Pair<ProcessRecord, Integer> object2) {
10098 if (object1.first.setAdj != object2.first.setAdj) {
10099 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10100 }
10101 if (object1.second.intValue() != object2.second.intValue()) {
10102 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10103 }
10104 return 0;
10105 }
10106 };
10107
10108 Collections.sort(list, comparator);
10109
Dianne Hackborn287952c2010-09-22 22:34:31 -070010110 final long curRealtime = SystemClock.elapsedRealtime();
10111 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10112 final long curUptime = SystemClock.uptimeMillis();
10113 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10114
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010115 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010116 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010117 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010118 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010119 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010120 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10121 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010122 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10123 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010124 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10125 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010126 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10127 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010128 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010129 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010130 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10131 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10132 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10133 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10134 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10135 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10136 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10137 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010138 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10139 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010140 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10141 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010142 } else {
10143 oomAdj = Integer.toString(r.setAdj);
10144 }
10145 String schedGroup;
10146 switch (r.setSchedGroup) {
10147 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10148 schedGroup = "B";
10149 break;
10150 case Process.THREAD_GROUP_DEFAULT:
10151 schedGroup = "F";
10152 break;
10153 default:
10154 schedGroup = Integer.toString(r.setSchedGroup);
10155 break;
10156 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010157 String foreground;
10158 if (r.foregroundActivities) {
10159 foreground = "A";
10160 } else if (r.foregroundServices) {
10161 foreground = "S";
10162 } else {
10163 foreground = " ";
10164 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010165 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010166 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010167 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10168 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010169 if (r.adjSource != null || r.adjTarget != null) {
10170 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010171 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010172 if (r.adjTarget instanceof ComponentName) {
10173 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10174 } else if (r.adjTarget != null) {
10175 pw.print(r.adjTarget.toString());
10176 } else {
10177 pw.print("{null}");
10178 }
10179 pw.print("<=");
10180 if (r.adjSource instanceof ProcessRecord) {
10181 pw.print("Proc{");
10182 pw.print(((ProcessRecord)r.adjSource).toShortString());
10183 pw.println("}");
10184 } else if (r.adjSource != null) {
10185 pw.println(r.adjSource.toString());
10186 } else {
10187 pw.println("{null}");
10188 }
10189 }
10190 if (inclDetails) {
10191 pw.print(prefix);
10192 pw.print(" ");
10193 pw.print("oom: max="); pw.print(r.maxAdj);
10194 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010195 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010196 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010197 pw.print(" curRaw="); pw.print(r.curRawAdj);
10198 pw.print(" setRaw="); pw.print(r.setRawAdj);
10199 pw.print(" cur="); pw.print(r.curAdj);
10200 pw.print(" set="); pw.println(r.setAdj);
10201 pw.print(prefix);
10202 pw.print(" ");
10203 pw.print("keeping="); pw.print(r.keeping);
10204 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010205 pw.print(" empty="); pw.print(r.empty);
10206 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010207
10208 if (!r.keeping) {
10209 if (r.lastWakeTime != 0) {
10210 long wtime;
10211 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10212 synchronized (stats) {
10213 wtime = stats.getProcessWakeTime(r.info.uid,
10214 r.pid, curRealtime);
10215 }
10216 long timeUsed = wtime - r.lastWakeTime;
10217 pw.print(prefix);
10218 pw.print(" ");
10219 pw.print("keep awake over ");
10220 TimeUtils.formatDuration(realtimeSince, pw);
10221 pw.print(" used ");
10222 TimeUtils.formatDuration(timeUsed, pw);
10223 pw.print(" (");
10224 pw.print((timeUsed*100)/realtimeSince);
10225 pw.println("%)");
10226 }
10227 if (r.lastCpuTime != 0) {
10228 long timeUsed = r.curCpuTime - r.lastCpuTime;
10229 pw.print(prefix);
10230 pw.print(" ");
10231 pw.print("run cpu over ");
10232 TimeUtils.formatDuration(uptimeSince, pw);
10233 pw.print(" used ");
10234 TimeUtils.formatDuration(timeUsed, pw);
10235 pw.print(" (");
10236 pw.print((timeUsed*100)/uptimeSince);
10237 pw.println("%)");
10238 }
10239 }
10240 }
10241 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010242 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010243 }
10244
Dianne Hackbornb437e092011-08-05 17:50:29 -070010245 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010246 ArrayList<ProcessRecord> procs;
10247 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010248 if (args != null && args.length > start
10249 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010250 procs = new ArrayList<ProcessRecord>();
10251 int pid = -1;
10252 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010253 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010254 } catch (NumberFormatException e) {
10255
10256 }
10257 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10258 ProcessRecord proc = mLruProcesses.get(i);
10259 if (proc.pid == pid) {
10260 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010261 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010262 procs.add(proc);
10263 }
10264 }
10265 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010266 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010267 return null;
10268 }
10269 } else {
10270 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10271 }
10272 }
10273 return procs;
10274 }
10275
10276 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10277 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010278 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010279 if (procs == null) {
10280 return;
10281 }
10282
10283 long uptime = SystemClock.uptimeMillis();
10284 long realtime = SystemClock.elapsedRealtime();
10285 pw.println("Applications Graphics Acceleration Info:");
10286 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10287
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010288 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10289 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010290 if (r.thread != null) {
10291 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10292 pw.flush();
10293 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010294 TransferPipe tp = new TransferPipe();
10295 try {
10296 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10297 tp.go(fd);
10298 } finally {
10299 tp.kill();
10300 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010301 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010302 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010303 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010304 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010305 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010306 pw.flush();
10307 }
10308 }
10309 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010310 }
10311
Jeff Brown6754ba22011-12-14 20:20:01 -080010312 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10313 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10314 if (procs == null) {
10315 return;
10316 }
10317
10318 pw.println("Applications Database Info:");
10319
10320 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10321 ProcessRecord r = procs.get(i);
10322 if (r.thread != null) {
10323 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10324 pw.flush();
10325 try {
10326 TransferPipe tp = new TransferPipe();
10327 try {
10328 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10329 tp.go(fd);
10330 } finally {
10331 tp.kill();
10332 }
10333 } catch (IOException e) {
10334 pw.println("Failure while dumping the app: " + r);
10335 pw.flush();
10336 } catch (RemoteException e) {
10337 pw.println("Got a RemoteException while dumping the app " + r);
10338 pw.flush();
10339 }
10340 }
10341 }
10342 }
10343
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010344 final static class MemItem {
10345 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010346 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010347 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010348 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010349 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010350
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010351 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010352 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010353 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010354 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010355 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010356 }
10357 }
10358
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010359 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010360 boolean sort) {
10361 if (sort) {
10362 Collections.sort(items, new Comparator<MemItem>() {
10363 @Override
10364 public int compare(MemItem lhs, MemItem rhs) {
10365 if (lhs.pss < rhs.pss) {
10366 return 1;
10367 } else if (lhs.pss > rhs.pss) {
10368 return -1;
10369 }
10370 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010371 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010372 });
10373 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010374
10375 for (int i=0; i<items.size(); i++) {
10376 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010377 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010378 if (mi.subitems != null) {
10379 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10380 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010381 }
10382 }
10383
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010384 // These are in KB.
10385 static final long[] DUMP_MEM_BUCKETS = new long[] {
10386 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10387 120*1024, 160*1024, 200*1024,
10388 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10389 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10390 };
10391
Dianne Hackborn672342c2011-11-29 11:29:02 -080010392 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10393 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010394 int start = label.lastIndexOf('.');
10395 if (start >= 0) start++;
10396 else start = 0;
10397 int end = label.length();
10398 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10399 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10400 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10401 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010402 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010403 out.append(label, start, end);
10404 return;
10405 }
10406 }
10407 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010408 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010409 out.append(label, start, end);
10410 }
10411
10412 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10413 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10414 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10415 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10416 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10417 };
10418 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10419 "System", "Persistent", "Foreground",
10420 "Visible", "Perceptible", "Heavy Weight",
10421 "Backup", "A Services", "Home", "Previous",
10422 "B Services", "Background"
10423 };
10424
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010425 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010426 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010427 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010428 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010429 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010430
10431 int opti = 0;
10432 while (opti < args.length) {
10433 String opt = args[opti];
10434 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10435 break;
10436 }
10437 opti++;
10438 if ("-a".equals(opt)) {
10439 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010440 } else if ("--oom".equals(opt)) {
10441 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010442 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010443 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010444 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010445 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010446 pw.println("If [process] is specified it can be the name or ");
10447 pw.println("pid of a specific process to dump.");
10448 return;
10449 } else {
10450 pw.println("Unknown argument: " + opt + "; use -h for help");
10451 }
10452 }
10453
10454 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010455 if (procs == null) {
10456 return;
10457 }
10458
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010459 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010460 long uptime = SystemClock.uptimeMillis();
10461 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010462
10463 if (procs.size() == 1 || isCheckinRequest) {
10464 dumpAll = true;
10465 }
10466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010467 if (isCheckinRequest) {
10468 // short checkin version
10469 pw.println(uptime + "," + realtime);
10470 pw.flush();
10471 } else {
10472 pw.println("Applications Memory Usage (kB):");
10473 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10474 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010475
Dianne Hackbornb437e092011-08-05 17:50:29 -070010476 String[] innerArgs = new String[args.length-opti];
10477 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10478
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010479 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10480 long nativePss=0, dalvikPss=0, otherPss=0;
10481 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10482
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010483 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10484 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10485 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010486
10487 long totalPss = 0;
10488
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010489 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10490 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010491 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010492 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10494 pw.flush();
10495 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010496 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010497 if (dumpAll) {
10498 try {
10499 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10500 } catch (RemoteException e) {
10501 if (!isCheckinRequest) {
10502 pw.println("Got RemoteException!");
10503 pw.flush();
10504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010505 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010506 } else {
10507 mi = new Debug.MemoryInfo();
10508 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010510
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010511 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010512 long myTotalPss = mi.getTotalPss();
10513 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010514 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010515 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010516 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010517
10518 nativePss += mi.nativePss;
10519 dalvikPss += mi.dalvikPss;
10520 otherPss += mi.otherPss;
10521 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10522 long mem = mi.getOtherPss(j);
10523 miscPss[j] += mem;
10524 otherPss -= mem;
10525 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010526
10527 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010528 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10529 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010530 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010531 if (oomProcs[oomIndex] == null) {
10532 oomProcs[oomIndex] = new ArrayList<MemItem>();
10533 }
10534 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010535 break;
10536 }
10537 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 }
10540 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010541
10542 if (!isCheckinRequest && procs.size() > 1) {
10543 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10544
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010545 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10546 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10547 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010548 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010549 String label = Debug.MemoryInfo.getOtherLabel(j);
10550 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010551 }
10552
Dianne Hackbornb437e092011-08-05 17:50:29 -070010553 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10554 for (int j=0; j<oomPss.length; j++) {
10555 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010556 String label = DUMP_MEM_OOM_LABEL[j];
10557 MemItem item = new MemItem(label, label, oomPss[j],
10558 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010559 item.subitems = oomProcs[j];
10560 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010561 }
10562 }
10563
Dianne Hackborn672342c2011-11-29 11:29:02 -080010564 if (outTag != null || outStack != null) {
10565 if (outTag != null) {
10566 appendMemBucket(outTag, totalPss, "total", false);
10567 }
10568 if (outStack != null) {
10569 appendMemBucket(outStack, totalPss, "total", true);
10570 }
10571 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010572 for (int i=0; i<oomMems.size(); i++) {
10573 MemItem miCat = oomMems.get(i);
10574 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10575 continue;
10576 }
10577 if (miCat.id < ProcessList.SERVICE_ADJ
10578 || miCat.id == ProcessList.HOME_APP_ADJ
10579 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010580 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10581 outTag.append(" / ");
10582 }
10583 if (outStack != null) {
10584 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10585 if (firstLine) {
10586 outStack.append(":");
10587 firstLine = false;
10588 }
10589 outStack.append("\n\t at ");
10590 } else {
10591 outStack.append("$");
10592 }
10593 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010594 for (int j=0; j<miCat.subitems.size(); j++) {
10595 MemItem mi = miCat.subitems.get(j);
10596 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010597 if (outTag != null) {
10598 outTag.append(" ");
10599 }
10600 if (outStack != null) {
10601 outStack.append("$");
10602 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010603 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010604 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10605 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10606 }
10607 if (outStack != null) {
10608 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10609 }
10610 }
10611 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10612 outStack.append("(");
10613 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10614 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10615 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10616 outStack.append(":");
10617 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10618 }
10619 }
10620 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010621 }
10622 }
10623 }
10624 }
10625
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010626 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010627 pw.println();
10628 pw.println("Total PSS by process:");
10629 dumpMemItems(pw, " ", procMems, true);
10630 pw.println();
10631 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010632 pw.println("Total PSS by OOM adjustment:");
10633 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010634 if (!oomOnly) {
10635 PrintWriter out = categoryPw != null ? categoryPw : pw;
10636 out.println();
10637 out.println("Total PSS by category:");
10638 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010639 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010640 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010641 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010642 final int[] SINGLE_LONG_FORMAT = new int[] {
10643 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10644 };
10645 long[] longOut = new long[1];
10646 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10647 SINGLE_LONG_FORMAT, null, longOut, null);
10648 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10649 longOut[0] = 0;
10650 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10651 SINGLE_LONG_FORMAT, null, longOut, null);
10652 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10653 longOut[0] = 0;
10654 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10655 SINGLE_LONG_FORMAT, null, longOut, null);
10656 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10657 longOut[0] = 0;
10658 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10659 SINGLE_LONG_FORMAT, null, longOut, null);
10660 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10661 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10662 pw.print(shared); pw.println(" kB");
10663 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10664 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 }
10667
10668 /**
10669 * Searches array of arguments for the specified string
10670 * @param args array of argument strings
10671 * @param value value to search for
10672 * @return true if the value is contained in the array
10673 */
10674 private static boolean scanArgs(String[] args, String value) {
10675 if (args != null) {
10676 for (String arg : args) {
10677 if (value.equals(arg)) {
10678 return true;
10679 }
10680 }
10681 }
10682 return false;
10683 }
10684
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010685 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10686 ContentProviderRecord cpr, boolean always) {
10687 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10688
10689 if (!inLaunching || always) {
10690 synchronized (cpr) {
10691 cpr.launchingApp = null;
10692 cpr.notifyAll();
10693 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010694 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010695 String names[] = cpr.info.authority.split(";");
10696 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010697 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010698 }
10699 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010700
10701 for (int i=0; i<cpr.connections.size(); i++) {
10702 ContentProviderConnection conn = cpr.connections.get(i);
10703 if (conn.waiting) {
10704 // If this connection is waiting for the provider, then we don't
10705 // need to mess with its process unless we are always removing
10706 // or for some reason the provider is not currently launching.
10707 if (inLaunching && !always) {
10708 continue;
10709 }
10710 }
10711 ProcessRecord capp = conn.client;
10712 conn.dead = true;
10713 if (conn.stableCount > 0) {
10714 if (!capp.persistent && capp.thread != null
10715 && capp.pid != 0
10716 && capp.pid != MY_PID) {
10717 Slog.i(TAG, "Kill " + capp.processName
10718 + " (pid " + capp.pid + "): provider " + cpr.info.name
10719 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010720 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010721 capp.processName, capp.setAdj, "dying provider "
10722 + cpr.name.toShortString());
10723 Process.killProcessQuiet(capp.pid);
10724 }
10725 } else if (capp.thread != null && conn.provider.provider != null) {
10726 try {
10727 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10728 } catch (RemoteException e) {
10729 }
10730 // In the protocol here, we don't expect the client to correctly
10731 // clean up this connection, we'll just remove it.
10732 cpr.connections.remove(i);
10733 conn.client.conProviders.remove(conn);
10734 }
10735 }
10736
10737 if (inLaunching && always) {
10738 mLaunchingProviders.remove(cpr);
10739 }
10740 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010741 }
10742
10743 /**
10744 * Main code for cleaning up a process when it has gone away. This is
10745 * called both as a result of the process dying, or directly when stopping
10746 * a process when running in single process mode.
10747 */
10748 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010749 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010751 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752 }
10753
Dianne Hackborn36124872009-10-08 16:22:03 -070010754 mProcessesToGc.remove(app);
10755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 // Dismiss any open dialogs.
10757 if (app.crashDialog != null) {
10758 app.crashDialog.dismiss();
10759 app.crashDialog = null;
10760 }
10761 if (app.anrDialog != null) {
10762 app.anrDialog.dismiss();
10763 app.anrDialog = null;
10764 }
10765 if (app.waitDialog != null) {
10766 app.waitDialog.dismiss();
10767 app.waitDialog = null;
10768 }
10769
10770 app.crashing = false;
10771 app.notResponding = false;
10772
10773 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010774 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 app.thread = null;
10776 app.forcingToForeground = null;
10777 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010778 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010779 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010780 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010782 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783
10784 boolean restart = false;
10785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 // Remove published content providers.
10787 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010788 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010790 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010791
10792 final boolean always = app.bad || !allowRestart;
10793 if (removeDyingProviderLocked(app, cpr, always) || always) {
10794 // We left the provider in the launching list, need to
10795 // restart it.
10796 restart = true;
10797 }
10798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010800 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 }
10802 app.pubProviders.clear();
10803 }
10804
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010805 // Take care of any launching providers waiting for this process.
10806 if (checkAppInLaunchingProvidersLocked(app, false)) {
10807 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010808 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 // Unregister from connected content providers.
10811 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010812 for (int i=0; i<app.conProviders.size(); i++) {
10813 ContentProviderConnection conn = app.conProviders.get(i);
10814 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010815 }
10816 app.conProviders.clear();
10817 }
10818
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010819 // At this point there may be remaining entries in mLaunchingProviders
10820 // where we were the only one waiting, so they are no longer of use.
10821 // Look for these and clean up if found.
10822 // XXX Commented out for now. Trying to figure out a way to reproduce
10823 // the actual situation to identify what is actually going on.
10824 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010825 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010826 ContentProviderRecord cpr = (ContentProviderRecord)
10827 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010828 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010829 synchronized (cpr) {
10830 cpr.launchingApp = null;
10831 cpr.notifyAll();
10832 }
10833 }
10834 }
10835 }
10836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010837 skipCurrentReceiverLocked(app);
10838
10839 // Unregister any receivers.
10840 if (app.receivers.size() > 0) {
10841 Iterator<ReceiverList> it = app.receivers.iterator();
10842 while (it.hasNext()) {
10843 removeReceiverLocked(it.next());
10844 }
10845 app.receivers.clear();
10846 }
10847
Christopher Tate181fafa2009-05-14 11:12:14 -070010848 // If the app is undergoing backup, tell the backup manager about it
10849 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010850 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10851 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010852 try {
10853 IBackupManager bm = IBackupManager.Stub.asInterface(
10854 ServiceManager.getService(Context.BACKUP_SERVICE));
10855 bm.agentDisconnected(app.info.packageName);
10856 } catch (RemoteException e) {
10857 // can't happen; backup manager is local
10858 }
10859 }
10860
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010861 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10862 ProcessChangeItem item = mPendingProcessChanges.get(i);
10863 if (item.pid == app.pid) {
10864 mPendingProcessChanges.remove(i);
10865 mAvailProcessChanges.add(item);
10866 }
10867 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010868 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 // If the caller is restarting this app, then leave it in its
10871 // current lists and let the caller take care of it.
10872 if (restarting) {
10873 return;
10874 }
10875
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010876 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010877 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010879 mProcessNames.remove(app.processName, app.uid);
10880 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010881 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010882 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10883 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010884 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010886 } else if (!app.removed) {
10887 // This app is persistent, so we need to keep its record around.
10888 // If it is not already on the pending app list, add it there
10889 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010890 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10891 mPersistentStartingProcesses.add(app);
10892 restart = true;
10893 }
10894 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010895 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010896 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010897 mProcessesOnHold.remove(app);
10898
The Android Open Source Project4df24232009-03-05 14:34:35 -080010899 if (app == mHomeProcess) {
10900 mHomeProcess = null;
10901 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010902 if (app == mPreviousProcess) {
10903 mPreviousProcess = null;
10904 }
10905
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010906 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010907 // We have components that still need to be running in the
10908 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010909 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 startProcessLocked(app, "restart", app.processName);
10911 } else if (app.pid > 0 && app.pid != MY_PID) {
10912 // Goodbye!
10913 synchronized (mPidsSelfLocked) {
10914 mPidsSelfLocked.remove(app.pid);
10915 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10916 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010917 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010918 }
10919 }
10920
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010921 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10922 // Look through the content providers we are waiting to have launched,
10923 // and if any run in this process then either schedule a restart of
10924 // the process or kill the client waiting for it if this process has
10925 // gone bad.
10926 int NL = mLaunchingProviders.size();
10927 boolean restart = false;
10928 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010929 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010930 if (cpr.launchingApp == app) {
10931 if (!alwaysBad && !app.bad) {
10932 restart = true;
10933 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010934 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010935 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010936 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010937 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010938 }
10939 }
10940 }
10941 return restart;
10942 }
10943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 // =========================================================
10945 // SERVICES
10946 // =========================================================
10947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10949 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010950 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010952 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010953 }
10954 }
10955
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010956 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010957 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010958 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010959 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010960 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010961 }
10962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010964 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010965 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010966 // Refuse possible leaked file descriptors
10967 if (service != null && service.hasFileDescriptors() == true) {
10968 throw new IllegalArgumentException("File descriptors passed in Intent");
10969 }
10970
Amith Yamasani742a6712011-05-04 14:49:28 -070010971 if (DEBUG_SERVICE)
10972 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010973 synchronized(this) {
10974 final int callingPid = Binder.getCallingPid();
10975 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010976 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010978 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010979 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 Binder.restoreCallingIdentity(origId);
10981 return res;
10982 }
10983 }
10984
10985 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010986 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010988 if (DEBUG_SERVICE)
10989 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010991 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010992 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010993 Binder.restoreCallingIdentity(origId);
10994 return res;
10995 }
10996 }
10997
10998 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010999 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011000 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011001 // Refuse possible leaked file descriptors
11002 if (service != null && service.hasFileDescriptors() == true) {
11003 throw new IllegalArgumentException("File descriptors passed in Intent");
11004 }
11005
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011006 checkValidCaller(Binder.getCallingUid(), userId);
11007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011008 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011009 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 }
11012
11013 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011014 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 // Refuse possible leaked file descriptors
11016 if (service != null && service.hasFileDescriptors() == true) {
11017 throw new IllegalArgumentException("File descriptors passed in Intent");
11018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011020 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 }
11023
11024 public boolean stopServiceToken(ComponentName className, IBinder token,
11025 int startId) {
11026 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011027 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 }
11030
11031 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011032 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011034 mServices.setServiceForegroundLocked(className, token, id, notification,
11035 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 }
11037 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011038
Dianne Hackborn41203752012-08-31 14:05:51 -070011039 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11040 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011041 final int callingUserId = UserHandle.getUserId(callingUid);
11042 if (callingUserId != userId) {
11043 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11044 if ((requireFull || checkComponentPermission(
11045 android.Manifest.permission.INTERACT_ACROSS_USERS,
11046 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11047 && checkComponentPermission(
11048 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11049 callingPid, callingUid, -1, true)
11050 != PackageManager.PERMISSION_GRANTED) {
11051 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11052 // In this case, they would like to just execute as their
11053 // owner user instead of failing.
11054 userId = callingUserId;
11055 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011056 StringBuilder builder = new StringBuilder(128);
11057 builder.append("Permission Denial: ");
11058 builder.append(name);
11059 if (callerPackage != null) {
11060 builder.append(" from ");
11061 builder.append(callerPackage);
11062 }
11063 builder.append(" asks to run as user ");
11064 builder.append(userId);
11065 builder.append(" but is calling from user ");
11066 builder.append(UserHandle.getUserId(callingUid));
11067 builder.append("; this requires ");
11068 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11069 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011070 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011071 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11072 }
11073 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011074 Slog.w(TAG, msg);
11075 throw new SecurityException(msg);
11076 }
11077 }
11078 }
11079 if (userId == UserHandle.USER_CURRENT
11080 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011081 // Note that we may be accessing this outside of a lock...
11082 // shouldn't be a big deal, if this is being called outside
11083 // of a locked context there is intrinsically a race with
11084 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011085 userId = mCurrentUserId;
11086 }
11087 if (!allowAll && userId < 0) {
11088 throw new IllegalArgumentException(
11089 "Call does not support special user #" + userId);
11090 }
11091 }
11092 return userId;
11093 }
11094
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011095 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11096 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011097 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011098 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011099 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11100 if (ActivityManager.checkUidPermission(
11101 android.Manifest.permission.INTERACT_ACROSS_USERS,
11102 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11103 ComponentName comp = new ComponentName(aInfo.packageName, className);
11104 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11105 + " requests FLAG_SINGLE_USER, but app does not hold "
11106 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11107 Slog.w(TAG, msg);
11108 throw new SecurityException(msg);
11109 }
11110 result = true;
11111 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011112 } else if (componentProcessName == aInfo.packageName) {
11113 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11114 } else if ("system".equals(componentProcessName)) {
11115 result = true;
11116 }
11117 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011118 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11119 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011120 }
11121 return result;
11122 }
11123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 public int bindService(IApplicationThread caller, IBinder token,
11125 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011126 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011127 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 // Refuse possible leaked file descriptors
11129 if (service != null && service.hasFileDescriptors() == true) {
11130 throw new IllegalArgumentException("File descriptors passed in Intent");
11131 }
11132
11133 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011134 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11135 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 }
11137 }
11138
11139 public boolean unbindService(IServiceConnection connection) {
11140 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011141 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011143 }
11144
11145 public void publishService(IBinder token, Intent intent, IBinder service) {
11146 // Refuse possible leaked file descriptors
11147 if (intent != null && intent.hasFileDescriptors() == true) {
11148 throw new IllegalArgumentException("File descriptors passed in Intent");
11149 }
11150
11151 synchronized(this) {
11152 if (!(token instanceof ServiceRecord)) {
11153 throw new IllegalArgumentException("Invalid service token");
11154 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011155 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011156 }
11157 }
11158
11159 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11160 // Refuse possible leaked file descriptors
11161 if (intent != null && intent.hasFileDescriptors() == true) {
11162 throw new IllegalArgumentException("File descriptors passed in Intent");
11163 }
11164
11165 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011166 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 }
11168 }
11169
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011170 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 synchronized(this) {
11172 if (!(token instanceof ServiceRecord)) {
11173 throw new IllegalArgumentException("Invalid service token");
11174 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011175 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 }
11178
11179 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011180 // BACKUP AND RESTORE
11181 // =========================================================
11182
11183 // Cause the target app to be launched if necessary and its backup agent
11184 // instantiated. The backup agent will invoke backupAgentCreated() on the
11185 // activity manager to announce its creation.
11186 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011187 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11188 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011189
11190 synchronized(this) {
11191 // !!! TODO: currently no check here that we're already bound
11192 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11193 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11194 synchronized (stats) {
11195 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11196 }
11197
Dianne Hackborne7f97212011-02-24 14:40:20 -080011198 // Backup agent is now in use, its package can't be stopped.
11199 try {
11200 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011201 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011202 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011203 } catch (IllegalArgumentException e) {
11204 Slog.w(TAG, "Failed trying to unstop package "
11205 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011206 }
11207
Christopher Tate181fafa2009-05-14 11:12:14 -070011208 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011209 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11210 ? new ComponentName(app.packageName, app.backupAgentName)
11211 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011212 // startProcessLocked() returns existing proc's record if it's already running
11213 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011214 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011215 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011216 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011217 return false;
11218 }
11219
11220 r.app = proc;
11221 mBackupTarget = r;
11222 mBackupAppName = app.packageName;
11223
Christopher Tate6fa95972009-06-05 18:43:55 -070011224 // Try not to kill the process during backup
11225 updateOomAdjLocked(proc);
11226
Christopher Tate181fafa2009-05-14 11:12:14 -070011227 // If the process is already attached, schedule the creation of the backup agent now.
11228 // If it is not yet live, this will be done when it attaches to the framework.
11229 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011230 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011231 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011232 proc.thread.scheduleCreateBackupAgent(app,
11233 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011234 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011235 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011236 }
11237 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011238 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011239 }
11240 // Invariants: at this point, the target app process exists and the application
11241 // is either already running or in the process of coming up. mBackupTarget and
11242 // mBackupAppName describe the app, so that when it binds back to the AM we
11243 // know that it's scheduled for a backup-agent operation.
11244 }
11245
11246 return true;
11247 }
11248
Christopher Tate346acb12012-10-15 19:20:25 -070011249 @Override
11250 public void clearPendingBackup() {
11251 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11252 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11253
11254 synchronized (this) {
11255 mBackupTarget = null;
11256 mBackupAppName = null;
11257 }
11258 }
11259
Christopher Tate181fafa2009-05-14 11:12:14 -070011260 // A backup agent has just come up
11261 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011262 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011263 + " = " + agent);
11264
11265 synchronized(this) {
11266 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011267 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011268 return;
11269 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011270 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011271
Dianne Hackborn06740692010-09-22 22:46:21 -070011272 long oldIdent = Binder.clearCallingIdentity();
11273 try {
11274 IBackupManager bm = IBackupManager.Stub.asInterface(
11275 ServiceManager.getService(Context.BACKUP_SERVICE));
11276 bm.agentConnected(agentPackageName, agent);
11277 } catch (RemoteException e) {
11278 // can't happen; the backup manager service is local
11279 } catch (Exception e) {
11280 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11281 e.printStackTrace();
11282 } finally {
11283 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011284 }
11285 }
11286
11287 // done with this agent
11288 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011289 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011290 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011291 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011292 return;
11293 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011294
11295 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011296 try {
11297 if (mBackupAppName == null) {
11298 Slog.w(TAG, "Unbinding backup agent with no active backup");
11299 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011300 }
Christopher Tate346acb12012-10-15 19:20:25 -070011301
11302 if (!mBackupAppName.equals(appInfo.packageName)) {
11303 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11304 return;
11305 }
11306
11307 // Not backing this app up any more; reset its OOM adjustment
11308 final ProcessRecord proc = mBackupTarget.app;
11309 updateOomAdjLocked(proc);
11310
11311 // If the app crashed during backup, 'thread' will be null here
11312 if (proc.thread != null) {
11313 try {
11314 proc.thread.scheduleDestroyBackupAgent(appInfo,
11315 compatibilityInfoForPackageLocked(appInfo));
11316 } catch (Exception e) {
11317 Slog.e(TAG, "Exception when unbinding backup agent:");
11318 e.printStackTrace();
11319 }
11320 }
11321 } finally {
11322 mBackupTarget = null;
11323 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011324 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011325 }
11326 }
11327 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 // BROADCASTS
11329 // =========================================================
11330
Josh Bartel7f208742010-02-25 11:01:44 -060011331 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011332 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011334 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11335 if (stickies == null) {
11336 return cur;
11337 }
11338 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011339 if (list == null) {
11340 return cur;
11341 }
11342 int N = list.size();
11343 for (int i=0; i<N; i++) {
11344 Intent intent = list.get(i);
11345 if (filter.match(resolver, intent, true, TAG) >= 0) {
11346 if (cur == null) {
11347 cur = new ArrayList<Intent>();
11348 }
11349 cur.add(intent);
11350 }
11351 }
11352 return cur;
11353 }
11354
Christopher Tatef46723b2012-01-26 14:19:24 -080011355 boolean isPendingBroadcastProcessLocked(int pid) {
11356 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11357 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359
Christopher Tatef46723b2012-01-26 14:19:24 -080011360 void skipPendingBroadcastLocked(int pid) {
11361 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11362 for (BroadcastQueue queue : mBroadcastQueues) {
11363 queue.skipPendingBroadcastLocked(pid);
11364 }
11365 }
11366
11367 // The app just attached; send any pending broadcasts that it should receive
11368 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11369 boolean didSomething = false;
11370 for (BroadcastQueue queue : mBroadcastQueues) {
11371 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011373 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011374 }
11375
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011376 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011377 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011378 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011379 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011380 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 synchronized(this) {
11382 ProcessRecord callerApp = null;
11383 if (caller != null) {
11384 callerApp = getRecordForAppLocked(caller);
11385 if (callerApp == null) {
11386 throw new SecurityException(
11387 "Unable to find app for caller " + caller
11388 + " (pid=" + Binder.getCallingPid()
11389 + ") when registering receiver " + receiver);
11390 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011391 if (callerApp.info.uid != Process.SYSTEM_UID &&
11392 !callerApp.pkgList.contains(callerPackage)) {
11393 throw new SecurityException("Given caller package " + callerPackage
11394 + " is not running in process " + callerApp);
11395 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011396 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011397 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011398 } else {
11399 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011400 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011401 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 }
11403
Dianne Hackborn139748f2012-09-24 11:36:57 -070011404 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011405 true, true, "registerReceiver", callerPackage);
11406
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 List allSticky = null;
11408
11409 // Look for any matching sticky broadcasts...
11410 Iterator actions = filter.actionsIterator();
11411 if (actions != null) {
11412 while (actions.hasNext()) {
11413 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011414 allSticky = getStickiesLocked(action, filter, allSticky,
11415 UserHandle.USER_ALL);
11416 allSticky = getStickiesLocked(action, filter, allSticky,
11417 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011418 }
11419 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011420 allSticky = getStickiesLocked(null, filter, allSticky,
11421 UserHandle.USER_ALL);
11422 allSticky = getStickiesLocked(null, filter, allSticky,
11423 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011424 }
11425
11426 // The first sticky in the list is returned directly back to
11427 // the client.
11428 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11429
Joe Onorato8a9b2202010-02-26 18:56:32 -080011430 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 + ": " + sticky);
11432
11433 if (receiver == null) {
11434 return sticky;
11435 }
11436
11437 ReceiverList rl
11438 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11439 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011440 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11441 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 if (rl.app != null) {
11443 rl.app.receivers.add(rl);
11444 } else {
11445 try {
11446 receiver.asBinder().linkToDeath(rl, 0);
11447 } catch (RemoteException e) {
11448 return sticky;
11449 }
11450 rl.linkedToDeath = true;
11451 }
11452 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011453 } else if (rl.uid != callingUid) {
11454 throw new IllegalArgumentException(
11455 "Receiver requested to register for uid " + callingUid
11456 + " was previously registered for uid " + rl.uid);
11457 } else if (rl.pid != callingPid) {
11458 throw new IllegalArgumentException(
11459 "Receiver requested to register for pid " + callingPid
11460 + " was previously registered for pid " + rl.pid);
11461 } else if (rl.userId != userId) {
11462 throw new IllegalArgumentException(
11463 "Receiver requested to register for user " + userId
11464 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011466 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011467 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011468 rl.add(bf);
11469 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011470 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 }
11472 mReceiverResolver.addFilter(bf);
11473
11474 // Enqueue broadcasts for all existing stickies that match
11475 // this filter.
11476 if (allSticky != null) {
11477 ArrayList receivers = new ArrayList();
11478 receivers.add(bf);
11479
11480 int N = allSticky.size();
11481 for (int i=0; i<N; i++) {
11482 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011483 BroadcastQueue queue = broadcastQueueForIntent(intent);
11484 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011486 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011487 queue.enqueueParallelBroadcastLocked(r);
11488 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
11490 }
11491
11492 return sticky;
11493 }
11494 }
11495
11496 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011497 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498
Christopher Tatef46723b2012-01-26 14:19:24 -080011499 final long origId = Binder.clearCallingIdentity();
11500 try {
11501 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502
Christopher Tatef46723b2012-01-26 14:19:24 -080011503 synchronized(this) {
11504 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011506 if (rl != null) {
11507 if (rl.curBroadcast != null) {
11508 BroadcastRecord r = rl.curBroadcast;
11509 final boolean doNext = finishReceiverLocked(
11510 receiver.asBinder(), r.resultCode, r.resultData,
11511 r.resultExtras, r.resultAbort, true);
11512 if (doNext) {
11513 doTrim = true;
11514 r.queue.processNextBroadcast(false);
11515 }
11516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011517
Christopher Tatef46723b2012-01-26 14:19:24 -080011518 if (rl.app != null) {
11519 rl.app.receivers.remove(rl);
11520 }
11521 removeReceiverLocked(rl);
11522 if (rl.linkedToDeath) {
11523 rl.linkedToDeath = false;
11524 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 }
11527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528
Christopher Tatef46723b2012-01-26 14:19:24 -080011529 // If we actually concluded any broadcasts, we might now be able
11530 // to trim the recipients' apps from our working set
11531 if (doTrim) {
11532 trimApplications();
11533 return;
11534 }
11535
11536 } finally {
11537 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 }
11540
11541 void removeReceiverLocked(ReceiverList rl) {
11542 mRegisteredReceivers.remove(rl.receiver.asBinder());
11543 int N = rl.size();
11544 for (int i=0; i<N; i++) {
11545 mReceiverResolver.removeFilter(rl.get(i));
11546 }
11547 }
11548
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011549 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011550 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11551 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011552 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011553 try {
11554 r.thread.dispatchPackageBroadcast(cmd, packages);
11555 } catch (RemoteException ex) {
11556 }
11557 }
11558 }
11559 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011560
11561 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11562 int[] users) {
11563 List<ResolveInfo> receivers = null;
11564 try {
11565 HashSet<ComponentName> singleUserReceivers = null;
11566 boolean scannedFirstReceivers = false;
11567 for (int user : users) {
11568 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11569 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011570 if (user != 0 && newReceivers != null) {
11571 // If this is not the primary user, we need to check for
11572 // any receivers that should be filtered out.
11573 for (int i=0; i<newReceivers.size(); i++) {
11574 ResolveInfo ri = newReceivers.get(i);
11575 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11576 newReceivers.remove(i);
11577 i--;
11578 }
11579 }
11580 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011581 if (newReceivers != null && newReceivers.size() == 0) {
11582 newReceivers = null;
11583 }
11584 if (receivers == null) {
11585 receivers = newReceivers;
11586 } else if (newReceivers != null) {
11587 // We need to concatenate the additional receivers
11588 // found with what we have do far. This would be easy,
11589 // but we also need to de-dup any receivers that are
11590 // singleUser.
11591 if (!scannedFirstReceivers) {
11592 // Collect any single user receivers we had already retrieved.
11593 scannedFirstReceivers = true;
11594 for (int i=0; i<receivers.size(); i++) {
11595 ResolveInfo ri = receivers.get(i);
11596 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11597 ComponentName cn = new ComponentName(
11598 ri.activityInfo.packageName, ri.activityInfo.name);
11599 if (singleUserReceivers == null) {
11600 singleUserReceivers = new HashSet<ComponentName>();
11601 }
11602 singleUserReceivers.add(cn);
11603 }
11604 }
11605 }
11606 // Add the new results to the existing results, tracking
11607 // and de-dupping single user receivers.
11608 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011609 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011610 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11611 ComponentName cn = new ComponentName(
11612 ri.activityInfo.packageName, ri.activityInfo.name);
11613 if (singleUserReceivers == null) {
11614 singleUserReceivers = new HashSet<ComponentName>();
11615 }
11616 if (!singleUserReceivers.contains(cn)) {
11617 singleUserReceivers.add(cn);
11618 receivers.add(ri);
11619 }
11620 } else {
11621 receivers.add(ri);
11622 }
11623 }
11624 }
11625 }
11626 } catch (RemoteException ex) {
11627 // pm is in same process, this will never happen.
11628 }
11629 return receivers;
11630 }
11631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011632 private final int broadcastIntentLocked(ProcessRecord callerApp,
11633 String callerPackage, Intent intent, String resolvedType,
11634 IIntentReceiver resultTo, int resultCode, String resultData,
11635 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011636 boolean ordered, boolean sticky, int callingPid, int callingUid,
11637 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 intent = new Intent(intent);
11639
Dianne Hackborne7f97212011-02-24 14:40:20 -080011640 // By default broadcasts do not go to stopped apps.
11641 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11642
Joe Onorato8a9b2202010-02-26 18:56:32 -080011643 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011645 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011647 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011649
Dianne Hackborn139748f2012-09-24 11:36:57 -070011650 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011651 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011652
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011653 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011654 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011655 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011656 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11657 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11658 Slog.w(TAG, "Skipping broadcast of " + intent
11659 + ": user " + userId + " is stopped");
11660 return ActivityManager.BROADCAST_SUCCESS;
11661 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011662 }
11663
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011664 /*
11665 * Prevent non-system code (defined here to be non-persistent
11666 * processes) from sending protected broadcasts.
11667 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011668 int callingAppId = UserHandle.getAppId(callingUid);
11669 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11670 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011671 callingUid == 0) {
11672 // Always okay.
11673 } else if (callerApp == null || !callerApp.persistent) {
11674 try {
11675 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11676 intent.getAction())) {
11677 String msg = "Permission Denial: not allowed to send broadcast "
11678 + intent.getAction() + " from pid="
11679 + callingPid + ", uid=" + callingUid;
11680 Slog.w(TAG, msg);
11681 throw new SecurityException(msg);
11682 }
11683 } catch (RemoteException e) {
11684 Slog.w(TAG, "Remote exception", e);
11685 return ActivityManager.BROADCAST_SUCCESS;
11686 }
11687 }
11688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 // Handle special intents: if this broadcast is from the package
11690 // manager about a package being removed, we need to remove all of
11691 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011692 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011694 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11695 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011696 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 || uidRemoved) {
11698 if (checkComponentPermission(
11699 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011700 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701 == PackageManager.PERMISSION_GRANTED) {
11702 if (uidRemoved) {
11703 final Bundle intentExtras = intent.getExtras();
11704 final int uid = intentExtras != null
11705 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11706 if (uid >= 0) {
11707 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11708 synchronized (bs) {
11709 bs.removeUidStatsLocked(uid);
11710 }
11711 }
11712 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011713 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011714 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011715 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011716 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11717 if (list != null && (list.length > 0)) {
11718 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011719 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011720 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011721 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011722 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011723 }
11724 } else {
11725 Uri data = intent.getData();
11726 String ssp;
11727 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11728 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11729 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011730 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11731 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011732 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011733 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011734 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011735 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011737 }
11738 }
11739 }
11740 } else {
11741 String msg = "Permission Denial: " + intent.getAction()
11742 + " broadcast from " + callerPackage + " (pid=" + callingPid
11743 + ", uid=" + callingUid + ")"
11744 + " requires "
11745 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011746 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011747 throw new SecurityException(msg);
11748 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011749
11750 // Special case for adding a package: by default turn on compatibility
11751 // mode.
11752 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011753 Uri data = intent.getData();
11754 String ssp;
11755 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11756 mCompatModePackages.handlePackageAddedLocked(ssp,
11757 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759 }
11760
11761 /*
11762 * If this is the time zone changed action, queue up a message that will reset the timezone
11763 * of all currently running processes. This message will get queued up before the broadcast
11764 * happens.
11765 */
11766 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11767 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11768 }
11769
Robert Greenwalt03595d02010-11-02 14:08:23 -070011770 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11771 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11772 }
11773
Robert Greenwalt434203a2010-10-11 16:00:27 -070011774 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11775 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11776 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11777 }
11778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 // Add to the sticky list if requested.
11780 if (sticky) {
11781 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11782 callingPid, callingUid)
11783 != PackageManager.PERMISSION_GRANTED) {
11784 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11785 + callingPid + ", uid=" + callingUid
11786 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011787 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 throw new SecurityException(msg);
11789 }
11790 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011791 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011792 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011793 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011794 }
11795 if (intent.getComponent() != null) {
11796 throw new SecurityException(
11797 "Sticky broadcasts can't target a specific component");
11798 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011799 // We use userId directly here, since the "all" target is maintained
11800 // as a separate set of sticky broadcasts.
11801 if (userId != UserHandle.USER_ALL) {
11802 // But first, if this is not a broadcast to all users, then
11803 // make sure it doesn't conflict with an existing broadcast to
11804 // all users.
11805 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11806 UserHandle.USER_ALL);
11807 if (stickies != null) {
11808 ArrayList<Intent> list = stickies.get(intent.getAction());
11809 if (list != null) {
11810 int N = list.size();
11811 int i;
11812 for (i=0; i<N; i++) {
11813 if (intent.filterEquals(list.get(i))) {
11814 throw new IllegalArgumentException(
11815 "Sticky broadcast " + intent + " for user "
11816 + userId + " conflicts with existing global broadcast");
11817 }
11818 }
11819 }
11820 }
11821 }
11822 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11823 if (stickies == null) {
11824 stickies = new HashMap<String, ArrayList<Intent>>();
11825 mStickyBroadcasts.put(userId, stickies);
11826 }
11827 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 if (list == null) {
11829 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011830 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831 }
11832 int N = list.size();
11833 int i;
11834 for (i=0; i<N; i++) {
11835 if (intent.filterEquals(list.get(i))) {
11836 // This sticky already exists, replace it.
11837 list.set(i, new Intent(intent));
11838 break;
11839 }
11840 }
11841 if (i >= N) {
11842 list.add(new Intent(intent));
11843 }
11844 }
11845
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011846 int[] users;
11847 if (userId == UserHandle.USER_ALL) {
11848 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011849 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011850 } else {
11851 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011852 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011853 }
11854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 // Figure out who all will receive this broadcast.
11856 List receivers = null;
11857 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011858 // Need to resolve the intent to interested receivers...
11859 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11860 == 0) {
11861 receivers = collectReceiverComponents(intent, resolvedType, users);
11862 }
11863 if (intent.getComponent() == null) {
11864 registeredReceivers = mReceiverResolver.queryIntent(intent,
11865 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011866 }
11867
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011868 final boolean replacePending =
11869 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11870
Joe Onorato8a9b2202010-02-26 18:56:32 -080011871 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011872 + " replacePending=" + replacePending);
11873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11875 if (!ordered && NR > 0) {
11876 // If we are not serializing this broadcast, then send the
11877 // registered receivers separately so they don't wait for the
11878 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011879 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11880 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881 callerPackage, callingPid, callingUid, requiredPermission,
11882 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011883 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011884 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011885 TAG, "Enqueueing parallel broadcast " + r);
11886 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011887 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011888 queue.enqueueParallelBroadcastLocked(r);
11889 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 registeredReceivers = null;
11892 NR = 0;
11893 }
11894
11895 // Merge into one list.
11896 int ir = 0;
11897 if (receivers != null) {
11898 // A special case for PACKAGE_ADDED: do not allow the package
11899 // being added to see this broadcast. This prevents them from
11900 // using this as a back door to get run as soon as they are
11901 // installed. Maybe in the future we want to have a special install
11902 // broadcast or such for apps, but we'd like to deliberately make
11903 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011904 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011905 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11906 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11907 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011908 Uri data = intent.getData();
11909 if (data != null) {
11910 String pkgName = data.getSchemeSpecificPart();
11911 if (pkgName != null) {
11912 skipPackages = new String[] { pkgName };
11913 }
11914 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011915 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011916 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011917 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011918 if (skipPackages != null && (skipPackages.length > 0)) {
11919 for (String skipPackage : skipPackages) {
11920 if (skipPackage != null) {
11921 int NT = receivers.size();
11922 for (int it=0; it<NT; it++) {
11923 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11924 if (curt.activityInfo.packageName.equals(skipPackage)) {
11925 receivers.remove(it);
11926 it--;
11927 NT--;
11928 }
11929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011930 }
11931 }
11932 }
11933
11934 int NT = receivers != null ? receivers.size() : 0;
11935 int it = 0;
11936 ResolveInfo curt = null;
11937 BroadcastFilter curr = null;
11938 while (it < NT && ir < NR) {
11939 if (curt == null) {
11940 curt = (ResolveInfo)receivers.get(it);
11941 }
11942 if (curr == null) {
11943 curr = registeredReceivers.get(ir);
11944 }
11945 if (curr.getPriority() >= curt.priority) {
11946 // Insert this broadcast record into the final list.
11947 receivers.add(it, curr);
11948 ir++;
11949 curr = null;
11950 it++;
11951 NT++;
11952 } else {
11953 // Skip to the next ResolveInfo in the final list.
11954 it++;
11955 curt = null;
11956 }
11957 }
11958 }
11959 while (ir < NR) {
11960 if (receivers == null) {
11961 receivers = new ArrayList();
11962 }
11963 receivers.add(registeredReceivers.get(ir));
11964 ir++;
11965 }
11966
11967 if ((receivers != null && receivers.size() > 0)
11968 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011969 BroadcastQueue queue = broadcastQueueForIntent(intent);
11970 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011971 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011972 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011973 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011974 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011975 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011976 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 if (DEBUG_BROADCAST) {
11978 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011979 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011981 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011982 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011983 queue.enqueueOrderedBroadcastLocked(r);
11984 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011986 }
11987
Dianne Hackborna4972e92012-03-14 10:38:05 -070011988 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 }
11990
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011991 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 // Refuse possible leaked file descriptors
11993 if (intent != null && intent.hasFileDescriptors() == true) {
11994 throw new IllegalArgumentException("File descriptors passed in Intent");
11995 }
11996
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011997 int flags = intent.getFlags();
11998
11999 if (!mProcessesReady) {
12000 // if the caller really truly claims to know what they're doing, go
12001 // ahead and allow the broadcast without launching any receivers
12002 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12003 intent = new Intent(intent);
12004 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12005 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12006 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12007 + " before boot completion");
12008 throw new IllegalStateException("Cannot broadcast before boot completed");
12009 }
12010 }
12011
12012 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12013 throw new IllegalArgumentException(
12014 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12015 }
12016
12017 return intent;
12018 }
12019
12020 public final int broadcastIntent(IApplicationThread caller,
12021 Intent intent, String resolvedType, IIntentReceiver resultTo,
12022 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012023 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012024 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012026 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12029 final int callingPid = Binder.getCallingPid();
12030 final int callingUid = Binder.getCallingUid();
12031 final long origId = Binder.clearCallingIdentity();
12032 int res = broadcastIntentLocked(callerApp,
12033 callerApp != null ? callerApp.info.packageName : null,
12034 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012035 resultCode, resultData, map, requiredPermission, serialized, sticky,
12036 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 Binder.restoreCallingIdentity(origId);
12038 return res;
12039 }
12040 }
12041
12042 int broadcastIntentInPackage(String packageName, int uid,
12043 Intent intent, String resolvedType, IIntentReceiver resultTo,
12044 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012045 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012047 intent = verifyBroadcastLocked(intent);
12048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 final long origId = Binder.clearCallingIdentity();
12050 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12051 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012052 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 Binder.restoreCallingIdentity(origId);
12054 return res;
12055 }
12056 }
12057
Amith Yamasani742a6712011-05-04 14:49:28 -070012058 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 // Refuse possible leaked file descriptors
12060 if (intent != null && intent.hasFileDescriptors() == true) {
12061 throw new IllegalArgumentException("File descriptors passed in Intent");
12062 }
12063
Dianne Hackborn139748f2012-09-24 11:36:57 -070012064 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012065 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067 synchronized(this) {
12068 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12069 != PackageManager.PERMISSION_GRANTED) {
12070 String msg = "Permission Denial: unbroadcastIntent() from pid="
12071 + Binder.getCallingPid()
12072 + ", uid=" + Binder.getCallingUid()
12073 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012074 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 throw new SecurityException(msg);
12076 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012077 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12078 if (stickies != null) {
12079 ArrayList<Intent> list = stickies.get(intent.getAction());
12080 if (list != null) {
12081 int N = list.size();
12082 int i;
12083 for (i=0; i<N; i++) {
12084 if (intent.filterEquals(list.get(i))) {
12085 list.remove(i);
12086 break;
12087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012089 if (list.size() <= 0) {
12090 stickies.remove(intent.getAction());
12091 }
12092 }
12093 if (stickies.size() <= 0) {
12094 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 }
12096 }
12097 }
12098 }
12099
12100 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12101 String resultData, Bundle resultExtras, boolean resultAbort,
12102 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012103 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12104 if (r == null) {
12105 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012106 return false;
12107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012108
Christopher Tatef46723b2012-01-26 14:19:24 -080012109 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12110 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 }
12112
12113 public void finishReceiver(IBinder who, int resultCode, String resultData,
12114 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012115 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116
12117 // Refuse possible leaked file descriptors
12118 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12119 throw new IllegalArgumentException("File descriptors passed in Bundle");
12120 }
12121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012123 try {
12124 boolean doNext = false;
12125 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126
Christopher Tatef46723b2012-01-26 14:19:24 -080012127 synchronized(this) {
12128 r = broadcastRecordForReceiverLocked(who);
12129 if (r != null) {
12130 doNext = r.queue.finishReceiverLocked(r, resultCode,
12131 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012134
Christopher Tatef46723b2012-01-26 14:19:24 -080012135 if (doNext) {
12136 r.queue.processNextBroadcast(false);
12137 }
12138 trimApplications();
12139 } finally {
12140 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012144 // =========================================================
12145 // INSTRUMENTATION
12146 // =========================================================
12147
12148 public boolean startInstrumentation(ComponentName className,
12149 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012150 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012151 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012152 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012153 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012154 // Refuse possible leaked file descriptors
12155 if (arguments != null && arguments.hasFileDescriptors()) {
12156 throw new IllegalArgumentException("File descriptors passed in Bundle");
12157 }
12158
12159 synchronized(this) {
12160 InstrumentationInfo ii = null;
12161 ApplicationInfo ai = null;
12162 try {
12163 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012164 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012165 ai = AppGlobals.getPackageManager().getApplicationInfo(
12166 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012167 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012168 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 }
12170 if (ii == null) {
12171 reportStartInstrumentationFailure(watcher, className,
12172 "Unable to find instrumentation info for: " + className);
12173 return false;
12174 }
12175 if (ai == null) {
12176 reportStartInstrumentationFailure(watcher, className,
12177 "Unable to find instrumentation target package: " + ii.targetPackage);
12178 return false;
12179 }
12180
12181 int match = mContext.getPackageManager().checkSignatures(
12182 ii.targetPackage, ii.packageName);
12183 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12184 String msg = "Permission Denial: starting instrumentation "
12185 + className + " from pid="
12186 + Binder.getCallingPid()
12187 + ", uid=" + Binder.getCallingPid()
12188 + " not allowed because package " + ii.packageName
12189 + " does not have a signature matching the target "
12190 + ii.targetPackage;
12191 reportStartInstrumentationFailure(watcher, className, msg);
12192 throw new SecurityException(msg);
12193 }
12194
12195 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012196 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012197 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012198 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012200 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 app.instrumentationProfileFile = profileFile;
12202 app.instrumentationArguments = arguments;
12203 app.instrumentationWatcher = watcher;
12204 app.instrumentationResultClass = className;
12205 Binder.restoreCallingIdentity(origId);
12206 }
12207
12208 return true;
12209 }
12210
12211 /**
12212 * Report errors that occur while attempting to start Instrumentation. Always writes the
12213 * error to the logs, but if somebody is watching, send the report there too. This enables
12214 * the "am" command to report errors with more information.
12215 *
12216 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12217 * @param cn The component name of the instrumentation.
12218 * @param report The error report.
12219 */
12220 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12221 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012222 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 try {
12224 if (watcher != null) {
12225 Bundle results = new Bundle();
12226 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12227 results.putString("Error", report);
12228 watcher.instrumentationStatus(cn, -1, results);
12229 }
12230 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012231 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 }
12233 }
12234
12235 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12236 if (app.instrumentationWatcher != null) {
12237 try {
12238 // NOTE: IInstrumentationWatcher *must* be oneway here
12239 app.instrumentationWatcher.instrumentationFinished(
12240 app.instrumentationClass,
12241 resultCode,
12242 results);
12243 } catch (RemoteException e) {
12244 }
12245 }
12246 app.instrumentationWatcher = null;
12247 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012248 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 app.instrumentationProfileFile = null;
12250 app.instrumentationArguments = null;
12251
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012252 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254
12255 public void finishInstrumentation(IApplicationThread target,
12256 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012257 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258 // Refuse possible leaked file descriptors
12259 if (results != null && results.hasFileDescriptors()) {
12260 throw new IllegalArgumentException("File descriptors passed in Intent");
12261 }
12262
12263 synchronized(this) {
12264 ProcessRecord app = getRecordForAppLocked(target);
12265 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012266 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012267 return;
12268 }
12269 final long origId = Binder.clearCallingIdentity();
12270 finishInstrumentationLocked(app, resultCode, results);
12271 Binder.restoreCallingIdentity(origId);
12272 }
12273 }
12274
12275 // =========================================================
12276 // CONFIGURATION
12277 // =========================================================
12278
12279 public ConfigurationInfo getDeviceConfigurationInfo() {
12280 ConfigurationInfo config = new ConfigurationInfo();
12281 synchronized (this) {
12282 config.reqTouchScreen = mConfiguration.touchscreen;
12283 config.reqKeyboardType = mConfiguration.keyboard;
12284 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012285 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12286 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012287 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12288 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012289 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12290 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012291 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12292 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012293 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012294 }
12295 return config;
12296 }
12297
12298 public Configuration getConfiguration() {
12299 Configuration ci;
12300 synchronized(this) {
12301 ci = new Configuration(mConfiguration);
12302 }
12303 return ci;
12304 }
12305
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012306 public void updatePersistentConfiguration(Configuration values) {
12307 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12308 "updateConfiguration()");
12309 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12310 "updateConfiguration()");
12311 if (values == null) {
12312 throw new NullPointerException("Configuration must not be null");
12313 }
12314
12315 synchronized(this) {
12316 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012317 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012318 Binder.restoreCallingIdentity(origId);
12319 }
12320 }
12321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012322 public void updateConfiguration(Configuration values) {
12323 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12324 "updateConfiguration()");
12325
12326 synchronized(this) {
12327 if (values == null && mWindowManager != null) {
12328 // sentinel: fetch the current configuration from the window manager
12329 values = mWindowManager.computeNewConfiguration();
12330 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012331
12332 if (mWindowManager != null) {
12333 mProcessList.applyDisplaySize(mWindowManager);
12334 }
12335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012337 if (values != null) {
12338 Settings.System.clearConfiguration(values);
12339 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012340 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 Binder.restoreCallingIdentity(origId);
12342 }
12343 }
12344
12345 /**
12346 * Do either or both things: (1) change the current configuration, and (2)
12347 * make sure the given activity is running with the (now) current
12348 * configuration. Returns true if the activity has been left running, or
12349 * false if <var>starting</var> is being destroyed to match the new
12350 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012351 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012352 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012353 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012354 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012355 // do nothing if we are headless
12356 if (mHeadless) return true;
12357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 int changes = 0;
12359
12360 boolean kept = true;
12361
12362 if (values != null) {
12363 Configuration newConfig = new Configuration(mConfiguration);
12364 changes = newConfig.updateFrom(values);
12365 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012366 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012367 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012368 }
12369
Doug Zongker2bec3d42009-12-04 12:52:44 -080012370 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371
Dianne Hackborn813075a62011-11-14 17:45:19 -080012372 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 saveLocaleLocked(values.locale,
12374 !values.locale.equals(mConfiguration.locale),
12375 values.userSetLocale);
12376 }
12377
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012378 mConfigurationSeq++;
12379 if (mConfigurationSeq <= 0) {
12380 mConfigurationSeq = 1;
12381 }
12382 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012384 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012385
12386 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012387
12388 // TODO: If our config changes, should we auto dismiss any currently
12389 // showing dialogs?
12390 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012391
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012392 AttributeCache ac = AttributeCache.instance();
12393 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012394 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012396
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012397 // Make sure all resources in our process are updated
12398 // right now, so that anyone who is going to retrieve
12399 // resource values after we return will be sure to get
12400 // the new ones. This is especially important during
12401 // boot, where the first config change needs to guarantee
12402 // all resources have that config before following boot
12403 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012404 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012405
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012406 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012407 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012408 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012409 mHandler.sendMessage(msg);
12410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012412 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12413 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 try {
12415 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012416 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012417 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012418 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 }
12420 } catch (Exception e) {
12421 }
12422 }
12423 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012424 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012425 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12426 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012427 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012428 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012429 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012430 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12431 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12432 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012433 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012434 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 }
12437 }
12438
12439 if (changes != 0 && starting == null) {
12440 // If the configuration changed, and the caller is not already
12441 // in the process of starting an activity, then find the top
12442 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012443 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 }
12445
12446 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012447 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012448 // And we need to make sure at this point that all other activities
12449 // are made visible with the correct configuration.
12450 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 }
12452
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012453 if (values != null && mWindowManager != null) {
12454 mWindowManager.setNewConfiguration(mConfiguration);
12455 }
12456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457 return kept;
12458 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012459
12460 /**
12461 * Decide based on the configuration whether we should shouw the ANR,
12462 * crash, etc dialogs. The idea is that if there is no affordnace to
12463 * press the on-screen buttons, we shouldn't show the dialog.
12464 *
12465 * A thought: SystemUI might also want to get told about this, the Power
12466 * dialog / global actions also might want different behaviors.
12467 */
12468 private static final boolean shouldShowDialogs(Configuration config) {
12469 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12470 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012472
12473 /**
12474 * Save the locale. You must be inside a synchronized (this) block.
12475 */
12476 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12477 if(isDiff) {
12478 SystemProperties.set("user.language", l.getLanguage());
12479 SystemProperties.set("user.region", l.getCountry());
12480 }
12481
12482 if(isPersist) {
12483 SystemProperties.set("persist.sys.language", l.getLanguage());
12484 SystemProperties.set("persist.sys.country", l.getCountry());
12485 SystemProperties.set("persist.sys.localevar", l.getVariant());
12486 }
12487 }
12488
Adam Powelldd8fab22012-03-22 17:47:27 -070012489 @Override
12490 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12491 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012492 return srec != null && srec.task.affinity != null &&
12493 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012494 }
12495
12496 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12497 Intent resultData) {
12498 ComponentName dest = destIntent.getComponent();
12499
12500 synchronized (this) {
12501 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012502 if (srec == null) {
12503 return false;
12504 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012505 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12506 final int start = history.indexOf(srec);
12507 if (start < 0) {
12508 // Current activity is not in history stack; do nothing.
12509 return false;
12510 }
12511 int finishTo = start - 1;
12512 ActivityRecord parent = null;
12513 boolean foundParentInTask = false;
12514 if (dest != null) {
12515 TaskRecord tr = srec.task;
12516 for (int i = start - 1; i >= 0; i--) {
12517 ActivityRecord r = history.get(i);
12518 if (tr != r.task) {
12519 // Couldn't find parent in the same task; stop at the one above this.
12520 // (Root of current task; in-app "home" behavior)
12521 // Always at least finish the current activity.
12522 finishTo = Math.min(start - 1, i + 1);
12523 parent = history.get(finishTo);
12524 break;
12525 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12526 r.info.name.equals(dest.getClassName())) {
12527 finishTo = i;
12528 parent = r;
12529 foundParentInTask = true;
12530 break;
12531 }
12532 }
12533 }
12534
12535 if (mController != null) {
12536 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12537 if (next != null) {
12538 // ask watcher if this is allowed
12539 boolean resumeOK = true;
12540 try {
12541 resumeOK = mController.activityResuming(next.packageName);
12542 } catch (RemoteException e) {
12543 mController = null;
12544 }
12545
12546 if (!resumeOK) {
12547 return false;
12548 }
12549 }
12550 }
12551 final long origId = Binder.clearCallingIdentity();
12552 for (int i = start; i > finishTo; i--) {
12553 ActivityRecord r = history.get(i);
12554 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012555 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012556 // Only return the supplied result for the first activity finished
12557 resultCode = Activity.RESULT_CANCELED;
12558 resultData = null;
12559 }
12560
12561 if (parent != null && foundParentInTask) {
12562 final int parentLaunchMode = parent.info.launchMode;
12563 final int destIntentFlags = destIntent.getFlags();
12564 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12565 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12566 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12567 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012568 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012569 } else {
12570 try {
12571 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012572 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012573 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12574 null, aInfo, parent.appToken, null,
12575 0, -1, parent.launchedFromUid, 0, null, true, null);
12576 foundParentInTask = res == ActivityManager.START_SUCCESS;
12577 } catch (RemoteException e) {
12578 foundParentInTask = false;
12579 }
12580 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012581 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012582 }
12583 }
12584 Binder.restoreCallingIdentity(origId);
12585 return foundParentInTask;
12586 }
12587 }
12588
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012589 public int getLaunchedFromUid(IBinder activityToken) {
12590 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12591 if (srec == null) {
12592 return -1;
12593 }
12594 return srec.launchedFromUid;
12595 }
12596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 // =========================================================
12598 // LIFETIME MANAGEMENT
12599 // =========================================================
12600
Christopher Tatef46723b2012-01-26 14:19:24 -080012601 // Returns which broadcast queue the app is the current [or imminent] receiver
12602 // on, or 'null' if the app is not an active broadcast recipient.
12603 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12604 BroadcastRecord r = app.curReceiver;
12605 if (r != null) {
12606 return r.queue;
12607 }
12608
12609 // It's not the current receiver, but it might be starting up to become one
12610 synchronized (this) {
12611 for (BroadcastQueue queue : mBroadcastQueues) {
12612 r = queue.mPendingBroadcast;
12613 if (r != null && r.curApp == app) {
12614 // found it; report which queue it's in
12615 return queue;
12616 }
12617 }
12618 }
12619
12620 return null;
12621 }
12622
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012623 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012624 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012625 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012626 // This adjustment has already been computed. If we are calling
12627 // from the top, we may have already computed our adjustment with
12628 // an earlier hidden adjustment that isn't really for us... if
12629 // so, use the new hidden adjustment.
12630 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012631 if (app.hasActivities) {
12632 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12633 } else if (app.hasClientActivities) {
12634 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12635 } else {
12636 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12637 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012638 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012639 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 }
12641
12642 if (app.thread == null) {
12643 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012644 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012645 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012646 }
12647
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012648 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12649 app.adjSource = null;
12650 app.adjTarget = null;
12651 app.empty = false;
12652 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012653 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012654
12655 final int activitiesSize = app.activities.size();
12656
Dianne Hackborn7d608422011-08-07 16:24:18 -070012657 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012658 // The max adjustment doesn't allow this app to be anything
12659 // below foreground, so it is not worth doing work for it.
12660 app.adjType = "fixed";
12661 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012662 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012663 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012664 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012665 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012666 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012667 // System process can do UI, and when they do we want to have
12668 // them trim their memory after the user leaves the UI. To
12669 // facilitate this, here we need to determine whether or not it
12670 // is currently showing UI.
12671 app.systemNoUi = true;
12672 if (app == TOP_APP) {
12673 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012674 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012675 } else if (activitiesSize > 0) {
12676 for (int j = 0; j < activitiesSize; j++) {
12677 final ActivityRecord r = app.activities.get(j);
12678 if (r.visible) {
12679 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012680 }
12681 if (r.app == app) {
12682 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012683 }
12684 }
12685 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012686 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012687 }
12688
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012689 app.keeping = false;
12690 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012691 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012692
The Android Open Source Project4df24232009-03-05 14:34:35 -080012693 // Determine the importance of the process, starting with most
12694 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012696 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012697 boolean foregroundActivities = false;
12698 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012699 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012700 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012701 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012702 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012703 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012704 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012705 foregroundActivities = true;
12706 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012707 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012708 } else if (app.instrumentationClass != null) {
12709 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012710 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012711 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012712 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012713 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012714 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012715 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012716 // counts as being in the foreground for OOM killer purposes.
12717 // It's placed in a sched group based on the nature of the
12718 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012719 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012720 schedGroup = (queue == mFgBroadcastQueue)
12721 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012722 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 } else if (app.executingServices.size() > 0) {
12724 // An app that is currently executing a service callback also
12725 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012726 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012727 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012728 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012729 } else {
12730 // Assume process is hidden (has activities); we will correct
12731 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012732 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012733 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012734 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012735 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012737
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012738 boolean hasStoppingActivities = false;
12739
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012740 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012741 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012742 for (int j = 0; j < activitiesSize; j++) {
12743 final ActivityRecord r = app.activities.get(j);
12744 if (r.visible) {
12745 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012746 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12747 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012748 app.adjType = "visible";
12749 }
12750 schedGroup = Process.THREAD_GROUP_DEFAULT;
12751 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012752 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012753 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012754 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012755 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012756 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12757 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012758 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012759 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012760 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012761 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012762 } else if (r.state == ActivityState.STOPPING) {
12763 // We will apply the actual adjustment later, because
12764 // we want to allow this process to immediately go through
12765 // any memory trimming that is in effect.
12766 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012767 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012768 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012769 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012770 if (r.app == app) {
12771 app.hasActivities = true;
12772 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012773 }
12774 }
12775
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012776 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012777 if (app.hasClientActivities) {
12778 adj = clientHiddenAdj;
12779 app.adjType = "bg-client-act";
12780 } else {
12781 // Whoops, this process is completely empty as far as we know
12782 // at this point.
12783 adj = emptyAdj;
12784 app.empty = true;
12785 app.adjType = "bg-empty";
12786 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012787 }
12788
Dianne Hackborn7d608422011-08-07 16:24:18 -070012789 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012790 if (app.foregroundServices) {
12791 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012792 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012793 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012794 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012795 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012796 } else if (app.forcingToForeground != null) {
12797 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012798 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012799 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012800 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012801 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012802 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012803 }
12804 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012805
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012806 if (app.foregroundServices) {
12807 interesting = true;
12808 }
12809
Dianne Hackborn7d608422011-08-07 16:24:18 -070012810 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012811 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012812 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012813 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012814 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012815 app.adjType = "heavy";
12816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817
Dianne Hackborn7d608422011-08-07 16:24:18 -070012818 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012819 // This process is hosting what we currently consider to be the
12820 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012821 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012822 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012823 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012824 app.adjType = "home";
12825 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012826
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012827 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12828 && app.activities.size() > 0) {
12829 // This was the previous process that showed UI to the user.
12830 // We want to try to keep it around more aggressively, to give
12831 // a good experience around switching between two apps.
12832 adj = ProcessList.PREVIOUS_APP_ADJ;
12833 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12834 app.hidden = false;
12835 app.adjType = "previous";
12836 }
12837
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012838 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12839 + " reason=" + app.adjType);
12840
The Android Open Source Project4df24232009-03-05 14:34:35 -080012841 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012842 // there are applications dependent on our services or providers, but
12843 // this gives us a baseline and makes sure we don't get into an
12844 // infinite recursion.
12845 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012846 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012847
Christopher Tate6fa95972009-06-05 18:43:55 -070012848 if (mBackupTarget != null && app == mBackupTarget.app) {
12849 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012850 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012851 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012852 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012853 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012854 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012855 }
12856 }
12857
Dianne Hackborn7d608422011-08-07 16:24:18 -070012858 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012859 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 final long now = SystemClock.uptimeMillis();
12861 // This process is more important if the top activity is
12862 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012863 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012865 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012866 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012867 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012868 // If this process has shown some UI, let it immediately
12869 // go to the LRU list because it may be pretty heavy with
12870 // UI stuff. We'll tag it with a label just to help
12871 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012872 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012873 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012875 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012876 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012877 // This service has seen some activity within
12878 // recent memory, so we will keep its process ahead
12879 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012880 if (adj > ProcessList.SERVICE_ADJ) {
12881 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012882 app.adjType = "started-services";
12883 app.hidden = false;
12884 }
12885 }
12886 // If we have let the service slide into the background
12887 // state, still have some text describing what it is doing
12888 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012889 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012890 app.adjType = "started-bg-services";
12891 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012892 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012893 // Don't kill this process because it is doing work; it
12894 // has said it is doing work.
12895 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012896 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012897 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012898 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012899 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012900 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012901 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012902 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012903 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012904 // XXX should compute this based on the max of
12905 // all connected clients.
12906 ConnectionRecord cr = clist.get(i);
12907 if (cr.binding.client == app) {
12908 // Binding to ourself is not interesting.
12909 continue;
12910 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012911 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012912 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012913 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012914 int myHiddenAdj = hiddenAdj;
12915 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012916 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012917 myHiddenAdj = client.hiddenAdj;
12918 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012919 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012920 }
12921 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012922 int myClientHiddenAdj = clientHiddenAdj;
12923 if (myClientHiddenAdj > client.clientHiddenAdj) {
12924 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
12925 myClientHiddenAdj = client.clientHiddenAdj;
12926 } else {
12927 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
12928 }
12929 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012930 int myEmptyAdj = emptyAdj;
12931 if (myEmptyAdj > client.emptyAdj) {
12932 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12933 myEmptyAdj = client.emptyAdj;
12934 } else {
12935 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12936 }
12937 }
12938 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012939 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012940 String adjType = null;
12941 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12942 // Not doing bind OOM management, so treat
12943 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012944 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012945 // If this process has shown some UI, let it immediately
12946 // go to the LRU list because it may be pretty heavy with
12947 // UI stuff. We'll tag it with a label just to help
12948 // debug and understand what is going on.
12949 if (adj > clientAdj) {
12950 adjType = "bound-bg-ui-services";
12951 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012952 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012953 clientAdj = adj;
12954 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012955 if (now >= (s.lastActivity
12956 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012957 // This service has not seen activity within
12958 // recent memory, so allow it to drop to the
12959 // LRU list if there is no other reason to keep
12960 // it around. We'll also tag it with a label just
12961 // to help debug and undertand what is going on.
12962 if (adj > clientAdj) {
12963 adjType = "bound-bg-services";
12964 }
12965 clientAdj = adj;
12966 }
12967 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012968 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
12969 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
12970 // If this connection is keeping the service
12971 // created, then we want to try to better follow
12972 // its memory management semantics for activities.
12973 // That is, if it is sitting in the background
12974 // LRU list as a hidden process (with activities),
12975 // we don't want the service it is connected to
12976 // to go into the empty LRU and quickly get killed,
12977 // because I'll we'll do is just end up restarting
12978 // the service.
12979 app.hasClientActivities |= client.hasActivities;
12980 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012981 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012982 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012983 // If this process has recently shown UI, and
12984 // the process that is binding to it is less
12985 // important than being visible, then we don't
12986 // care about the binding as much as we care
12987 // about letting this process get into the LRU
12988 // list to be killed and restarted if needed for
12989 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012990 if (app.hasShownUi && app != mHomeProcess
12991 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012992 adjType = "bound-bg-ui-services";
12993 } else {
12994 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12995 |Context.BIND_IMPORTANT)) != 0) {
12996 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012997 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12998 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12999 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13000 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13001 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013002 adj = clientAdj;
13003 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013004 app.pendingUiClean = true;
13005 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13006 adj = ProcessList.VISIBLE_APP_ADJ;
13007 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013008 }
13009 if (!client.hidden) {
13010 app.hidden = false;
13011 }
13012 if (client.keeping) {
13013 app.keeping = true;
13014 }
13015 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013016 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013017 }
13018 if (adjType != null) {
13019 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013020 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13021 .REASON_SERVICE_IN_USE;
13022 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013023 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013024 app.adjTarget = s.name;
13025 }
13026 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13027 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13028 schedGroup = Process.THREAD_GROUP_DEFAULT;
13029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013030 }
13031 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013032 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013033 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013034 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013035 (a.visible || a.state == ActivityState.RESUMED
13036 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013037 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013038 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13039 schedGroup = Process.THREAD_GROUP_DEFAULT;
13040 }
13041 app.hidden = false;
13042 app.adjType = "service";
13043 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13044 .REASON_SERVICE_IN_USE;
13045 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013046 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013047 app.adjTarget = s.name;
13048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 }
13051 }
13052 }
13053 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013054
Dianne Hackborn287952c2010-09-22 22:34:31 -070013055 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013056 // would like to avoid killing it unless it would prevent the current
13057 // application from running. By default we put the process in
13058 // with the rest of the background processes; as we scan through
13059 // its services we may bump it up from there.
13060 if (adj > hiddenAdj) {
13061 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013062 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013063 app.adjType = "bg-services";
13064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 }
13066
Dianne Hackborn7d608422011-08-07 16:24:18 -070013067 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013068 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013069 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013070 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013071 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013072 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013073 for (int i = cpr.connections.size()-1;
13074 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13075 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13076 i--) {
13077 ContentProviderConnection conn = cpr.connections.get(i);
13078 ProcessRecord client = conn.client;
13079 if (client == app) {
13080 // Being our own client is not interesting.
13081 continue;
13082 }
13083 int myHiddenAdj = hiddenAdj;
13084 if (myHiddenAdj > client.hiddenAdj) {
13085 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13086 myHiddenAdj = client.hiddenAdj;
13087 } else {
13088 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013089 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013090 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013091 int myClientHiddenAdj = clientHiddenAdj;
13092 if (myClientHiddenAdj > client.clientHiddenAdj) {
13093 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13094 myClientHiddenAdj = client.clientHiddenAdj;
13095 } else {
13096 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13097 }
13098 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013099 int myEmptyAdj = emptyAdj;
13100 if (myEmptyAdj > client.emptyAdj) {
13101 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13102 myEmptyAdj = client.emptyAdj;
13103 } else {
13104 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13105 }
13106 }
13107 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013108 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013109 if (adj > clientAdj) {
13110 if (app.hasShownUi && app != mHomeProcess
13111 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13112 app.adjType = "bg-ui-provider";
13113 } else {
13114 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13115 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13116 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013117 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013118 if (!client.hidden) {
13119 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013120 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013121 if (client.keeping) {
13122 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013123 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013124 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13125 .REASON_PROVIDER_IN_USE;
13126 app.adjSource = client;
13127 app.adjSourceOom = clientAdj;
13128 app.adjTarget = cpr.name;
13129 }
13130 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13131 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 }
13133 }
13134 // If the provider has external (non-framework) process
13135 // dependencies, ensure that its adjustment is at least
13136 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013137 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013138 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13139 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013140 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013141 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013142 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013143 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013144 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 }
13146 }
13147 }
13148 }
13149
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013150 if (adj == ProcessList.SERVICE_ADJ) {
13151 if (doingAll) {
13152 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13153 mNewNumServiceProcs++;
13154 }
13155 if (app.serviceb) {
13156 adj = ProcessList.SERVICE_B_ADJ;
13157 }
13158 } else {
13159 app.serviceb = false;
13160 }
13161
13162 app.nonStoppingAdj = adj;
13163
13164 if (hasStoppingActivities) {
13165 // Only upgrade adjustment.
13166 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13167 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13168 app.adjType = "stopping";
13169 }
13170 }
13171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013172 app.curRawAdj = adj;
13173
Joe Onorato8a9b2202010-02-26 18:56:32 -080013174 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13176 if (adj > app.maxAdj) {
13177 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013178 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013179 schedGroup = Process.THREAD_GROUP_DEFAULT;
13180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013181 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013182 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013183 app.keeping = true;
13184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013185
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013186 if (app.hasAboveClient) {
13187 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13188 // then we need to drop its adjustment to be lower than the service's
13189 // in order to honor the request. We want to drop it by one adjustment
13190 // level... but there is special meaning applied to various levels so
13191 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013192 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013193 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013194 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13195 adj = ProcessList.VISIBLE_APP_ADJ;
13196 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13197 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13198 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13199 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013200 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013201 adj++;
13202 }
13203 }
13204
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013205 int importance = app.memImportance;
13206 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13207 app.curAdj = adj;
13208 app.curSchedGroup = schedGroup;
13209 if (!interesting) {
13210 // For this reporting, if there is not something explicitly
13211 // interesting in this process then we will push it to the
13212 // background importance.
13213 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13214 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13215 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13216 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13217 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13218 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13219 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13220 } else if (adj >= ProcessList.SERVICE_ADJ) {
13221 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13222 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13223 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13224 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13225 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13226 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13227 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13228 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13229 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13230 } else {
13231 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13232 }
13233 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013234
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013235 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13236 if (foregroundActivities != app.foregroundActivities) {
13237 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13238 }
13239 if (changes != 0) {
13240 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13241 app.memImportance = importance;
13242 app.foregroundActivities = foregroundActivities;
13243 int i = mPendingProcessChanges.size()-1;
13244 ProcessChangeItem item = null;
13245 while (i >= 0) {
13246 item = mPendingProcessChanges.get(i);
13247 if (item.pid == app.pid) {
13248 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13249 break;
13250 }
13251 i--;
13252 }
13253 if (i < 0) {
13254 // No existing item in pending changes; need a new one.
13255 final int NA = mAvailProcessChanges.size();
13256 if (NA > 0) {
13257 item = mAvailProcessChanges.remove(NA-1);
13258 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13259 } else {
13260 item = new ProcessChangeItem();
13261 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13262 }
13263 item.changes = 0;
13264 item.pid = app.pid;
13265 item.uid = app.info.uid;
13266 if (mPendingProcessChanges.size() == 0) {
13267 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13268 "*** Enqueueing dispatch processes changed!");
13269 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13270 }
13271 mPendingProcessChanges.add(item);
13272 }
13273 item.changes |= changes;
13274 item.importance = importance;
13275 item.foregroundActivities = foregroundActivities;
13276 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13277 + Integer.toHexString(System.identityHashCode(item))
13278 + " " + app.toShortString() + ": changes=" + item.changes
13279 + " importance=" + item.importance
13280 + " foreground=" + item.foregroundActivities
13281 + " type=" + app.adjType + " source=" + app.adjSource
13282 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013283 }
13284
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013285 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013286 }
13287
13288 /**
13289 * Ask a given process to GC right now.
13290 */
13291 final void performAppGcLocked(ProcessRecord app) {
13292 try {
13293 app.lastRequestedGc = SystemClock.uptimeMillis();
13294 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013295 if (app.reportLowMemory) {
13296 app.reportLowMemory = false;
13297 app.thread.scheduleLowMemory();
13298 } else {
13299 app.thread.processInBackground();
13300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 }
13302 } catch (Exception e) {
13303 // whatever.
13304 }
13305 }
13306
13307 /**
13308 * Returns true if things are idle enough to perform GCs.
13309 */
Josh Bartel7f208742010-02-25 11:01:44 -060013310 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013311 boolean processingBroadcasts = false;
13312 for (BroadcastQueue q : mBroadcastQueues) {
13313 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13314 processingBroadcasts = true;
13315 }
13316 }
13317 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013318 && (mSleeping || (mMainStack.mResumedActivity != null &&
13319 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 }
13321
13322 /**
13323 * Perform GCs on all processes that are waiting for it, but only
13324 * if things are idle.
13325 */
13326 final void performAppGcsLocked() {
13327 final int N = mProcessesToGc.size();
13328 if (N <= 0) {
13329 return;
13330 }
Josh Bartel7f208742010-02-25 11:01:44 -060013331 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 while (mProcessesToGc.size() > 0) {
13333 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013334 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013335 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13336 <= SystemClock.uptimeMillis()) {
13337 // To avoid spamming the system, we will GC processes one
13338 // at a time, waiting a few seconds between each.
13339 performAppGcLocked(proc);
13340 scheduleAppGcsLocked();
13341 return;
13342 } else {
13343 // It hasn't been long enough since we last GCed this
13344 // process... put it in the list to wait for its time.
13345 addProcessToGcListLocked(proc);
13346 break;
13347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 }
13349 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013350
13351 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013352 }
13353 }
13354
13355 /**
13356 * If all looks good, perform GCs on all processes waiting for them.
13357 */
13358 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013359 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013360 performAppGcsLocked();
13361 return;
13362 }
13363 // Still not idle, wait some more.
13364 scheduleAppGcsLocked();
13365 }
13366
13367 /**
13368 * Schedule the execution of all pending app GCs.
13369 */
13370 final void scheduleAppGcsLocked() {
13371 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013372
13373 if (mProcessesToGc.size() > 0) {
13374 // Schedule a GC for the time to the next process.
13375 ProcessRecord proc = mProcessesToGc.get(0);
13376 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13377
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013378 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013379 long now = SystemClock.uptimeMillis();
13380 if (when < (now+GC_TIMEOUT)) {
13381 when = now + GC_TIMEOUT;
13382 }
13383 mHandler.sendMessageAtTime(msg, when);
13384 }
13385 }
13386
13387 /**
13388 * Add a process to the array of processes waiting to be GCed. Keeps the
13389 * list in sorted order by the last GC time. The process can't already be
13390 * on the list.
13391 */
13392 final void addProcessToGcListLocked(ProcessRecord proc) {
13393 boolean added = false;
13394 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13395 if (mProcessesToGc.get(i).lastRequestedGc <
13396 proc.lastRequestedGc) {
13397 added = true;
13398 mProcessesToGc.add(i+1, proc);
13399 break;
13400 }
13401 }
13402 if (!added) {
13403 mProcessesToGc.add(0, proc);
13404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405 }
13406
13407 /**
13408 * Set up to ask a process to GC itself. This will either do it
13409 * immediately, or put it on the list of processes to gc the next
13410 * time things are idle.
13411 */
13412 final void scheduleAppGcLocked(ProcessRecord app) {
13413 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013414 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013415 return;
13416 }
13417 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013418 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013419 scheduleAppGcsLocked();
13420 }
13421 }
13422
Dianne Hackborn287952c2010-09-22 22:34:31 -070013423 final void checkExcessivePowerUsageLocked(boolean doKills) {
13424 updateCpuStatsNow();
13425
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013426 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013427 boolean doWakeKills = doKills;
13428 boolean doCpuKills = doKills;
13429 if (mLastPowerCheckRealtime == 0) {
13430 doWakeKills = false;
13431 }
13432 if (mLastPowerCheckUptime == 0) {
13433 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013434 }
13435 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013436 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013437 }
13438 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013439 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13440 final long curUptime = SystemClock.uptimeMillis();
13441 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13442 mLastPowerCheckRealtime = curRealtime;
13443 mLastPowerCheckUptime = curUptime;
13444 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13445 doWakeKills = false;
13446 }
13447 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13448 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013449 }
13450 int i = mLruProcesses.size();
13451 while (i > 0) {
13452 i--;
13453 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013454 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013455 long wtime;
13456 synchronized (stats) {
13457 wtime = stats.getProcessWakeTime(app.info.uid,
13458 app.pid, curRealtime);
13459 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013460 long wtimeUsed = wtime - app.lastWakeTime;
13461 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13462 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013463 StringBuilder sb = new StringBuilder(128);
13464 sb.append("Wake for ");
13465 app.toShortString(sb);
13466 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013467 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013468 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013469 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013470 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013471 sb.append((wtimeUsed*100)/realtimeSince);
13472 sb.append("%)");
13473 Slog.i(TAG, sb.toString());
13474 sb.setLength(0);
13475 sb.append("CPU for ");
13476 app.toShortString(sb);
13477 sb.append(": over ");
13478 TimeUtils.formatDuration(uptimeSince, sb);
13479 sb.append(" used ");
13480 TimeUtils.formatDuration(cputimeUsed, sb);
13481 sb.append(" (");
13482 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013483 sb.append("%)");
13484 Slog.i(TAG, sb.toString());
13485 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013486 // If a process has held a wake lock for more
13487 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013488 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013489 if (doWakeKills && realtimeSince > 0
13490 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13491 synchronized (stats) {
13492 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13493 realtimeSince, wtimeUsed);
13494 }
13495 Slog.w(TAG, "Excessive wake lock in " + app.processName
13496 + " (pid " + app.pid + "): held " + wtimeUsed
13497 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013498 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013499 app.processName, app.setAdj, "excessive wake lock");
13500 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013501 } else if (doCpuKills && uptimeSince > 0
13502 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13503 synchronized (stats) {
13504 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13505 uptimeSince, cputimeUsed);
13506 }
13507 Slog.w(TAG, "Excessive CPU in " + app.processName
13508 + " (pid " + app.pid + "): used " + cputimeUsed
13509 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013510 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013511 app.processName, app.setAdj, "excessive cpu");
13512 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013513 } else {
13514 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013515 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013516 }
13517 }
13518 }
13519 }
13520
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013521 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013522 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013523 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013524 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013525 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013526
13527 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013528 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 }
13530
Dianne Hackborn287952c2010-09-22 22:34:31 -070013531 final boolean wasKeeping = app.keeping;
13532
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013533 boolean success = true;
13534
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013535 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013536
Jeff Brown10e89712011-07-08 18:52:57 -070013537 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013538 if (wasKeeping && !app.keeping) {
13539 // This app is no longer something we want to keep. Note
13540 // its current wake lock time to later know to kill it if
13541 // it is not behaving well.
13542 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13543 synchronized (stats) {
13544 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13545 app.pid, SystemClock.elapsedRealtime());
13546 }
13547 app.lastCpuTime = app.curCpuTime;
13548 }
13549
13550 app.setRawAdj = app.curRawAdj;
13551 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013552
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013553 if (app.curAdj != app.setAdj) {
13554 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013555 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013556 TAG, "Set " + app.pid + " " + app.processName +
13557 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013558 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013559 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013560 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013562 }
13563 }
13564 if (app.setSchedGroup != app.curSchedGroup) {
13565 app.setSchedGroup = app.curSchedGroup;
13566 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13567 "Setting process group of " + app.processName
13568 + " to " + app.curSchedGroup);
13569 if (app.waitingToKill != null &&
13570 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13571 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013572 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013573 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013574 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013575 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013576 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013577 } else {
13578 if (true) {
13579 long oldId = Binder.clearCallingIdentity();
13580 try {
13581 Process.setProcessGroup(app.pid, app.curSchedGroup);
13582 } catch (Exception e) {
13583 Slog.w(TAG, "Failed setting process group of " + app.pid
13584 + " to " + app.curSchedGroup);
13585 e.printStackTrace();
13586 } finally {
13587 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013588 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013589 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013590 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013591 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013592 app.thread.setSchedulingGroup(app.curSchedGroup);
13593 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013594 }
13595 }
13596 }
13597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013598 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013599 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013600 }
13601
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013602 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013603 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013604 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013605 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013606 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013607 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 }
13609 }
13610 return resumedActivity;
13611 }
13612
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013613 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013614 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013615 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13616 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013617 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13618 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619
13620 mAdjSeq++;
13621
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013622 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13623 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013624 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13625 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013626 if (nowHidden != wasHidden) {
13627 // Changed to/from hidden state, so apps after it in the LRU
13628 // list may also be changed.
13629 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013630 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013631 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 }
13633
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013634 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013635 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013637 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013638
13639 if (false) {
13640 RuntimeException e = new RuntimeException();
13641 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013642 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 }
13644
13645 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013646 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013648 final int emptyProcessLimit;
13649 final int hiddenProcessLimit;
13650 if (mProcessLimit <= 0) {
13651 emptyProcessLimit = hiddenProcessLimit = 0;
13652 } else if (mProcessLimit == 1) {
13653 emptyProcessLimit = 1;
13654 hiddenProcessLimit = 0;
13655 } else {
13656 emptyProcessLimit = (mProcessLimit*2)/3;
13657 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13658 }
13659
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013660 // Let's determine how many processes we have running vs.
13661 // how many slots we have for background processes; we may want
13662 // to put multiple processes in a slot of there are enough of
13663 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013664 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13665 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013666 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13667 if (numEmptyProcs > hiddenProcessLimit) {
13668 // If there are more empty processes than our limit on hidden
13669 // processes, then use the hidden process limit for the factor.
13670 // This ensures that the really old empty processes get pushed
13671 // down to the bottom, so if we are running low on memory we will
13672 // have a better chance at keeping around more hidden processes
13673 // instead of a gazillion empty processes.
13674 numEmptyProcs = hiddenProcessLimit;
13675 }
13676 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013677 if (emptyFactor < 1) emptyFactor = 1;
13678 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13679 if (hiddenFactor < 1) hiddenFactor = 1;
13680 int stepHidden = 0;
13681 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013682 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013683 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013684 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013685
13686 mNumNonHiddenProcs = 0;
13687 mNumHiddenProcs = 0;
13688
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013689 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013690 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013691 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013692 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013693 int nextHiddenAdj = curHiddenAdj+1;
13694 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13695 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013696 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 while (i > 0) {
13698 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013699 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013700 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013701 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013702 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013703 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13704 // This process was assigned as a hidden process... step the
13705 // hidden level.
13706 mNumHiddenProcs++;
13707 if (curHiddenAdj != nextHiddenAdj) {
13708 stepHidden++;
13709 if (stepHidden >= hiddenFactor) {
13710 stepHidden = 0;
13711 curHiddenAdj = nextHiddenAdj;
13712 nextHiddenAdj += 2;
13713 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13714 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13715 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013716 if (curClientHiddenAdj <= curHiddenAdj) {
13717 curClientHiddenAdj = curHiddenAdj + 1;
13718 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13719 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13720 }
13721 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013722 }
13723 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013724 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013725 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013726 Slog.i(TAG, "No longer want " + app.processName
13727 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013728 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013729 app.processName, app.setAdj, "too many background");
13730 app.killedBackground = true;
13731 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013732 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013733 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13734 // This process has a client that has activities. We will have
13735 // given it the current hidden adj; here we will just leave it
13736 // without stepping the hidden adj.
13737 curClientHiddenAdj++;
13738 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13739 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13740 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013741 } else {
13742 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13743 // This process was assigned as an empty process... step the
13744 // empty level.
13745 if (curEmptyAdj != nextEmptyAdj) {
13746 stepEmpty++;
13747 if (stepEmpty >= emptyFactor) {
13748 stepEmpty = 0;
13749 curEmptyAdj = nextEmptyAdj;
13750 nextEmptyAdj += 2;
13751 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13752 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13753 }
13754 }
13755 }
13756 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13757 mNumNonHiddenProcs++;
13758 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013759 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13760 && !app.hasClientActivities) {
13761 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13762 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013763 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013764 + " (pid " + app.pid + "): empty for "
13765 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13766 / 1000) + "s");
13767 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13768 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013769 app.killedBackground = true;
13770 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013771 } else {
13772 numEmpty++;
13773 if (numEmpty > emptyProcessLimit) {
13774 Slog.i(TAG, "No longer want " + app.processName
13775 + " (pid " + app.pid + "): empty #" + numEmpty);
13776 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13777 app.processName, app.setAdj, "too many background");
13778 app.killedBackground = true;
13779 Process.killProcessQuiet(app.pid);
13780 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013781 }
13782 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013783 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013784 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013785 // If this is an isolated process, and there are no
13786 // services running in it, then the process is no longer
13787 // needed. We agressively kill these because we can by
13788 // definition not re-use the same process again, and it is
13789 // good to avoid having whatever code was running in them
13790 // left sitting around after no longer needed.
13791 Slog.i(TAG, "Isolated process " + app.processName
13792 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013793 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013794 app.processName, app.setAdj, "isolated not needed");
13795 app.killedBackground = true;
13796 Process.killProcessQuiet(app.pid);
13797 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013798 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13799 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13800 && !app.killedBackground) {
13801 numTrimming++;
13802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013803 }
13804 }
13805
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013806 mNumServiceProcs = mNewNumServiceProcs;
13807
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013808 // Now determine the memory trimming level of background processes.
13809 // Unfortunately we need to start at the back of the list to do this
13810 // properly. We only do this if the number of background apps we
13811 // are managing to keep around is less than half the maximum we desire;
13812 // if we are keeping a good number around, we'll let them use whatever
13813 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013814 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13815 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013816 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013817 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013818 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013819 int minFactor = 2;
13820 if (mHomeProcess != null) minFactor++;
13821 if (mPreviousProcess != null) minFactor++;
13822 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013823 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013824 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013825 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013826 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013827 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013828 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13829 } else {
13830 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13831 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013832 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013833 for (i=0; i<N; i++) {
13834 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013835 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13836 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013837 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013838 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13839 try {
13840 app.thread.scheduleTrimMemory(curLevel);
13841 } catch (RemoteException e) {
13842 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013843 if (false) {
13844 // For now we won't do this; our memory trimming seems
13845 // to be good enough at this point that destroying
13846 // activities causes more harm than good.
13847 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13848 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013849 // Need to do this on its own message because the stack may not
13850 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013851 // For these apps we will also finish their activities
13852 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013853 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013854 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013855 }
13856 }
13857 app.trimMemoryLevel = curLevel;
13858 step++;
13859 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013860 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013861 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013862 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13863 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013864 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013865 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13866 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013867 break;
13868 }
13869 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013870 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013871 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013872 && app.thread != null) {
13873 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013874 app.thread.scheduleTrimMemory(
13875 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013876 } catch (RemoteException e) {
13877 }
13878 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013879 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013880 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013881 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013882 && app.pendingUiClean) {
13883 // If this application is now in the background and it
13884 // had done UI, then give it the special trim level to
13885 // have it free UI resources.
13886 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13887 if (app.trimMemoryLevel < level && app.thread != null) {
13888 try {
13889 app.thread.scheduleTrimMemory(level);
13890 } catch (RemoteException e) {
13891 }
13892 }
13893 app.pendingUiClean = false;
13894 }
13895 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013896 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013897 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013898 } catch (RemoteException e) {
13899 }
13900 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013901 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013902 }
13903 }
13904 } else {
13905 final int N = mLruProcesses.size();
13906 for (i=0; i<N; i++) {
13907 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013908 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013909 && app.pendingUiClean) {
13910 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13911 && app.thread != null) {
13912 try {
13913 app.thread.scheduleTrimMemory(
13914 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13915 } catch (RemoteException e) {
13916 }
13917 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013918 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013919 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013920 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013921 }
13922 }
13923
13924 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013925 // Need to do this on its own message because the stack may not
13926 // be in a consistent state at this point.
13927 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013929 }
13930
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013931 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013932 synchronized (this) {
13933 int i;
13934
13935 // First remove any unused application processes whose package
13936 // has been removed.
13937 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13938 final ProcessRecord app = mRemovedProcesses.get(i);
13939 if (app.activities.size() == 0
13940 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013941 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013942 TAG, "Exiting empty application process "
13943 + app.processName + " ("
13944 + (app.thread != null ? app.thread.asBinder() : null)
13945 + ")\n");
13946 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013947 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013948 app.processName, app.setAdj, "empty");
13949 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013950 } else {
13951 try {
13952 app.thread.scheduleExit();
13953 } catch (Exception e) {
13954 // Ignore exceptions.
13955 }
13956 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013957 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013958 mRemovedProcesses.remove(i);
13959
13960 if (app.persistent) {
13961 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013962 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013963 }
13964 }
13965 }
13966 }
13967
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013968 // Now update the oom adj for all processes.
13969 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013970 }
13971 }
13972
13973 /** This method sends the specified signal to each of the persistent apps */
13974 public void signalPersistentProcesses(int sig) throws RemoteException {
13975 if (sig != Process.SIGNAL_USR1) {
13976 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13977 }
13978
13979 synchronized (this) {
13980 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13981 != PackageManager.PERMISSION_GRANTED) {
13982 throw new SecurityException("Requires permission "
13983 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13984 }
13985
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013986 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13987 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013988 if (r.thread != null && r.persistent) {
13989 Process.sendSignal(r.pid, sig);
13990 }
13991 }
13992 }
13993 }
13994
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013995 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13996 if (proc == null || proc == mProfileProc) {
13997 proc = mProfileProc;
13998 path = mProfileFile;
13999 profileType = mProfileType;
14000 clearProfilerLocked();
14001 }
14002 if (proc == null) {
14003 return;
14004 }
14005 try {
14006 proc.thread.profilerControl(false, path, null, profileType);
14007 } catch (RemoteException e) {
14008 throw new IllegalStateException("Process disappeared");
14009 }
14010 }
14011
14012 private void clearProfilerLocked() {
14013 if (mProfileFd != null) {
14014 try {
14015 mProfileFd.close();
14016 } catch (IOException e) {
14017 }
14018 }
14019 mProfileApp = null;
14020 mProfileProc = null;
14021 mProfileFile = null;
14022 mProfileType = 0;
14023 mAutoStopProfiler = false;
14024 }
14025
Dianne Hackborn1676c852012-09-10 14:52:30 -070014026 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014027 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014028
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014029 try {
14030 synchronized (this) {
14031 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14032 // its own permission.
14033 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14034 != PackageManager.PERMISSION_GRANTED) {
14035 throw new SecurityException("Requires permission "
14036 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014037 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014038
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014039 if (start && fd == null) {
14040 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014041 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014042
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014043 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014044 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014045 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014046 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014047
14048 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014049 throw new IllegalArgumentException("Unknown process: " + process);
14050 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014051
14052 if (start) {
14053 stopProfilerLocked(null, null, 0);
14054 setProfileApp(proc.info, proc.processName, path, fd, false);
14055 mProfileProc = proc;
14056 mProfileType = profileType;
14057 try {
14058 fd = fd.dup();
14059 } catch (IOException e) {
14060 fd = null;
14061 }
14062 proc.thread.profilerControl(start, path, fd, profileType);
14063 fd = null;
14064 mProfileFd = null;
14065 } else {
14066 stopProfilerLocked(proc, path, profileType);
14067 if (fd != null) {
14068 try {
14069 fd.close();
14070 } catch (IOException e) {
14071 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014072 }
14073 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014074
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014075 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014076 }
14077 } catch (RemoteException e) {
14078 throw new IllegalStateException("Process disappeared");
14079 } finally {
14080 if (fd != null) {
14081 try {
14082 fd.close();
14083 } catch (IOException e) {
14084 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014085 }
14086 }
14087 }
Andy McFadden824c5102010-07-09 16:26:57 -070014088
Dianne Hackborn1676c852012-09-10 14:52:30 -070014089 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014090 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014091 userId, true, true, callName, null);
14092 ProcessRecord proc = null;
14093 try {
14094 int pid = Integer.parseInt(process);
14095 synchronized (mPidsSelfLocked) {
14096 proc = mPidsSelfLocked.get(pid);
14097 }
14098 } catch (NumberFormatException e) {
14099 }
14100
14101 if (proc == null) {
14102 HashMap<String, SparseArray<ProcessRecord>> all
14103 = mProcessNames.getMap();
14104 SparseArray<ProcessRecord> procs = all.get(process);
14105 if (procs != null && procs.size() > 0) {
14106 proc = procs.valueAt(0);
14107 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14108 for (int i=1; i<procs.size(); i++) {
14109 ProcessRecord thisProc = procs.valueAt(i);
14110 if (thisProc.userId == userId) {
14111 proc = thisProc;
14112 break;
14113 }
14114 }
14115 }
14116 }
14117 }
14118
14119 return proc;
14120 }
14121
14122 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014123 String path, ParcelFileDescriptor fd) throws RemoteException {
14124
14125 try {
14126 synchronized (this) {
14127 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14128 // its own permission (same as profileControl).
14129 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14130 != PackageManager.PERMISSION_GRANTED) {
14131 throw new SecurityException("Requires permission "
14132 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14133 }
14134
14135 if (fd == null) {
14136 throw new IllegalArgumentException("null fd");
14137 }
14138
Dianne Hackborn1676c852012-09-10 14:52:30 -070014139 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014140 if (proc == null || proc.thread == null) {
14141 throw new IllegalArgumentException("Unknown process: " + process);
14142 }
14143
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014144 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14145 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014146 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14147 throw new SecurityException("Process not debuggable: " + proc);
14148 }
14149 }
14150
14151 proc.thread.dumpHeap(managed, path, fd);
14152 fd = null;
14153 return true;
14154 }
14155 } catch (RemoteException e) {
14156 throw new IllegalStateException("Process disappeared");
14157 } finally {
14158 if (fd != null) {
14159 try {
14160 fd.close();
14161 } catch (IOException e) {
14162 }
14163 }
14164 }
14165 }
14166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014167 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14168 public void monitor() {
14169 synchronized (this) { }
14170 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014171
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014172 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014173 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14174 ProcessRecord processRecord = mLruProcesses.get(i);
14175 try {
14176 if (processRecord.thread != null) {
14177 processRecord.thread.setCoreSettings(settings);
14178 }
14179 } catch (RemoteException re) {
14180 /* ignore */
14181 }
14182 }
14183 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014184
14185 // Multi-user methods
14186
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014187 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014188 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014189 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14190 != PackageManager.PERMISSION_GRANTED) {
14191 String msg = "Permission Denial: switchUser() from pid="
14192 + Binder.getCallingPid()
14193 + ", uid=" + Binder.getCallingUid()
14194 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14195 Slog.w(TAG, msg);
14196 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014197 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014198
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014199 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014200 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014201 synchronized (this) {
14202 final int oldUserId = mCurrentUserId;
14203 if (oldUserId == userId) {
14204 return true;
14205 }
14206
14207 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14208 if (userInfo == null) {
14209 Slog.w(TAG, "No user info for user #" + userId);
14210 return false;
14211 }
14212
14213 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14214 R.anim.screen_user_enter);
14215
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014216 boolean needStart = false;
14217
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014218 // If the user we are switching to is not currently started, then
14219 // we need to start it now.
14220 if (mStartedUsers.get(userId) == null) {
14221 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014222 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014223 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014224 }
14225
14226 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014227 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014228 final Integer userIdInt = Integer.valueOf(userId);
14229 mUserLru.remove(userIdInt);
14230 mUserLru.add(userIdInt);
14231
Craig Mautnerf1b67412012-09-19 13:18:29 -070014232 mWindowManager.setCurrentUser(userId);
14233
Adam Cohenf7522022012-10-03 20:03:18 -070014234 // Once the internal notion of the active user has switched, we lock the device
14235 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014236 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014237
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014238 final UserStartedState uss = mStartedUsers.get(userId);
14239
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014240 // Make sure user is in the started state. If it is currently
14241 // stopping, we need to knock that off.
14242 if (uss.mState == UserStartedState.STATE_STOPPING) {
14243 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14244 // so we can just fairly silently bring the user back from
14245 // the almost-dead.
14246 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014247 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014248 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014249 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14250 // This means ACTION_SHUTDOWN has been sent, so we will
14251 // need to treat this as a new boot of the user.
14252 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014253 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014254 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014255 }
14256
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014257 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14258 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14259 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14260 oldUserId, userId, uss));
14261 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14262 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014263 if (needStart) {
14264 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14265 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14266 | Intent.FLAG_RECEIVER_FOREGROUND);
14267 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14268 broadcastIntentLocked(null, null, intent,
14269 null, null, 0, null, null, null,
14270 false, false, MY_PID, Process.SYSTEM_UID, userId);
14271 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014272
14273 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14274 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014275 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014276 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014277 broadcastIntentLocked(null, null, intent, null,
14278 new IIntentReceiver.Stub() {
14279 public void performReceive(Intent intent, int resultCode,
14280 String data, Bundle extras, boolean ordered,
14281 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014282 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014283 }
14284 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14285 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014286 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014287 } else {
14288 getUserManagerLocked().makeInitialized(userInfo.id);
14289 }
14290 }
14291
14292 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14293 if (!haveActivities) {
14294 startHomeActivityLocked(userId);
14295 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014296
Jeff Sharkey86597df2012-11-09 15:00:31 -080014297 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014298 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014299 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014300 if (needStart) {
14301 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14302 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14303 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14304 broadcastIntentLocked(null, null, intent,
14305 null, new IIntentReceiver.Stub() {
14306 @Override
14307 public void performReceive(Intent intent, int resultCode, String data,
14308 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14309 throws RemoteException {
14310 }
14311 }, 0, null, null,
14312 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014313 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014314 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014315 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014316 } finally {
14317 Binder.restoreCallingIdentity(ident);
14318 }
Amith Yamasani13593602012-03-22 16:16:17 -070014319
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014320 return true;
14321 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014322
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014323 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14324 long ident = Binder.clearCallingIdentity();
14325 try {
14326 Intent intent;
14327 if (oldUserId >= 0) {
14328 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014329 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14330 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014331 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14332 broadcastIntentLocked(null, null, intent,
14333 null, null, 0, null, null, null,
14334 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14335 }
14336 if (newUserId >= 0) {
14337 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014338 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14339 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014340 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14341 broadcastIntentLocked(null, null, intent,
14342 null, null, 0, null, null, null,
14343 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14344 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014345 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14346 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014347 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14348 broadcastIntentLocked(null, null, intent,
14349 null, null, 0, null, null,
14350 android.Manifest.permission.MANAGE_USERS,
14351 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14352 }
14353 } finally {
14354 Binder.restoreCallingIdentity(ident);
14355 }
14356 }
14357
14358 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14359 final int newUserId) {
14360 final int N = mUserSwitchObservers.beginBroadcast();
14361 if (N > 0) {
14362 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14363 int mCount = 0;
14364 @Override
14365 public void sendResult(Bundle data) throws RemoteException {
14366 synchronized (ActivityManagerService.this) {
14367 if (mCurUserSwitchCallback == this) {
14368 mCount++;
14369 if (mCount == N) {
14370 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14371 }
14372 }
14373 }
14374 }
14375 };
14376 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014377 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014378 mCurUserSwitchCallback = callback;
14379 }
14380 for (int i=0; i<N; i++) {
14381 try {
14382 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14383 newUserId, callback);
14384 } catch (RemoteException e) {
14385 }
14386 }
14387 } else {
14388 synchronized (this) {
14389 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14390 }
14391 }
14392 mUserSwitchObservers.finishBroadcast();
14393 }
14394
14395 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14396 synchronized (this) {
14397 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14398 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14399 }
14400 }
14401
14402 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14403 mCurUserSwitchCallback = null;
14404 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14405 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14406 oldUserId, newUserId, uss));
14407 }
14408
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014409 void userInitialized(UserStartedState uss, int newUserId) {
14410 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014411 }
14412
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014413 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014414 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014415 }
14416
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014417 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14418 boolean clearInitializing, boolean clearSwitching) {
14419 boolean unfrozen = false;
14420 synchronized (this) {
14421 if (clearInitializing) {
14422 uss.initializing = false;
14423 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14424 }
14425 if (clearSwitching) {
14426 uss.switching = false;
14427 }
14428 if (!uss.switching && !uss.initializing) {
14429 mWindowManager.stopFreezingScreen();
14430 unfrozen = true;
14431 }
14432 }
14433 if (unfrozen) {
14434 final int N = mUserSwitchObservers.beginBroadcast();
14435 for (int i=0; i<N; i++) {
14436 try {
14437 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14438 } catch (RemoteException e) {
14439 }
14440 }
14441 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014442 }
14443 }
14444
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014445 void finishUserSwitch(UserStartedState uss) {
14446 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014447 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014448 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14449 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014450 final int userId = uss.mHandle.getIdentifier();
14451 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14452 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14453 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014454 null, null, 0, null, null,
14455 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014456 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014457 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014458 int num = mUserLru.size();
14459 int i = 0;
14460 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14461 Integer oldUserId = mUserLru.get(i);
14462 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14463 if (oldUss == null) {
14464 // Shouldn't happen, but be sane if it does.
14465 mUserLru.remove(i);
14466 num--;
14467 continue;
14468 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014469 if (oldUss.mState == UserStartedState.STATE_STOPPING
14470 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014471 // This user is already stopping, doesn't count.
14472 num--;
14473 i++;
14474 continue;
14475 }
14476 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14477 // Owner and current can't be stopped, but count as running.
14478 i++;
14479 continue;
14480 }
14481 // This is a user to be stopped.
14482 stopUserLocked(oldUserId, null);
14483 num--;
14484 i++;
14485 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014486 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014487 }
14488
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014489 @Override
14490 public int stopUser(final int userId, final IStopUserCallback callback) {
14491 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14492 != PackageManager.PERMISSION_GRANTED) {
14493 String msg = "Permission Denial: switchUser() from pid="
14494 + Binder.getCallingPid()
14495 + ", uid=" + Binder.getCallingUid()
14496 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14497 Slog.w(TAG, msg);
14498 throw new SecurityException(msg);
14499 }
14500 if (userId <= 0) {
14501 throw new IllegalArgumentException("Can't stop primary user " + userId);
14502 }
Amith Yamasani13593602012-03-22 16:16:17 -070014503 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014504 return stopUserLocked(userId, callback);
14505 }
14506 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014507
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014508 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14509 if (mCurrentUserId == userId) {
14510 return ActivityManager.USER_OP_IS_CURRENT;
14511 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014512
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014513 final UserStartedState uss = mStartedUsers.get(userId);
14514 if (uss == null) {
14515 // User is not started, nothing to do... but we do need to
14516 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014517 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014518 mHandler.post(new Runnable() {
14519 @Override
14520 public void run() {
14521 try {
14522 callback.userStopped(userId);
14523 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014524 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014525 }
14526 });
14527 }
14528 return ActivityManager.USER_OP_SUCCESS;
14529 }
14530
14531 if (callback != null) {
14532 uss.mStopCallbacks.add(callback);
14533 }
14534
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014535 if (uss.mState != UserStartedState.STATE_STOPPING
14536 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014537 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014538 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014539
14540 long ident = Binder.clearCallingIdentity();
14541 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014542 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014543 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014544 // stop the user.
14545 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14546 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14547 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14548 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14549 // This is the result receiver for the final shutdown broadcast.
14550 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014551 @Override
14552 public void performReceive(Intent intent, int resultCode, String data,
14553 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14554 finishUserStop(uss);
14555 }
14556 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014557 // This is the result receiver for the initial stopping broadcast.
14558 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14559 @Override
14560 public void performReceive(Intent intent, int resultCode, String data,
14561 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14562 // On to the next.
14563 synchronized (ActivityManagerService.this) {
14564 if (uss.mState != UserStartedState.STATE_STOPPING) {
14565 // Whoops, we are being started back up. Abort, abort!
14566 return;
14567 }
14568 uss.mState = UserStartedState.STATE_SHUTDOWN;
14569 }
14570 broadcastIntentLocked(null, null, shutdownIntent,
14571 null, shutdownReceiver, 0, null, null, null,
14572 true, false, MY_PID, Process.SYSTEM_UID, userId);
14573 }
14574 };
14575 // Kick things off.
14576 broadcastIntentLocked(null, null, stoppingIntent,
14577 null, stoppingReceiver, 0, null, null,
14578 android.Manifest.permission.INTERACT_ACROSS_USERS,
14579 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014580 } finally {
14581 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014582 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014583 }
Amith Yamasani13593602012-03-22 16:16:17 -070014584
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014585 return ActivityManager.USER_OP_SUCCESS;
14586 }
14587
14588 void finishUserStop(UserStartedState uss) {
14589 final int userId = uss.mHandle.getIdentifier();
14590 boolean stopped;
14591 ArrayList<IStopUserCallback> callbacks;
14592 synchronized (this) {
14593 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014594 if (mStartedUsers.get(userId) != uss) {
14595 stopped = false;
14596 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014597 stopped = false;
14598 } else {
14599 stopped = true;
14600 // User can no longer run.
14601 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014602 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014603 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014604
14605 // Clean up all state and processes associated with the user.
14606 // Kill all the processes for the user.
14607 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014608 }
14609 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014610
14611 for (int i=0; i<callbacks.size(); i++) {
14612 try {
14613 if (stopped) callbacks.get(i).userStopped(userId);
14614 else callbacks.get(i).userStopAborted(userId);
14615 } catch (RemoteException e) {
14616 }
14617 }
14618 }
14619
14620 @Override
14621 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014622 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14623 != PackageManager.PERMISSION_GRANTED) && (
14624 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14625 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014626 String msg = "Permission Denial: getCurrentUser() from pid="
14627 + Binder.getCallingPid()
14628 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014629 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014630 Slog.w(TAG, msg);
14631 throw new SecurityException(msg);
14632 }
14633 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014634 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014635 }
Amith Yamasani13593602012-03-22 16:16:17 -070014636 }
14637
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014638 int getCurrentUserIdLocked() {
14639 return mCurrentUserId;
14640 }
14641
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014642 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014643 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014644 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14645 != PackageManager.PERMISSION_GRANTED) {
14646 String msg = "Permission Denial: isUserRunning() from pid="
14647 + Binder.getCallingPid()
14648 + ", uid=" + Binder.getCallingUid()
14649 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14650 Slog.w(TAG, msg);
14651 throw new SecurityException(msg);
14652 }
14653 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014654 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014655 }
14656 }
14657
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014658 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014659 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014660 if (state == null) {
14661 return false;
14662 }
14663 if (orStopped) {
14664 return true;
14665 }
14666 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014667 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014668 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014669
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014670 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014671 public int[] getRunningUserIds() {
14672 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14673 != PackageManager.PERMISSION_GRANTED) {
14674 String msg = "Permission Denial: isUserRunning() from pid="
14675 + Binder.getCallingPid()
14676 + ", uid=" + Binder.getCallingUid()
14677 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14678 Slog.w(TAG, msg);
14679 throw new SecurityException(msg);
14680 }
14681 synchronized (this) {
14682 return mStartedUserArray;
14683 }
14684 }
14685
14686 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014687 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014688 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014689 UserStartedState uss = mStartedUsers.valueAt(i);
14690 // This list does not include stopping users.
14691 if (uss.mState != UserStartedState.STATE_STOPPING
14692 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14693 num++;
14694 }
14695 }
14696 mStartedUserArray = new int[num];
14697 num = 0;
14698 for (int i=0; i<mStartedUsers.size(); i++) {
14699 UserStartedState uss = mStartedUsers.valueAt(i);
14700 if (uss.mState != UserStartedState.STATE_STOPPING
14701 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14702 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14703 num++;
14704 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014705 }
14706 }
14707
14708 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014709 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14710 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14711 != PackageManager.PERMISSION_GRANTED) {
14712 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14713 + Binder.getCallingPid()
14714 + ", uid=" + Binder.getCallingUid()
14715 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14716 Slog.w(TAG, msg);
14717 throw new SecurityException(msg);
14718 }
14719
14720 mUserSwitchObservers.register(observer);
14721 }
14722
14723 @Override
14724 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14725 mUserSwitchObservers.unregister(observer);
14726 }
14727
Dianne Hackborn1676c852012-09-10 14:52:30 -070014728 private boolean userExists(int userId) {
14729 if (userId == 0) {
14730 return true;
14731 }
14732 UserManagerService ums = getUserManagerLocked();
14733 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14734 }
14735
14736 int[] getUsersLocked() {
14737 UserManagerService ums = getUserManagerLocked();
14738 return ums != null ? ums.getUserIds() : new int[] { 0 };
14739 }
14740
14741 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014742 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014743 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14744 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014745 }
14746 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014747 }
14748
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014749 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014750 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014751
14752 throw new SecurityException("Caller uid=" + uid
14753 + " is not privileged to communicate with user=" + userId);
14754 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014755
14756 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014757 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014758 }
14759
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014760 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014761 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014762 ApplicationInfo newInfo = new ApplicationInfo(info);
14763 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014764 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14765 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014766 return newInfo;
14767 }
14768
14769 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014770 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014771 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014772 return aInfo;
14773 }
14774
14775 ActivityInfo info = new ActivityInfo(aInfo);
14776 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14777 return info;
14778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014779}