blob: af412dfe9017143b38eb43c3656e91380121f940 [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;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080054import android.app.IUiAutomationConnection;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070055import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070057import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070058import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080060import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020061import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080062import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080063import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070064import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070066import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.content.ContentResolver;
68import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020069import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070070import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070071import android.content.IIntentReceiver;
72import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070073import android.content.Intent;
74import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070075import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.content.pm.ActivityInfo;
77import android.content.pm.ApplicationInfo;
78import android.content.pm.ConfigurationInfo;
79import android.content.pm.IPackageDataObserver;
80import android.content.pm.IPackageManager;
81import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080082import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070084import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070085import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070086import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.content.pm.ProviderInfo;
88import android.content.pm.ResolveInfo;
89import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040090import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.content.res.Configuration;
92import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070093import android.net.Proxy;
94import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.net.Uri;
96import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080097import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080098import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070099import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -0800100import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800102import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import android.os.FileUtils;
104import android.os.Handler;
105import android.os.IBinder;
106import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700107import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700108import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.Looper;
110import android.os.Message;
111import android.os.Parcel;
112import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700114import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400116import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700118import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.os.SystemClock;
120import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700121import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700122import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700124import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800126import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700127import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700129import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700131import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import android.view.Gravity;
133import android.view.LayoutInflater;
134import android.view.View;
135import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.BufferedInputStream;
138import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700139import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700140import java.io.DataInputStream;
141import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.File;
143import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700144import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700146import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200147import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800148import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700150import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.lang.ref.WeakReference;
152import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700153import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700154import java.util.Collections;
155import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156import java.util.HashMap;
157import java.util.HashSet;
158import java.util.Iterator;
159import java.util.List;
160import java.util.Locale;
161import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700162import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700163import java.util.concurrent.atomic.AtomicBoolean;
164import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800166public final class ActivityManagerService extends ActivityManagerNative
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700167 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700168 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700170 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400172 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 static final boolean DEBUG_SWITCH = localLOGV || false;
174 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700175 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_PAUSE = localLOGV || false;
177 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
178 static final boolean DEBUG_TRANSITION = localLOGV || false;
179 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800180 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700181 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700183 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 static final boolean DEBUG_VISBILITY = localLOGV || false;
185 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700186 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700187 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700188 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800189 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700191 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700192 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700193 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700194 static final boolean DEBUG_POWER = localLOGV || false;
195 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700196 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700197 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 static final boolean VALIDATE_TOKENS = false;
199 static final boolean SHOW_ACTIVITY_START_TIME = true;
200
201 // Control over CPU and battery monitoring.
202 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
203 static final boolean MONITOR_CPU_USAGE = true;
204 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
205 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
206 static final boolean MONITOR_THREAD_CPU_USAGE = false;
207
Dianne Hackborn1655be42009-05-08 14:29:01 -0700208 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700209 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700210
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800211 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700213 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // Maximum number of recent tasks that we can remember.
216 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700217
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700218 // Amount of time after a call to stopAppSwitches() during which we will
219 // prevent further untrusted switches from happening.
220 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
222 // How long we wait for a launched process to attach to the activity manager
223 // before we decide it's never going to come up for real.
224 static final int PROC_START_TIMEOUT = 10*1000;
225
Jeff Brown3f9dd282011-07-08 20:02:19 -0700226 // How long we wait for a launched process to attach to the activity manager
227 // before we decide it's never going to come up for real, when the process was
228 // started with a wrapper for instrumentation (such as Valgrind) because it
229 // could take much longer than usual.
230 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // How long to wait after going idle before forcing apps to GC.
233 static final int GC_TIMEOUT = 5*1000;
234
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700235 // The minimum amount of time between successive GC requests for a process.
236 static final int GC_MIN_INTERVAL = 60*1000;
237
Dianne Hackborn287952c2010-09-22 22:34:31 -0700238 // The rate at which we check for apps using excessive power -- 15 mins.
239 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
240
241 // The minimum sample duration we will allow before deciding we have
242 // enough data on wake locks to start killing things.
243 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
244
245 // The minimum sample duration we will allow before deciding we have
246 // enough data on CPU usage to start killing things.
247 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800250 static final int BROADCAST_FG_TIMEOUT = 10*1000;
251 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // How long we wait until we timeout on key dispatching.
254 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // How long we wait until we timeout on key dispatching during instrumentation.
257 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
258
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700259 // Amount of time we wait for observers to handle a user switch before
260 // giving up on them and unfreezing the screen.
261 static final int USER_SWITCH_TIMEOUT = 2*1000;
262
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700263 // Maximum number of users we allow to be running at a time.
264 static final int MAX_RUNNING_USERS = 3;
265
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800266 // How long to wait in getTopActivityExtras for the activity to respond with the result.
267 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000;
268
Dan Egnor42471dd2010-01-07 17:25:22 -0800269 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270
271 static final String[] EMPTY_STRING_ARRAY = new String[0];
272
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700273 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700274
275 private final boolean mHeadless;
276
Joe Onorato54a4a412011-11-02 20:50:08 -0700277 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
278 // default actuion automatically. Important for devices without direct input
279 // devices.
280 private boolean mShowDialogs = true;
281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700283 * Description of a request to start a new activity, which has been held
284 * due to app switches being disabled.
285 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700286 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700287 ActivityRecord r;
288 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700289 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700290 }
291
292 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
293 = new ArrayList<PendingActivityLaunch>();
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 BroadcastQueue mFgBroadcastQueue;
297 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800298 // Convenient for easy iteration over the queues. Foreground is first
299 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800301
302 BroadcastQueue broadcastQueueForIntent(Intent intent) {
303 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
304 if (DEBUG_BACKGROUND_BROADCAST) {
305 Slog.i(TAG, "Broadcast intent " + intent + " on "
306 + (isFg ? "foreground" : "background")
307 + " queue");
308 }
309 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
310 }
311
312 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
313 for (BroadcastQueue queue : mBroadcastQueues) {
314 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
315 if (r != null) {
316 return r;
317 }
318 }
319 return null;
320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800321
322 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * Activity we have told the window manager to have key focus.
324 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700325 ActivityRecord mFocusedActivity = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800326
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700327 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800328 * List of intents that were used to start the most recent tasks.
329 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700330 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800332 public class PendingActivityExtras extends Binder implements Runnable {
333 public final ActivityRecord activity;
334 public boolean haveResult = false;
335 public Bundle result = null;
336 public PendingActivityExtras(ActivityRecord _activity) {
337 activity = _activity;
338 }
339 @Override
340 public void run() {
341 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity);
342 synchronized (this) {
343 haveResult = true;
344 notifyAll();
345 }
346 }
347 }
348
349 final ArrayList<PendingActivityExtras> mPendingActivityExtras
350 = new ArrayList<PendingActivityExtras>();
351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700353 * Process management.
354 */
355 final ProcessList mProcessList = new ProcessList();
356
357 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * All of the applications we currently have running organized by name.
359 * The keys are strings of the application package name (as
360 * returned by the package manager), and the keys are ApplicationRecord
361 * objects.
362 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800366 * The currently running isolated processes.
367 */
368 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
369
370 /**
371 * Counter for assigning isolated process uids, to avoid frequently reusing the
372 * same ones.
373 */
374 int mNextIsolatedProcessUid = 0;
375
376 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700377 * The currently running heavy-weight process, if any.
378 */
379 ProcessRecord mHeavyWeightProcess = null;
380
381 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800382 * The last time that various processes have crashed.
383 */
384 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
385
386 /**
387 * Set of applications that we consider to be bad, and will reject
388 * incoming broadcasts from (which the user has no control over).
389 * Processes are added to this set when they have crashed twice within
390 * a minimum amount of time; they are removed from it when they are
391 * later restarted (hopefully due to some user action). The value is the
392 * time it was added to the list.
393 */
394 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
395
396 /**
397 * All of the processes we currently have running organized by pid.
398 * The keys are the pid running the application.
399 *
400 * <p>NOTE: This object is protected by its own lock, NOT the global
401 * activity manager lock!
402 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700403 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404
405 /**
406 * All of the processes that have been forced to be foreground. The key
407 * is the pid of the caller who requested it (we hold a death
408 * link on it).
409 */
410 abstract class ForegroundToken implements IBinder.DeathRecipient {
411 int pid;
412 IBinder token;
413 }
414 final SparseArray<ForegroundToken> mForegroundProcesses
415 = new SparseArray<ForegroundToken>();
416
417 /**
418 * List of records for processes that someone had tried to start before the
419 * system was ready. We don't start them at that point, but ensure they
420 * are started by the time booting is complete.
421 */
422 final ArrayList<ProcessRecord> mProcessesOnHold
423 = new ArrayList<ProcessRecord>();
424
425 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 * List of persistent applications that are in the process
427 * of being started.
428 */
429 final ArrayList<ProcessRecord> mPersistentStartingProcesses
430 = new ArrayList<ProcessRecord>();
431
432 /**
433 * Processes that are being forcibly torn down.
434 */
435 final ArrayList<ProcessRecord> mRemovedProcesses
436 = new ArrayList<ProcessRecord>();
437
438 /**
439 * List of running applications, sorted by recent usage.
440 * The first entry in the list is the least recently used.
441 * It contains ApplicationRecord objects. This list does NOT include
442 * any persistent application records (since we never want to exit them).
443 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800444 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 = new ArrayList<ProcessRecord>();
446
447 /**
448 * List of processes that should gc as soon as things are idle.
449 */
450 final ArrayList<ProcessRecord> mProcessesToGc
451 = new ArrayList<ProcessRecord>();
452
453 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800454 * This is the process holding what we currently consider to be
455 * the "home" activity.
456 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700457 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800458
459 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700460 * This is the process holding the activity the user last visited that
461 * is in a different process from the one they are currently in.
462 */
463 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800464
465 /**
466 * The time at which the previous process was last visible.
467 */
468 long mPreviousProcessVisibleTime;
469
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700470 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700471 * Which uses have been started, so are allowed to run code.
472 */
473 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
474
475 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700476 * LRU list of history of current users. Most recently current is at the end.
477 */
478 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
479
480 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700481 * Constant array of the users that are currently started.
482 */
483 int[] mStartedUserArray = new int[] { 0 };
484
485 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700486 * Registered observers of the user switching mechanics.
487 */
488 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
489 = new RemoteCallbackList<IUserSwitchObserver>();
490
491 /**
492 * Currently active user switch.
493 */
494 Object mCurUserSwitchCallback;
495
496 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400497 * Packages that the user has asked to have run in screen size
498 * compatibility mode instead of filling the screen.
499 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700500 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400501
502 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * Set of PendingResultRecord objects that are currently active.
504 */
505 final HashSet mPendingResultRecords = new HashSet();
506
507 /**
508 * Set of IntentSenderRecord objects that are currently active.
509 */
510 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
511 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
512
513 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800514 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700515 * already logged DropBox entries for. Guarded by itself. If
516 * something (rogue user app) forces this over
517 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
518 */
519 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
520 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
521
522 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700523 * Strict Mode background batched logging state.
524 *
525 * The string buffer is guarded by itself, and its lock is also
526 * used to determine if another batched write is already
527 * in-flight.
528 */
529 private final StringBuilder mStrictModeBuffer = new StringBuilder();
530
531 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 * Keeps track of all IIntentReceivers that have been registered for
533 * broadcasts. Hash keys are the receiver IBinder, hash value is
534 * a ReceiverList.
535 */
536 final HashMap mRegisteredReceivers = new HashMap();
537
538 /**
539 * Resolver for broadcast intents to registered receivers.
540 * Holds BroadcastFilter (subclass of IntentFilter).
541 */
542 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
543 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
544 @Override
545 protected boolean allowFilterResult(
546 BroadcastFilter filter, List<BroadcastFilter> dest) {
547 IBinder target = filter.receiverList.receiver.asBinder();
548 for (int i=dest.size()-1; i>=0; i--) {
549 if (dest.get(i).receiverList.receiver.asBinder() == target) {
550 return false;
551 }
552 }
553 return true;
554 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700555
556 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700557 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700558 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
559 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700560 return super.newResult(filter, match, userId);
561 }
562 return null;
563 }
564
565 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700566 protected BroadcastFilter[] newArray(int size) {
567 return new BroadcastFilter[size];
568 }
569
570 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700571 protected String packageForFilter(BroadcastFilter filter) {
572 return filter.packageName;
573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800574 };
575
576 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700577 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700579 * that action (which should usually be one). The SparseArray is keyed
580 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
581 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700583 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
584 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700586 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587
588 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700589 * Backup/restore process management
590 */
591 String mBackupAppName = null;
592 BackupRecord mBackupTarget = null;
593
594 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 * List of PendingThumbnailsRecord objects of clients who are still
596 * waiting to receive all of the thumbnails for a task.
597 */
598 final ArrayList mPendingThumbnails = new ArrayList();
599
600 /**
601 * List of HistoryRecord objects that have been finished and must
602 * still report back to a pending thumbnail receiver.
603 */
604 final ArrayList mCancelledThumbnails = new ArrayList();
605
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700606 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 /**
609 * List of content providers who have clients waiting for them. The
610 * application is currently being launched and the provider will be
611 * removed from this list once it is published.
612 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700613 final ArrayList<ContentProviderRecord> mLaunchingProviders
614 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615
616 /**
617 * Global set of specific Uri permissions that have been granted.
618 */
619 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
620 = new SparseArray<HashMap<Uri, UriPermission>>();
621
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800622 CoreSettingsObserver mCoreSettingsObserver;
623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 /**
625 * Thread-local storage used to carry caller permissions over through
626 * indirect content-provider access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 */
628 private class Identity {
629 public int pid;
630 public int uid;
631
632 Identity(int _pid, int _uid) {
633 pid = _pid;
634 uid = _uid;
635 }
636 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
639
640 /**
641 * All information we have collected about the runtime performance of
642 * any user id that can impact battery performance.
643 */
644 final BatteryStatsService mBatteryStatsService;
645
646 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800647 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 */
649 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800650
651 /**
652 * Information about and control over application operations
653 */
654 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655
656 /**
657 * Current configuration information. HistoryRecord objects are given
658 * a reference to this object to indicate which configuration they are
659 * currently running in, so this object must be kept immutable.
660 */
661 Configuration mConfiguration = new Configuration();
662
663 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800664 * Current sequencing integer of the configuration, for skipping old
665 * configurations.
666 */
667 int mConfigurationSeq = 0;
668
669 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700670 * Hardware-reported OpenGLES version.
671 */
672 final int GL_ES_VERSION;
673
674 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 * List of initialization arguments to pass to all processes when binding applications to them.
676 * For example, references to the commonly used services.
677 */
678 HashMap<String, IBinder> mAppBindArgs;
679
680 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700681 * Temporary to avoid allocations. Protected by main lock.
682 */
683 final StringBuilder mStringBuilder = new StringBuilder(256);
684
685 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686 * Used to control how we initialize the service.
687 */
688 boolean mStartRunning = false;
689 ComponentName mTopComponent;
690 String mTopAction;
691 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700692 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 boolean mSystemReady = false;
694 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700695 boolean mWaitingUpdate = false;
696 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700697 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700698 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699
700 Context mContext;
701
702 int mFactoryTest;
703
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700704 boolean mCheckedForSetup;
705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700707 * The time at which we will allow normal application switches again,
708 * after a call to {@link #stopAppSwitches()}.
709 */
710 long mAppSwitchesAllowedTime;
711
712 /**
713 * This is set to true after the first switch after mAppSwitchesAllowedTime
714 * is set; any switches after that will clear the time.
715 */
716 boolean mDidAppSwitch;
717
718 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700719 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700720 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700721 long mLastPowerCheckRealtime;
722
723 /**
724 * Last time (in uptime) at which we checked for power usage.
725 */
726 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700727
728 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 * Set while we are wanting to sleep, to prevent any
730 * activities from being started/resumed.
731 */
732 boolean mSleeping = false;
733
734 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700735 * State of external calls telling us if the device is asleep.
736 */
737 boolean mWentToSleep = false;
738
739 /**
740 * State of external call telling us if the lock screen is shown.
741 */
742 boolean mLockScreenShown = false;
743
744 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700745 * Set if we are shutting down the system, similar to sleeping.
746 */
747 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 /**
750 * Task identifier that activities are currently being started
751 * in. Incremented each time a new task is created.
752 * todo: Replace this with a TokenSpace class that generates non-repeating
753 * integers that won't wrap.
754 */
755 int mCurTask = 1;
756
757 /**
758 * Current sequence id for oom_adj computation traversal.
759 */
760 int mAdjSeq = 0;
761
762 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700763 * Current sequence id for process LRU updating.
764 */
765 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766
767 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700768 * Keep track of the non-hidden/empty process we last found, to help
769 * determine how to distribute hidden/empty processes next time.
770 */
771 int mNumNonHiddenProcs = 0;
772
773 /**
774 * Keep track of the number of hidden procs, to balance oom adj
775 * distribution between those and empty procs.
776 */
777 int mNumHiddenProcs = 0;
778
779 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700780 * Keep track of the number of service processes we last found, to
781 * determine on the next iteration which should be B services.
782 */
783 int mNumServiceProcs = 0;
784 int mNewNumServiceProcs = 0;
785
786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 * System monitoring: number of processes that died since the last
788 * N procs were started.
789 */
790 int[] mProcDeaths = new int[20];
791
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700792 /**
793 * This is set if we had to do a delayed dexopt of an app before launching
794 * it, to increasing the ANR timeouts in that case.
795 */
796 boolean mDidDexOpt;
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 String mDebugApp = null;
799 boolean mWaitForDebugger = false;
800 boolean mDebugTransient = false;
801 String mOrigDebugApp = null;
802 boolean mOrigWaitForDebugger = false;
803 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700804 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700805 String mProfileApp = null;
806 ProcessRecord mProfileProc = null;
807 String mProfileFile;
808 ParcelFileDescriptor mProfileFd;
809 int mProfileType = 0;
810 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800811 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700813 static class ProcessChangeItem {
814 static final int CHANGE_ACTIVITIES = 1<<0;
815 static final int CHANGE_IMPORTANCE= 1<<1;
816 int changes;
817 int uid;
818 int pid;
819 int importance;
820 boolean foregroundActivities;
821 }
822
Jeff Sharkeya4620792011-05-20 15:29:23 -0700823 final RemoteCallbackList<IProcessObserver> mProcessObservers
824 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700825 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
826
827 final ArrayList<ProcessChangeItem> mPendingProcessChanges
828 = new ArrayList<ProcessChangeItem>();
829 final ArrayList<ProcessChangeItem> mAvailProcessChanges
830 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 * Runtime statistics collection thread. This object's lock is used to
834 * protect all related state.
835 */
836 final Thread mProcessStatsThread;
837
838 /**
839 * Used to collect process stats when showing not responding dialog.
840 * Protected by mProcessStatsThread.
841 */
842 final ProcessStats mProcessStats = new ProcessStats(
843 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700844 final AtomicLong mLastCpuTime = new AtomicLong(0);
845 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 long mLastWriteTime = 0;
848
849 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700850 * Used to retain an update lock when the foreground activity is in
851 * immersive mode.
852 */
853 final UpdateLock mUpdateLock = new UpdateLock("immersive");
854
855 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 * Set to true after the system has finished booting.
857 */
858 boolean mBooted = false;
859
Dianne Hackborn7d608422011-08-07 16:24:18 -0700860 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700861 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862
863 WindowManagerService mWindowManager;
864
865 static ActivityManagerService mSelf;
866 static ActivityThread mSystemThread;
867
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700868 private int mCurrentUserId = 0;
869 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700870 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 private final class AppDeathRecipient implements IBinder.DeathRecipient {
873 final ProcessRecord mApp;
874 final int mPid;
875 final IApplicationThread mAppThread;
876
877 AppDeathRecipient(ProcessRecord app, int pid,
878 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800879 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 TAG, "New death recipient " + this
881 + " for thread " + thread.asBinder());
882 mApp = app;
883 mPid = pid;
884 mAppThread = thread;
885 }
886
887 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800888 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 TAG, "Death received in " + this
890 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 synchronized(ActivityManagerService.this) {
892 appDiedLocked(mApp, mPid, mAppThread);
893 }
894 }
895 }
896
897 static final int SHOW_ERROR_MSG = 1;
898 static final int SHOW_NOT_RESPONDING_MSG = 2;
899 static final int SHOW_FACTORY_ERROR_MSG = 3;
900 static final int UPDATE_CONFIGURATION_MSG = 4;
901 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
902 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 static final int SERVICE_TIMEOUT_MSG = 12;
904 static final int UPDATE_TIME_ZONE = 13;
905 static final int SHOW_UID_ERROR_MSG = 14;
906 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800907 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700908 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700909 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800910 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700911 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
912 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700913 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700914 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700915 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700916 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700917 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700918 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700919 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700920 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700921 static final int REPORT_USER_SWITCH_MSG = 34;
922 static final int CONTINUE_USER_SWITCH_MSG = 35;
923 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700924 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800926 static final int FIRST_ACTIVITY_STACK_MSG = 100;
927 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
928 static final int FIRST_COMPAT_MODE_MSG = 300;
929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700931 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700932 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933
934 final Handler mHandler = new Handler() {
935 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800936 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 //}
938
939 public void handleMessage(Message msg) {
940 switch (msg.what) {
941 case SHOW_ERROR_MSG: {
942 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700943 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
944 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 synchronized (ActivityManagerService.this) {
946 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700947 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800949 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700950 if (res != null) {
951 res.set(0);
952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 return;
954 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700955 if (!showBackground && UserHandle.getAppId(proc.uid)
956 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
957 && proc.pid != MY_PID) {
958 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
959 if (res != null) {
960 res.set(0);
961 }
962 return;
963 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700964 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700965 Dialog d = new AppErrorDialog(mContext,
966 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 d.show();
968 proc.crashDialog = d;
969 } else {
970 // The device is asleep, so just pretend that the user
971 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700972 if (res != null) {
973 res.set(0);
974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 }
976 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700977
978 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 } break;
980 case SHOW_NOT_RESPONDING_MSG: {
981 synchronized (ActivityManagerService.this) {
982 HashMap data = (HashMap) msg.obj;
983 ProcessRecord proc = (ProcessRecord)data.get("app");
984 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800985 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 return;
987 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800988
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700989 Intent intent = new Intent("android.intent.action.ANR");
990 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800991 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
992 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700993 }
994 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800995 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700996 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800997
Justin Kohbc52ca22012-03-29 15:11:44 -0700998 if (mShowDialogs) {
999 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07001000 mContext, proc, (ActivityRecord)data.get("activity"),
1001 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -07001002 d.show();
1003 proc.anrDialog = d;
1004 } else {
1005 // Just kill the app if there is no dialog to be shown.
1006 killAppAtUsersRequest(proc, null);
1007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001009
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001010 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001012 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1013 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1014 synchronized (ActivityManagerService.this) {
1015 ProcessRecord proc = (ProcessRecord) data.get("app");
1016 if (proc == null) {
1017 Slog.e(TAG, "App not found when showing strict mode dialog.");
1018 break;
1019 }
1020 if (proc.crashDialog != null) {
1021 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1022 return;
1023 }
1024 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001025 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001026 Dialog d = new StrictModeViolationDialog(mContext,
1027 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001028 d.show();
1029 proc.crashDialog = d;
1030 } else {
1031 // The device is asleep, so just pretend that the user
1032 // saw a crash dialog and hit "force quit".
1033 res.set(0);
1034 }
1035 }
1036 ensureBootCompleted();
1037 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 case SHOW_FACTORY_ERROR_MSG: {
1039 Dialog d = new FactoryErrorDialog(
1040 mContext, msg.getData().getCharSequence("msg"));
1041 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001042 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 } break;
1044 case UPDATE_CONFIGURATION_MSG: {
1045 final ContentResolver resolver = mContext.getContentResolver();
1046 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1047 } break;
1048 case GC_BACKGROUND_PROCESSES_MSG: {
1049 synchronized (ActivityManagerService.this) {
1050 performAppGcsIfAppropriateLocked();
1051 }
1052 } break;
1053 case WAIT_FOR_DEBUGGER_MSG: {
1054 synchronized (ActivityManagerService.this) {
1055 ProcessRecord app = (ProcessRecord)msg.obj;
1056 if (msg.arg1 != 0) {
1057 if (!app.waitedForDebugger) {
1058 Dialog d = new AppWaitingForDebuggerDialog(
1059 ActivityManagerService.this,
1060 mContext, app);
1061 app.waitDialog = d;
1062 app.waitedForDebugger = true;
1063 d.show();
1064 }
1065 } else {
1066 if (app.waitDialog != null) {
1067 app.waitDialog.dismiss();
1068 app.waitDialog = null;
1069 }
1070 }
1071 }
1072 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001074 if (mDidDexOpt) {
1075 mDidDexOpt = false;
1076 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1077 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001078 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001079 return;
1080 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001081 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 } break;
1083 case UPDATE_TIME_ZONE: {
1084 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001085 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1086 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 if (r.thread != null) {
1088 try {
1089 r.thread.updateTimeZone();
1090 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001091 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093 }
1094 }
1095 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001096 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001097 case CLEAR_DNS_CACHE: {
1098 synchronized (ActivityManagerService.this) {
1099 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1100 ProcessRecord r = mLruProcesses.get(i);
1101 if (r.thread != null) {
1102 try {
1103 r.thread.clearDnsCache();
1104 } catch (RemoteException ex) {
1105 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1106 }
1107 }
1108 }
1109 }
1110 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001111 case UPDATE_HTTP_PROXY: {
1112 ProxyProperties proxy = (ProxyProperties)msg.obj;
1113 String host = "";
1114 String port = "";
1115 String exclList = "";
1116 if (proxy != null) {
1117 host = proxy.getHost();
1118 port = Integer.toString(proxy.getPort());
1119 exclList = proxy.getExclusionList();
1120 }
1121 synchronized (ActivityManagerService.this) {
1122 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1123 ProcessRecord r = mLruProcesses.get(i);
1124 if (r.thread != null) {
1125 try {
1126 r.thread.setHttpProxy(host, port, exclList);
1127 } catch (RemoteException ex) {
1128 Slog.w(TAG, "Failed to update http proxy for: " +
1129 r.info.processName);
1130 }
1131 }
1132 }
1133 }
1134 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001136 String title = "System UIDs Inconsistent";
1137 String text = "UIDs on the system are inconsistent, you need to wipe your"
1138 + " data partition or your device will be unstable.";
1139 Log.e(TAG, title + ": " + text);
1140 if (mShowDialogs) {
1141 // XXX This is a temporary dialog, no need to localize.
1142 AlertDialog d = new BaseErrorDialog(mContext);
1143 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1144 d.setCancelable(false);
1145 d.setTitle(title);
1146 d.setMessage(text);
1147 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1148 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1149 mUidAlert = d;
1150 d.show();
1151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } break;
1153 case IM_FEELING_LUCKY_MSG: {
1154 if (mUidAlert != null) {
1155 mUidAlert.dismiss();
1156 mUidAlert = null;
1157 }
1158 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001160 if (mDidDexOpt) {
1161 mDidDexOpt = false;
1162 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1163 nmsg.obj = msg.obj;
1164 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1165 return;
1166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 ProcessRecord app = (ProcessRecord)msg.obj;
1168 synchronized (ActivityManagerService.this) {
1169 processStartTimedOutLocked(app);
1170 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001171 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001172 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1173 synchronized (ActivityManagerService.this) {
1174 doPendingActivityLaunchesLocked(true);
1175 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001176 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001177 case KILL_APPLICATION_MSG: {
1178 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001179 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001180 boolean restart = (msg.arg2 == 1);
1181 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001182 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1183 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001184 }
1185 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001186 case FINALIZE_PENDING_INTENT_MSG: {
1187 ((PendingIntentRecord)msg.obj).completeFinalize();
1188 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001189 case POST_HEAVY_NOTIFICATION_MSG: {
1190 INotificationManager inm = NotificationManager.getService();
1191 if (inm == null) {
1192 return;
1193 }
1194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001195 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001196 ProcessRecord process = root.app;
1197 if (process == null) {
1198 return;
1199 }
1200
1201 try {
1202 Context context = mContext.createPackageContext(process.info.packageName, 0);
1203 String text = mContext.getString(R.string.heavy_weight_notification,
1204 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1205 Notification notification = new Notification();
1206 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1207 notification.when = 0;
1208 notification.flags = Notification.FLAG_ONGOING_EVENT;
1209 notification.tickerText = text;
1210 notification.defaults = 0; // please be quiet
1211 notification.sound = null;
1212 notification.vibrate = null;
1213 notification.setLatestEventInfo(context, text,
1214 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001215 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1216 PendingIntent.FLAG_CANCEL_CURRENT, null,
1217 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001218
1219 try {
1220 int[] outId = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001221 inm.enqueueNotificationWithTag("android", "android", null,
Dianne Hackborn41203752012-08-31 14:05:51 -07001222 R.string.heavy_weight_notification,
1223 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001224 } catch (RuntimeException e) {
1225 Slog.w(ActivityManagerService.TAG,
1226 "Error showing notification for heavy-weight app", e);
1227 } catch (RemoteException e) {
1228 }
1229 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001230 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001231 }
1232 } break;
1233 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1234 INotificationManager inm = NotificationManager.getService();
1235 if (inm == null) {
1236 return;
1237 }
1238 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001239 inm.cancelNotificationWithTag("android", null,
1240 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001241 } catch (RuntimeException e) {
1242 Slog.w(ActivityManagerService.TAG,
1243 "Error canceling notification for service", e);
1244 } catch (RemoteException e) {
1245 }
1246 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001247 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1248 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001249 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001250 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001251 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1252 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001253 }
1254 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001255 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1256 synchronized (ActivityManagerService.this) {
1257 ActivityRecord ar = (ActivityRecord)msg.obj;
1258 if (mCompatModeDialog != null) {
1259 if (mCompatModeDialog.mAppInfo.packageName.equals(
1260 ar.info.applicationInfo.packageName)) {
1261 return;
1262 }
1263 mCompatModeDialog.dismiss();
1264 mCompatModeDialog = null;
1265 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001266 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001267 if (mCompatModePackages.getPackageAskCompatModeLocked(
1268 ar.packageName)) {
1269 int mode = mCompatModePackages.computeCompatModeLocked(
1270 ar.info.applicationInfo);
1271 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1272 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1273 mCompatModeDialog = new CompatModeDialog(
1274 ActivityManagerService.this, mContext,
1275 ar.info.applicationInfo);
1276 mCompatModeDialog.show();
1277 }
1278 }
1279 }
1280 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001281 break;
1282 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001283 case DISPATCH_PROCESSES_CHANGED: {
1284 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001285 break;
1286 }
1287 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001288 final int pid = msg.arg1;
1289 final int uid = msg.arg2;
1290 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001291 break;
1292 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001293 case REPORT_MEM_USAGE: {
1294 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1295 if (!isDebuggable) {
1296 return;
1297 }
1298 synchronized (ActivityManagerService.this) {
1299 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001300 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1301 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001302 // avoid spamming.
1303 return;
1304 }
1305 mLastMemUsageReportTime = now;
1306 }
1307 Thread thread = new Thread() {
1308 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001309 StringBuilder dropBuilder = new StringBuilder(1024);
1310 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001311 StringWriter oomSw = new StringWriter();
1312 PrintWriter oomPw = new PrintWriter(oomSw);
1313 StringWriter catSw = new StringWriter();
1314 PrintWriter catPw = new PrintWriter(catSw);
1315 String[] emptyArgs = new String[] { };
1316 StringBuilder tag = new StringBuilder(128);
1317 StringBuilder stack = new StringBuilder(128);
1318 tag.append("Low on memory -- ");
1319 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1320 tag, stack);
1321 dropBuilder.append(stack);
1322 dropBuilder.append('\n');
1323 dropBuilder.append('\n');
1324 String oomString = oomSw.toString();
1325 dropBuilder.append(oomString);
1326 dropBuilder.append('\n');
1327 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001328 try {
1329 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1330 "procrank", });
1331 final InputStreamReader converter = new InputStreamReader(
1332 proc.getInputStream());
1333 BufferedReader in = new BufferedReader(converter);
1334 String line;
1335 while (true) {
1336 line = in.readLine();
1337 if (line == null) {
1338 break;
1339 }
1340 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001341 logBuilder.append(line);
1342 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001343 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001344 dropBuilder.append(line);
1345 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001346 }
1347 converter.close();
1348 } catch (IOException e) {
1349 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001350 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001351 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001352 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001353 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001354 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1355 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001356 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001357 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001358 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001359 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001360 addErrorToDropBox("lowmem", null, "system_server", null,
1361 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001362 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001363 synchronized (ActivityManagerService.this) {
1364 long now = SystemClock.uptimeMillis();
1365 if (mLastMemUsageReportTime < now) {
1366 mLastMemUsageReportTime = now;
1367 }
1368 }
1369 }
1370 };
1371 thread.start();
1372 break;
1373 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001374 case REPORT_USER_SWITCH_MSG: {
1375 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1376 break;
1377 }
1378 case CONTINUE_USER_SWITCH_MSG: {
1379 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1380 break;
1381 }
1382 case USER_SWITCH_TIMEOUT_MSG: {
1383 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1384 break;
1385 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001386 case IMMERSIVE_MODE_LOCK_MSG: {
1387 final boolean nextState = (msg.arg1 != 0);
1388 if (mUpdateLock.isHeld() != nextState) {
1389 if (DEBUG_IMMERSIVE) {
1390 final ActivityRecord r = (ActivityRecord) msg.obj;
1391 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1392 }
1393 if (nextState) {
1394 mUpdateLock.acquire();
1395 } else {
1396 mUpdateLock.release();
1397 }
1398 }
1399 break;
1400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402 }
1403 };
1404
1405 public static void setSystemProcess() {
1406 try {
1407 ActivityManagerService m = mSelf;
1408
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001409 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001411 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001412 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 if (MONITOR_CPU_USAGE) {
1414 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 ServiceManager.addService("permission", new PermissionController(m));
1417
1418 ApplicationInfo info =
1419 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001420 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001421 mSystemThread.installSystemApplicationInfo(info);
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 synchronized (mSelf) {
1424 ProcessRecord app = mSelf.newProcessRecordLocked(
1425 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001426 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001428 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001429 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001430 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 synchronized (mSelf.mPidsSelfLocked) {
1432 mSelf.mPidsSelfLocked.put(app.pid, app);
1433 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001434 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436 } catch (PackageManager.NameNotFoundException e) {
1437 throw new RuntimeException(
1438 "Unable to find android system package", e);
1439 }
1440 }
1441
1442 public void setWindowManager(WindowManagerService wm) {
1443 mWindowManager = wm;
1444 }
1445
1446 public static final Context main(int factoryTest) {
1447 AThread thr = new AThread();
1448 thr.start();
1449
1450 synchronized (thr) {
1451 while (thr.mService == null) {
1452 try {
1453 thr.wait();
1454 } catch (InterruptedException e) {
1455 }
1456 }
1457 }
1458
1459 ActivityManagerService m = thr.mService;
1460 mSelf = m;
1461 ActivityThread at = ActivityThread.systemMain();
1462 mSystemThread = at;
1463 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001464 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 m.mContext = context;
1466 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001467 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468
1469 m.mBatteryStatsService.publish(context);
1470 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001471 m.mAppOpsService.publish(context);
1472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 synchronized (thr) {
1474 thr.mReady = true;
1475 thr.notifyAll();
1476 }
1477
1478 m.startRunning(null, null, null, null);
1479
1480 return context;
1481 }
1482
1483 public static ActivityManagerService self() {
1484 return mSelf;
1485 }
1486
1487 static class AThread extends Thread {
1488 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001489 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 boolean mReady = false;
1491
1492 public AThread() {
1493 super("ActivityManager");
1494 }
1495
1496 public void run() {
1497 Looper.prepare();
1498
1499 android.os.Process.setThreadPriority(
1500 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001501 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502
1503 ActivityManagerService m = new ActivityManagerService();
1504
1505 synchronized (this) {
1506 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001507 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 notifyAll();
1509 }
1510
1511 synchronized (this) {
1512 while (!mReady) {
1513 try {
1514 wait();
1515 } catch (InterruptedException e) {
1516 }
1517 }
1518 }
1519
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001520 // For debug builds, log event loop stalls to dropbox for analysis.
1521 if (StrictMode.conditionallyEnableDebugLogging()) {
1522 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1523 }
1524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 Looper.loop();
1526 }
1527 }
1528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 static class MemBinder extends Binder {
1530 ActivityManagerService mActivityManagerService;
1531 MemBinder(ActivityManagerService activityManagerService) {
1532 mActivityManagerService = activityManagerService;
1533 }
1534
1535 @Override
1536 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001537 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1538 != PackageManager.PERMISSION_GRANTED) {
1539 pw.println("Permission Denial: can't dump meminfo from from pid="
1540 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1541 + " without permission " + android.Manifest.permission.DUMP);
1542 return;
1543 }
1544
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001545 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001546 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549
Chet Haase9c1e23b2011-03-24 10:51:31 -07001550 static class GraphicsBinder extends Binder {
1551 ActivityManagerService mActivityManagerService;
1552 GraphicsBinder(ActivityManagerService activityManagerService) {
1553 mActivityManagerService = activityManagerService;
1554 }
1555
1556 @Override
1557 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001558 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1559 != PackageManager.PERMISSION_GRANTED) {
1560 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1561 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1562 + " without permission " + android.Manifest.permission.DUMP);
1563 return;
1564 }
1565
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001566 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001567 }
1568 }
1569
Jeff Brown6754ba22011-12-14 20:20:01 -08001570 static class DbBinder extends Binder {
1571 ActivityManagerService mActivityManagerService;
1572 DbBinder(ActivityManagerService activityManagerService) {
1573 mActivityManagerService = activityManagerService;
1574 }
1575
1576 @Override
1577 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1578 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1579 != PackageManager.PERMISSION_GRANTED) {
1580 pw.println("Permission Denial: can't dump dbinfo from from pid="
1581 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1582 + " without permission " + android.Manifest.permission.DUMP);
1583 return;
1584 }
1585
1586 mActivityManagerService.dumpDbInfo(fd, pw, args);
1587 }
1588 }
1589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 static class CpuBinder extends Binder {
1591 ActivityManagerService mActivityManagerService;
1592 CpuBinder(ActivityManagerService activityManagerService) {
1593 mActivityManagerService = activityManagerService;
1594 }
1595
1596 @Override
1597 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001598 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1599 != PackageManager.PERMISSION_GRANTED) {
1600 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1601 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1602 + " without permission " + android.Manifest.permission.DUMP);
1603 return;
1604 }
1605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001607 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1608 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1609 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
1611 }
1612 }
1613
1614 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001615 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001616
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001617 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1618 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1619 mBroadcastQueues[0] = mFgBroadcastQueue;
1620 mBroadcastQueues[1] = mBgBroadcastQueue;
1621
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001622 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001623 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 File dataDir = Environment.getDataDirectory();
1626 File systemDir = new File(dataDir, "system");
1627 systemDir.mkdirs();
1628 mBatteryStatsService = new BatteryStatsService(new File(
1629 systemDir, "batterystats.bin").toString());
1630 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001631 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001632 mOnBattery = DEBUG_POWER ? true
1633 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001634 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001635
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001636 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001637 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001638 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001639 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001641 // User 0 is the first and only user that runs at boot.
1642 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001643 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001644 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001645
Jack Palevichb90d28c2009-07-22 15:35:24 -07001646 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1647 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1648
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001649 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001650 mConfiguration.setLocale(Locale.getDefault());
1651
Dianne Hackborn813075a62011-11-14 17:45:19 -08001652 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 mProcessStats.init();
1654
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001655 mCompatModePackages = new CompatModePackages(this, systemDir);
1656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 // Add ourself to the Watchdog monitors.
1658 Watchdog.getInstance().addMonitor(this);
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 mProcessStatsThread = new Thread("ProcessStats") {
1661 public void run() {
1662 while (true) {
1663 try {
1664 try {
1665 synchronized(this) {
1666 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001667 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001669 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 // + ", write delay=" + nextWriteDelay);
1671 if (nextWriteDelay < nextCpuDelay) {
1672 nextCpuDelay = nextWriteDelay;
1673 }
1674 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001675 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 this.wait(nextCpuDelay);
1677 }
1678 }
1679 } catch (InterruptedException e) {
1680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 updateCpuStatsNow();
1682 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001683 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685 }
1686 }
1687 };
1688 mProcessStatsThread.start();
1689 }
1690
1691 @Override
1692 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1693 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001694 if (code == SYSPROPS_TRANSACTION) {
1695 // We need to tell all apps about the system property change.
1696 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1697 synchronized(this) {
1698 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1699 final int NA = apps.size();
1700 for (int ia=0; ia<NA; ia++) {
1701 ProcessRecord app = apps.valueAt(ia);
1702 if (app.thread != null) {
1703 procs.add(app.thread.asBinder());
1704 }
1705 }
1706 }
1707 }
1708
1709 int N = procs.size();
1710 for (int i=0; i<N; i++) {
1711 Parcel data2 = Parcel.obtain();
1712 try {
1713 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1714 } catch (RemoteException e) {
1715 }
1716 data2.recycle();
1717 }
1718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 try {
1720 return super.onTransact(code, data, reply, flags);
1721 } catch (RuntimeException e) {
1722 // The activity manager only throws security exceptions, so let's
1723 // log all others.
1724 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001725 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
1727 throw e;
1728 }
1729 }
1730
1731 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001732 final long now = SystemClock.uptimeMillis();
1733 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1734 return;
1735 }
1736 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1737 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 mProcessStatsThread.notify();
1739 }
1740 }
1741 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 void updateCpuStatsNow() {
1744 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001745 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 final long now = SystemClock.uptimeMillis();
1747 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001750 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1751 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 haveNewCpuStats = true;
1753 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001754 //Slog.i(TAG, mProcessStats.printCurrentState());
1755 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 // + mProcessStats.getTotalCpuPercent() + "%");
1757
Joe Onorato8a9b2202010-02-26 18:56:32 -08001758 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 if ("true".equals(SystemProperties.get("events.cpu"))) {
1760 int user = mProcessStats.getLastUserTime();
1761 int system = mProcessStats.getLastSystemTime();
1762 int iowait = mProcessStats.getLastIoWaitTime();
1763 int irq = mProcessStats.getLastIrqTime();
1764 int softIrq = mProcessStats.getLastSoftIrqTime();
1765 int idle = mProcessStats.getLastIdleTime();
1766
1767 int total = user + system + iowait + irq + softIrq + idle;
1768 if (total == 0) total = 1;
1769
Doug Zongker2bec3d42009-12-04 12:52:44 -08001770 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 ((user+system+iowait+irq+softIrq) * 100) / total,
1772 (user * 100) / total,
1773 (system * 100) / total,
1774 (iowait * 100) / total,
1775 (irq * 100) / total,
1776 (softIrq * 100) / total);
1777 }
1778 }
1779
Amith Yamasanie43530a2009-08-21 13:11:37 -07001780 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001781 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001782 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 synchronized(mPidsSelfLocked) {
1784 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001785 if (mOnBattery) {
1786 int perc = bstats.startAddingCpuLocked();
1787 int totalUTime = 0;
1788 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001789 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001791 ProcessStats.Stats st = mProcessStats.getStats(i);
1792 if (!st.working) {
1793 continue;
1794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001796 int otherUTime = (st.rel_utime*perc)/100;
1797 int otherSTime = (st.rel_stime*perc)/100;
1798 totalUTime += otherUTime;
1799 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 if (pr != null) {
1801 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001802 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1803 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001804 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001805 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001806 } else {
1807 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001808 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001809 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001810 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1811 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001812 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001816 bstats.finishAddingCpuLocked(perc, totalUTime,
1817 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
1819 }
1820 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1823 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001824 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 }
1826 }
1827 }
1828 }
1829
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001830 @Override
1831 public void batteryNeedsCpuUpdate() {
1832 updateCpuStatsNow();
1833 }
1834
1835 @Override
1836 public void batteryPowerChanged(boolean onBattery) {
1837 // When plugging in, update the CPU stats first before changing
1838 // the plug state.
1839 updateCpuStatsNow();
1840 synchronized (this) {
1841 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001842 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001843 }
1844 }
1845 }
1846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 /**
1848 * Initialize the application bind args. These are passed to each
1849 * process when the bindApplication() IPC is sent to the process. They're
1850 * lazily setup to make sure the services are running when they're asked for.
1851 */
1852 private HashMap<String, IBinder> getCommonServicesLocked() {
1853 if (mAppBindArgs == null) {
1854 mAppBindArgs = new HashMap<String, IBinder>();
1855
1856 // Setup the application init args
1857 mAppBindArgs.put("package", ServiceManager.getService("package"));
1858 mAppBindArgs.put("window", ServiceManager.getService("window"));
1859 mAppBindArgs.put(Context.ALARM_SERVICE,
1860 ServiceManager.getService(Context.ALARM_SERVICE));
1861 }
1862 return mAppBindArgs;
1863 }
1864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001865 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 if (mFocusedActivity != r) {
1867 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001868 if (r != null) {
1869 mWindowManager.setFocusedApp(r.appToken, true);
1870 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001871 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
1873 }
1874
Christopher Tate73c2aee2012-03-15 16:27:14 -07001875 final void applyUpdateLockStateLocked(ActivityRecord r) {
1876 // Modifications to the UpdateLock state are done on our handler, outside
1877 // the activity manager's locks. The new state is determined based on the
1878 // state *now* of the relevant activity record. The object is passed to
1879 // the handler solely for logging detail, not to be consulted/modified.
1880 final boolean nextState = r != null && r.immersive;
1881 mHandler.sendMessage(
1882 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1883 }
1884
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001885 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001887 int lrui = mLruProcesses.indexOf(app);
1888 if (lrui >= 0) mLruProcesses.remove(lrui);
1889
1890 int i = mLruProcesses.size()-1;
1891 int skipTop = 0;
1892
Dianne Hackborn906497c2010-05-10 15:57:38 -07001893 app.lruSeq = mLruSeq;
1894
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001895 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001896 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001897 if (app.activities.size() > 0) {
1898 // If this process has activities, we more strongly want to keep
1899 // it around.
1900 app.lruWeight = app.lastActivityTime;
1901 } else if (app.pubProviders.size() > 0) {
1902 // If this process contains content providers, we want to keep
1903 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001904 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001905 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001906 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001907 } else {
1908 // If this process doesn't have activities, we less strongly
1909 // want to keep it around, and generally want to avoid getting
1910 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001911 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001912 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001913 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001914 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001915
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001916 while (i >= 0) {
1917 ProcessRecord p = mLruProcesses.get(i);
1918 // If this app shouldn't be in front of the first N background
1919 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001920 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001921 skipTop--;
1922 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001923 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001924 mLruProcesses.add(i+1, app);
1925 break;
1926 }
1927 i--;
1928 }
1929 if (i < 0) {
1930 mLruProcesses.add(0, app);
1931 }
1932
Dianne Hackborn906497c2010-05-10 15:57:38 -07001933 // If the app is currently using a content provider or service,
1934 // bump those processes as well.
1935 if (app.connections.size() > 0) {
1936 for (ConnectionRecord cr : app.connections) {
1937 if (cr.binding != null && cr.binding.service != null
1938 && cr.binding.service.app != null
1939 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001940 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001941 }
1942 }
1943 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001944 for (int j=app.conProviders.size()-1; j>=0; j--) {
1945 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1946 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001947 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001948 }
1949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 }
1951
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001952 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001953 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001954 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001955 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001956
1957 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1958 if (oomAdj) {
1959 updateOomAdjLocked();
1960 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001961 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001962
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001963 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001964 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001965 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001966 // The system gets to run in any process. If there are multiple
1967 // processes with the same uid, just pick the first (this
1968 // should never happen).
1969 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1970 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001971 if (procs == null) return null;
1972 final int N = procs.size();
1973 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001974 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977 ProcessRecord proc = mProcessNames.get(processName, uid);
1978 return proc;
1979 }
1980
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001981 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001982 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001983 try {
1984 if (pm.performDexOpt(packageName)) {
1985 mDidDexOpt = true;
1986 }
1987 } catch (RemoteException e) {
1988 }
1989 }
1990
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001991 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08001993 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
1994 || transit == AppTransition.TRANSIT_TASK_OPEN
1995 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 }
1997
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001998 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002000 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2001 boolean isolated) {
2002 ProcessRecord app;
2003 if (!isolated) {
2004 app = getProcessRecordLocked(processName, info.uid);
2005 } else {
2006 // If this is an isolated process, it can't re-use an existing process.
2007 app = null;
2008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 // We don't have to do anything more if:
2010 // (1) There is an existing application record; and
2011 // (2) The caller doesn't think it is dead, OR there is no thread
2012 // object attached to it so we know it couldn't have crashed; and
2013 // (3) There is a pid assigned to it, so it is either starting or
2014 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002015 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 + " app=" + app + " knownToBeDead=" + knownToBeDead
2017 + " thread=" + (app != null ? app.thread : null)
2018 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002019 if (app != null && app.pid > 0) {
2020 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002021 // We already have the app running, or are waiting for it to
2022 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002023 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002024 // If this is a new package in the process, add the package to the list
2025 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002026 return app;
2027 } else {
2028 // An application record is attached to a previous process,
2029 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002030 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002031 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 String hostingNameStr = hostingName != null
2036 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002037
2038 if (!isolated) {
2039 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2040 // If we are in the background, then check to see if this process
2041 // is bad. If so, we will just silently fail.
2042 if (mBadProcesses.get(info.processName, info.uid) != null) {
2043 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2044 + "/" + info.processName);
2045 return null;
2046 }
2047 } else {
2048 // When the user is explicitly starting a process, then clear its
2049 // crash count so that we won't make it bad until they see at
2050 // least one crash dialog again, and make the process good again
2051 // if it had been bad.
2052 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002053 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002054 mProcessCrashTimes.remove(info.processName, info.uid);
2055 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002056 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2057 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002058 info.processName);
2059 mBadProcesses.remove(info.processName, info.uid);
2060 if (app != null) {
2061 app.bad = false;
2062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
2064 }
2065 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002068 app = newProcessRecordLocked(null, info, processName, isolated);
2069 if (app == null) {
2070 Slog.w(TAG, "Failed making new process record for "
2071 + processName + "/" + info.uid + " isolated=" + isolated);
2072 return null;
2073 }
2074 mProcessNames.put(processName, app.uid, app);
2075 if (isolated) {
2076 mIsolatedProcesses.put(app.uid, app);
2077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 } else {
2079 // If this is a new package in the process, add the package to the list
2080 app.addPackage(info.packageName);
2081 }
2082
2083 // If the system is not ready yet, then hold off on starting this
2084 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002085 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002086 && !isAllowedWhileBooting(info)
2087 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 if (!mProcessesOnHold.contains(app)) {
2089 mProcessesOnHold.add(app);
2090 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002091 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 return app;
2093 }
2094
2095 startProcessLocked(app, hostingType, hostingNameStr);
2096 return (app.pid != 0) ? app : null;
2097 }
2098
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002099 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2100 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2101 }
2102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 private final void startProcessLocked(ProcessRecord app,
2104 String hostingType, String hostingNameStr) {
2105 if (app.pid > 0 && app.pid != MY_PID) {
2106 synchronized (mPidsSelfLocked) {
2107 mPidsSelfLocked.remove(app.pid);
2108 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2109 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002110 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002113 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2114 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 mProcessesOnHold.remove(app);
2116
2117 updateCpuStats();
2118
2119 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2120 mProcDeaths[0] = 0;
2121
2122 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002123 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002126 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002127 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002128 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002129 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002130 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002131 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002132
2133 if (Environment.isExternalStorageEmulated()) {
2134 if (pm.checkPermission(
2135 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2136 app.info.packageName) == PERMISSION_GRANTED) {
2137 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2138 } else {
2139 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2140 }
2141 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002142 } catch (PackageManager.NameNotFoundException e) {
2143 Slog.w(TAG, "Unable to retrieve gids", e);
2144 }
Kenny Roote091f222012-09-11 15:01:26 -07002145
2146 /*
2147 * Add shared application GID so applications can share some
2148 * resources like shared libraries
2149 */
2150 if (permGids == null) {
2151 gids = new int[1];
2152 } else {
2153 gids = new int[permGids.length + 1];
2154 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2155 }
2156 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2159 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2160 && mTopComponent != null
2161 && app.processName.equals(mTopComponent.getPackageName())) {
2162 uid = 0;
2163 }
2164 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2165 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2166 uid = 0;
2167 }
2168 }
2169 int debugFlags = 0;
2170 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2171 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002172 // Also turn on CheckJNI for debuggable apps. It's quite
2173 // awkward to turn on otherwise.
2174 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002176 // Run the app in safe mode if its manifest requests so or the
2177 // system is booted in safe mode.
2178 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2179 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002180 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2183 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2184 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002185 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2186 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 if ("1".equals(SystemProperties.get("debug.assert"))) {
2189 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2190 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002191
2192 // Start the process. It will either succeed and return a result containing
2193 // the PID of the new process, or else throw a RuntimeException.
2194 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002195 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002196 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002198 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2199 synchronized (bs) {
2200 if (bs.isOnBattery()) {
2201 app.batteryStats.incStartsLocked();
2202 }
2203 }
2204
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002205 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2206 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 app.processName, hostingType,
2208 hostingNameStr != null ? hostingNameStr : "");
2209
2210 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002211 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002214 StringBuilder buf = mStringBuilder;
2215 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 buf.append("Start proc ");
2217 buf.append(app.processName);
2218 buf.append(" for ");
2219 buf.append(hostingType);
2220 if (hostingNameStr != null) {
2221 buf.append(" ");
2222 buf.append(hostingNameStr);
2223 }
2224 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002225 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 buf.append(" uid=");
2227 buf.append(uid);
2228 buf.append(" gids={");
2229 if (gids != null) {
2230 for (int gi=0; gi<gids.length; gi++) {
2231 if (gi != 0) buf.append(", ");
2232 buf.append(gids[gi]);
2233
2234 }
2235 }
2236 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002237 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002238 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002239 app.usingWrapper = startResult.usingWrapper;
2240 app.removed = false;
2241 synchronized (mPidsSelfLocked) {
2242 this.mPidsSelfLocked.put(startResult.pid, app);
2243 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2244 msg.obj = app;
2245 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2246 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247 }
2248 } catch (RuntimeException e) {
2249 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002250 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002251 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
2253 }
2254
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 if (resumed) {
2257 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2258 } else {
2259 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2260 }
2261 }
2262
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002263 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002264 if (mHeadless) {
2265 // Added because none of the other calls to ensureBootCompleted seem to fire
2266 // when running headless.
2267 ensureBootCompleted();
2268 return false;
2269 }
2270
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002271 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2272 && mTopAction == null) {
2273 // We are running in factory test mode, but unable to find
2274 // the factory test app, so just sit around displaying the
2275 // error message and don't try to start anything.
2276 return false;
2277 }
2278 Intent intent = new Intent(
2279 mTopAction,
2280 mTopData != null ? Uri.parse(mTopData) : null);
2281 intent.setComponent(mTopComponent);
2282 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2283 intent.addCategory(Intent.CATEGORY_HOME);
2284 }
2285 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002286 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002287 if (aInfo != null) {
2288 intent.setComponent(new ComponentName(
2289 aInfo.applicationInfo.packageName, aInfo.name));
2290 // Don't do this if the home app is currently being
2291 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002292 aInfo = new ActivityInfo(aInfo);
2293 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002294 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2295 aInfo.applicationInfo.uid);
2296 if (app == null || app.instrumentationClass == null) {
2297 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002298 mMainStack.startActivityLocked(null, intent, null, aInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002299 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002300 }
2301 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002302
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002303 return true;
2304 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002305
Amith Yamasani259d5e52012-08-31 15:11:01 -07002306 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2307 ActivityInfo ai = null;
2308 ComponentName comp = intent.getComponent();
2309 try {
2310 if (comp != null) {
2311 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2312 } else {
2313 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2314 intent,
2315 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2316 flags, userId);
2317
2318 if (info != null) {
2319 ai = info.activityInfo;
2320 }
2321 }
2322 } catch (RemoteException e) {
2323 // ignore
2324 }
2325
2326 return ai;
2327 }
2328
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002329 /**
2330 * Starts the "new version setup screen" if appropriate.
2331 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002332 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002333 // Only do this once per boot.
2334 if (mCheckedForSetup) {
2335 return;
2336 }
2337
2338 // We will show this screen if the current one is a different
2339 // version than the last one shown, and we are not running in
2340 // low-level factory test mode.
2341 final ContentResolver resolver = mContext.getContentResolver();
2342 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002343 Settings.Global.getInt(resolver,
2344 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002345 mCheckedForSetup = true;
2346
2347 // See if we should be showing the platform update setup UI.
2348 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2349 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2350 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2351
2352 // We don't allow third party apps to replace this.
2353 ResolveInfo ri = null;
2354 for (int i=0; ris != null && i<ris.size(); i++) {
2355 if ((ris.get(i).activityInfo.applicationInfo.flags
2356 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2357 ri = ris.get(i);
2358 break;
2359 }
2360 }
2361
2362 if (ri != null) {
2363 String vers = ri.activityInfo.metaData != null
2364 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2365 : null;
2366 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2367 vers = ri.activityInfo.applicationInfo.metaData.getString(
2368 Intent.METADATA_SETUP_VERSION);
2369 }
2370 String lastVers = Settings.Secure.getString(
2371 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2372 if (vers != null && !vers.equals(lastVers)) {
2373 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2374 intent.setComponent(new ComponentName(
2375 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002376 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002377 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002378 }
2379 }
2380 }
2381 }
2382
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002383 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002384 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002385 }
2386
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002387 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002388 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002389 throw new SecurityException("Isolated process not allowed to call " + caller);
2390 }
2391 }
2392
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002393 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002394 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002395 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002396 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2397 }
2398 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002399
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002400 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002401 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2402 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002403 synchronized (this) {
2404 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2405 }
2406 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002407
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002408 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002409 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002410 synchronized (this) {
2411 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2412 }
2413 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002414
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002415 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002416 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2417 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002418 synchronized (this) {
2419 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002420 }
2421 }
2422
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002423 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002424 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002425 synchronized (this) {
2426 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2427 }
2428 }
2429
2430 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002431 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2432 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002433 synchronized (this) {
2434 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2435 }
2436 }
2437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002438 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002439 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002440 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002443 private void dispatchProcessesChanged() {
2444 int N;
2445 synchronized (this) {
2446 N = mPendingProcessChanges.size();
2447 if (mActiveProcessChanges.length < N) {
2448 mActiveProcessChanges = new ProcessChangeItem[N];
2449 }
2450 mPendingProcessChanges.toArray(mActiveProcessChanges);
2451 mAvailProcessChanges.addAll(mPendingProcessChanges);
2452 mPendingProcessChanges.clear();
2453 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2454 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002455 int i = mProcessObservers.beginBroadcast();
2456 while (i > 0) {
2457 i--;
2458 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2459 if (observer != null) {
2460 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002461 for (int j=0; j<N; j++) {
2462 ProcessChangeItem item = mActiveProcessChanges[j];
2463 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2464 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2465 + item.pid + " uid=" + item.uid + ": "
2466 + item.foregroundActivities);
2467 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2468 item.foregroundActivities);
2469 }
2470 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2471 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2472 + item.pid + " uid=" + item.uid + ": " + item.importance);
2473 observer.onImportanceChanged(item.pid, item.uid,
2474 item.importance);
2475 }
2476 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002477 } catch (RemoteException e) {
2478 }
2479 }
2480 }
2481 mProcessObservers.finishBroadcast();
2482 }
2483
2484 private void dispatchProcessDied(int pid, int uid) {
2485 int i = mProcessObservers.beginBroadcast();
2486 while (i > 0) {
2487 i--;
2488 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2489 if (observer != null) {
2490 try {
2491 observer.onProcessDied(pid, uid);
2492 } catch (RemoteException e) {
2493 }
2494 }
2495 }
2496 mProcessObservers.finishBroadcast();
2497 }
2498
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002499 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002500 final int N = mPendingActivityLaunches.size();
2501 if (N <= 0) {
2502 return;
2503 }
2504 for (int i=0; i<N; i++) {
2505 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002507 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002508 }
2509 mPendingActivityLaunches.clear();
2510 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002511
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002512 public final int startActivity(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002513 Intent intent, String resolvedType, IBinder resultTo,
2514 String resultWho, int requestCode, int startFlags,
2515 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002516 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
2517 resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002518 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002519 }
2520
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002521 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Amith Yamasani82644082012-08-03 13:09:11 -07002522 Intent intent, String resolvedType, IBinder resultTo,
2523 String resultWho, int requestCode, int startFlags,
2524 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002525 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002526 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002527 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002528 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002529 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2530 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002531 }
2532
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002533 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002534 Intent intent, String resolvedType, IBinder resultTo,
2535 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002536 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002537 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002538 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002539 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002540 WaitResult res = new WaitResult();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002541 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002542 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002543 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002544 return res;
2545 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002546
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002547 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002548 Intent intent, String resolvedType, IBinder resultTo,
2549 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002550 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002551 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002552 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002553 false, true, "startActivityWithConfig", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002554 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002555 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002556 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002557 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002558 }
2559
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002560 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002561 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002562 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002564 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002565 // Refuse possible leaked file descriptors
2566 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2567 throw new IllegalArgumentException("File descriptors passed in Intent");
2568 }
2569
2570 IIntentSender sender = intent.getTarget();
2571 if (!(sender instanceof PendingIntentRecord)) {
2572 throw new IllegalArgumentException("Bad PendingIntent object");
2573 }
2574
2575 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002576
2577 synchronized (this) {
2578 // If this is coming from the currently resumed activity, it is
2579 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002580 if (mMainStack.mResumedActivity != null
2581 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002582 Binder.getCallingUid()) {
2583 mAppSwitchesAllowedTime = 0;
2584 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002585 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002586 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2587 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002588 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002589 }
2590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002592 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 // Refuse possible leaked file descriptors
2594 if (intent != null && intent.hasFileDescriptors() == true) {
2595 throw new IllegalArgumentException("File descriptors passed in Intent");
2596 }
2597
2598 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002599 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2600 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002601 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 return false;
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 if (r.app == null || r.app.thread == null) {
2605 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002606 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 return false;
2608 }
2609 intent = new Intent(intent);
2610 // The caller is not allowed to change the data.
2611 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2612 // And we are resetting to find the next component...
2613 intent.setComponent(null);
2614
2615 ActivityInfo aInfo = null;
2616 try {
2617 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002618 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002620 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002621 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622
2623 // Look for the original activity in the list...
2624 final int N = resolves != null ? resolves.size() : 0;
2625 for (int i=0; i<N; i++) {
2626 ResolveInfo rInfo = resolves.get(i);
2627 if (rInfo.activityInfo.packageName.equals(r.packageName)
2628 && rInfo.activityInfo.name.equals(r.info.name)) {
2629 // We found the current one... the next matching is
2630 // after it.
2631 i++;
2632 if (i<N) {
2633 aInfo = resolves.get(i).activityInfo;
2634 }
2635 break;
2636 }
2637 }
2638 } catch (RemoteException e) {
2639 }
2640
2641 if (aInfo == null) {
2642 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002643 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 return false;
2645 }
2646
2647 intent.setComponent(new ComponentName(
2648 aInfo.applicationInfo.packageName, aInfo.name));
2649 intent.setFlags(intent.getFlags()&~(
2650 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2651 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2652 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2653 Intent.FLAG_ACTIVITY_NEW_TASK));
2654
2655 // Okay now we need to start the new activity, replacing the
2656 // currently running activity. This is a little tricky because
2657 // we want to start the new one as if the current one is finished,
2658 // but not finish the current one first so that there is no flicker.
2659 // And thus...
2660 final boolean wasFinishing = r.finishing;
2661 r.finishing = true;
2662
2663 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002664 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 final String resultWho = r.resultWho;
2666 final int requestCode = r.requestCode;
2667 r.resultTo = null;
2668 if (resultTo != null) {
2669 resultTo.removeResultsLocked(r, resultWho, requestCode);
2670 }
2671
2672 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002673 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002674 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002675 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002676 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 Binder.restoreCallingIdentity(origId);
2678
2679 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002680 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 return false;
2682 }
2683 return true;
2684 }
2685 }
2686
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002687 final int startActivityInPackage(int uid, String callingPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002689 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2690
Dianne Hackborn139748f2012-09-24 11:36:57 -07002691 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002692 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002694 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002695 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002696 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002697 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002698 }
2699
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002700 public final int startActivities(IApplicationThread caller, String callingPackage,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002701 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2702 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002703 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002704 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002705 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002706 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents,
2707 resolvedTypes, resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002708 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002709 }
2710
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002711 final int startActivitiesInPackage(int uid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002712 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002713 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002714
Dianne Hackborn139748f2012-09-24 11:36:57 -07002715 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002716 false, true, "startActivityInPackage", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002717 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes,
2718 resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002719 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002722 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002724 // Quick case: check if the top-most recent task is the same.
2725 if (N > 0 && mRecentTasks.get(0) == task) {
2726 return;
2727 }
2728 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002729 for (int i=0; i<N; i++) {
2730 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002731 if (task.userId == tr.userId
2732 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2733 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002734 mRecentTasks.remove(i);
2735 i--;
2736 N--;
2737 if (task.intent == null) {
2738 // If the new recent task we are adding is not fully
2739 // specified, then replace it with the existing recent task.
2740 task = tr;
2741 }
2742 }
2743 }
2744 if (N >= MAX_RECENT_TASKS) {
2745 mRecentTasks.remove(N-1);
2746 }
2747 mRecentTasks.add(0, task);
2748 }
2749
2750 public void setRequestedOrientation(IBinder token,
2751 int requestedOrientation) {
2752 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002753 ActivityRecord r = mMainStack.isInStackLocked(token);
2754 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 return;
2756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002758 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002760 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002761 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 if (config != null) {
2763 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002764 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002765 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 }
2767 }
2768 Binder.restoreCallingIdentity(origId);
2769 }
2770 }
2771
2772 public int getRequestedOrientation(IBinder token) {
2773 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002774 ActivityRecord r = mMainStack.isInStackLocked(token);
2775 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2777 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002778 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 /**
2783 * This is the internal entry point for handling Activity.finish().
2784 *
2785 * @param token The Binder token referencing the Activity we want to finish.
2786 * @param resultCode Result code, if any, from this Activity.
2787 * @param resultData Result data (Intent), if any, from this Activity.
2788 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002789 * @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 -08002790 */
2791 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2792 // Refuse possible leaked file descriptors
2793 if (resultData != null && resultData.hasFileDescriptors() == true) {
2794 throw new IllegalArgumentException("File descriptors passed in Intent");
2795 }
2796
2797 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002798 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002799 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002800 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 if (next != null) {
2802 // ask watcher if this is allowed
2803 boolean resumeOK = true;
2804 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002805 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002807 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002808 }
2809
2810 if (!resumeOK) {
2811 return false;
2812 }
2813 }
2814 }
2815 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002816 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002817 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 Binder.restoreCallingIdentity(origId);
2819 return res;
2820 }
2821 }
2822
Dianne Hackborn860755f2010-06-03 18:47:52 -07002823 public final void finishHeavyWeightApp() {
2824 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2825 != PackageManager.PERMISSION_GRANTED) {
2826 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2827 + Binder.getCallingPid()
2828 + ", uid=" + Binder.getCallingUid()
2829 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2830 Slog.w(TAG, msg);
2831 throw new SecurityException(msg);
2832 }
2833
2834 synchronized(this) {
2835 if (mHeavyWeightProcess == null) {
2836 return;
2837 }
2838
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002839 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002840 mHeavyWeightProcess.activities);
2841 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002842 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002843 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002844 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002845 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002846 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002847 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002848 }
2849 }
2850 }
2851
Dianne Hackborn41203752012-08-31 14:05:51 -07002852 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2853 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002854 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002855 }
2856 }
2857
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002858 public void crashApplication(int uid, int initialPid, String packageName,
2859 String message) {
2860 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2861 != PackageManager.PERMISSION_GRANTED) {
2862 String msg = "Permission Denial: crashApplication() from pid="
2863 + Binder.getCallingPid()
2864 + ", uid=" + Binder.getCallingUid()
2865 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2866 Slog.w(TAG, msg);
2867 throw new SecurityException(msg);
2868 }
2869
2870 synchronized(this) {
2871 ProcessRecord proc = null;
2872
2873 // Figure out which process to kill. We don't trust that initialPid
2874 // still has any relation to current pids, so must scan through the
2875 // list.
2876 synchronized (mPidsSelfLocked) {
2877 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2878 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002879 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002880 continue;
2881 }
2882 if (p.pid == initialPid) {
2883 proc = p;
2884 break;
2885 }
2886 for (String str : p.pkgList) {
2887 if (str.equals(packageName)) {
2888 proc = p;
2889 }
2890 }
2891 }
2892 }
2893
2894 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002895 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002896 + " initialPid=" + initialPid
2897 + " packageName=" + packageName);
2898 return;
2899 }
2900
2901 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002902 if (proc.pid == Process.myPid()) {
2903 Log.w(TAG, "crashApplication: trying to crash self!");
2904 return;
2905 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002906 long ident = Binder.clearCallingIdentity();
2907 try {
2908 proc.thread.scheduleCrash(message);
2909 } catch (RemoteException e) {
2910 }
2911 Binder.restoreCallingIdentity(ident);
2912 }
2913 }
2914 }
2915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 public final void finishSubActivity(IBinder token, String resultWho,
2917 int requestCode) {
2918 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002920 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002921 Binder.restoreCallingIdentity(origId);
2922 }
2923 }
2924
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002925 public boolean finishActivityAffinity(IBinder token) {
2926 synchronized(this) {
2927 final long origId = Binder.clearCallingIdentity();
2928 boolean res = mMainStack.finishActivityAffinityLocked(token);
2929 Binder.restoreCallingIdentity(origId);
2930 return res;
2931 }
2932 }
2933
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002934 public boolean willActivityBeVisible(IBinder token) {
2935 synchronized(this) {
2936 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002937 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2938 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002939 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002940 return true;
2941 }
2942 if (r.fullscreen && !r.finishing) {
2943 return false;
2944 }
2945 }
2946 return true;
2947 }
2948 }
2949
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002950 public void overridePendingTransition(IBinder token, String packageName,
2951 int enterAnim, int exitAnim) {
2952 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002953 ActivityRecord self = mMainStack.isInStackLocked(token);
2954 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002955 return;
2956 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002957
2958 final long origId = Binder.clearCallingIdentity();
2959
2960 if (self.state == ActivityState.RESUMED
2961 || self.state == ActivityState.PAUSING) {
2962 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002963 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002964 }
2965
2966 Binder.restoreCallingIdentity(origId);
2967 }
2968 }
2969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 * Main function for removing an existing process from the activity manager
2972 * as a result of that process going away. Clears out all connections
2973 * to the process.
2974 */
2975 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002976 boolean restarting, boolean allowRestart) {
2977 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002978 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002979 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 }
2981
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002982 if (mProfileProc == app) {
2983 clearProfilerLocked();
2984 }
2985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002987 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002988 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2989 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002990 mMainStack.mPausingActivity = null;
2991 }
2992 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2993 mMainStack.mLastPausedActivity = null;
2994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995
2996 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002997 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998
2999 app.activities.clear();
3000
3001 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003002 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 + " running instrumentation " + app.instrumentationClass);
3004 Bundle info = new Bundle();
3005 info.putString("shortMsg", "Process crashed.");
3006 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3007 }
3008
3009 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003010 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 // If there was nothing to resume, and we are not already
3012 // restarting this process, but there is a visible activity that
3013 // is hosted by the process... then make sure all visible
3014 // activities are running, taking care of restarting this
3015 // process.
3016 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003017 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003018 }
3019 }
3020 }
3021 }
3022
3023 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3024 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003026 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3027 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3029 return i;
3030 }
3031 }
3032 return -1;
3033 }
3034
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003035 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 IApplicationThread thread) {
3037 if (thread == null) {
3038 return null;
3039 }
3040
3041 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003042 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 }
3044
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003045 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 IApplicationThread thread) {
3047
3048 mProcDeaths[0]++;
3049
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003050 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3051 synchronized (stats) {
3052 stats.noteProcessDiedLocked(app.info.uid, pid);
3053 }
3054
Magnus Edlund7bb25812010-02-24 15:45:06 +01003055 // Clean up already done if the process has been re-started.
3056 if (app.pid == pid && app.thread != null &&
3057 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003058 if (!app.killedBackground) {
3059 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3060 + ") has died.");
3061 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003062 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003063 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 TAG, "Dying app: " + app + ", pid: " + pid
3065 + ", thread: " + thread.asBinder());
3066 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003067 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068
3069 if (doLowMem) {
3070 // If there are no longer any background processes running,
3071 // and the app that died was not running instrumentation,
3072 // then tell everyone we are now low on memory.
3073 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003074 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3075 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003076 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077 haveBg = true;
3078 break;
3079 }
3080 }
3081
3082 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003083 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003084 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003085 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3086 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003087 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003088 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3089 // The low memory report is overriding any current
3090 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003091 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003092 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003093 rec.lastRequestedGc = 0;
3094 } else {
3095 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003097 rec.reportLowMemory = true;
3098 rec.lastLowMemory = now;
3099 mProcessesToGc.remove(rec);
3100 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 }
3102 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003103 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003104 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
3106 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003107 } else if (app.pid != pid) {
3108 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003109 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003110 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003111 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003112 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003113 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114 + thread.asBinder());
3115 }
3116 }
3117
Dan Egnor42471dd2010-01-07 17:25:22 -08003118 /**
3119 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003120 * @param clearTraces causes the dump file to be erased prior to the new
3121 * traces being written, if true; when false, the new traces will be
3122 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003123 * @param firstPids of dalvik VM processes to dump stack traces for first
3124 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003125 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003126 * @return file containing stack traces, or null if no dump file is configured
3127 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003128 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003129 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003130 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3131 if (tracesPath == null || tracesPath.length() == 0) {
3132 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003134
3135 File tracesFile = new File(tracesPath);
3136 try {
3137 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003138 if (!tracesDir.exists()) {
3139 tracesFile.mkdirs();
3140 if (!SELinux.restorecon(tracesDir)) {
3141 return null;
3142 }
3143 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003144 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3145
Christopher Tate6ee412d2010-05-28 12:01:56 -07003146 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003147 tracesFile.createNewFile();
3148 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3149 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003150 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003151 return null;
3152 }
3153
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003154 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003155 return tracesFile;
3156 }
3157
3158 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003159 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003160 // Use a FileObserver to detect when traces finish writing.
3161 // The order of traces is considered important to maintain for legibility.
3162 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3163 public synchronized void onEvent(int event, String path) { notify(); }
3164 };
3165
3166 try {
3167 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003168
3169 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003170 if (firstPids != null) {
3171 try {
3172 int num = firstPids.size();
3173 for (int i = 0; i < num; i++) {
3174 synchronized (observer) {
3175 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3176 observer.wait(200); // Wait for write-close, give up after 200msec
3177 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003178 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003179 } catch (InterruptedException e) {
3180 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003181 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003182 }
3183
3184 // Next measure CPU usage.
3185 if (processStats != null) {
3186 processStats.init();
3187 System.gc();
3188 processStats.update();
3189 try {
3190 synchronized (processStats) {
3191 processStats.wait(500); // measure over 1/2 second.
3192 }
3193 } catch (InterruptedException e) {
3194 }
3195 processStats.update();
3196
3197 // We'll take the stack crawls of just the top apps using CPU.
3198 final int N = processStats.countWorkingStats();
3199 int numProcs = 0;
3200 for (int i=0; i<N && numProcs<5; i++) {
3201 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3202 if (lastPids.indexOfKey(stats.pid) >= 0) {
3203 numProcs++;
3204 try {
3205 synchronized (observer) {
3206 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3207 observer.wait(200); // Wait for write-close, give up after 200msec
3208 }
3209 } catch (InterruptedException e) {
3210 Log.wtf(TAG, e);
3211 }
3212
3213 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003214 }
3215 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003216
Dan Egnor42471dd2010-01-07 17:25:22 -08003217 } finally {
3218 observer.stopWatching();
3219 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003220
3221 if (nativeProcs != null) {
3222 int[] pids = Process.getPidsForCommands(nativeProcs);
3223 if (pids != null) {
3224 for (int pid : pids) {
3225 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3226 }
3227 }
3228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 }
3230
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003231 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003232 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003233 return;
3234 }
3235 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3236 if (tracesPath == null || tracesPath.length() == 0) {
3237 return;
3238 }
3239
3240 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3241 StrictMode.allowThreadDiskWrites();
3242 try {
3243 final File tracesFile = new File(tracesPath);
3244 final File tracesDir = tracesFile.getParentFile();
3245 final File tracesTmp = new File(tracesDir, "__tmp__");
3246 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003247 if (!tracesDir.exists()) {
3248 tracesFile.mkdirs();
3249 if (!SELinux.restorecon(tracesDir.getPath())) {
3250 return;
3251 }
3252 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003253 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3254
3255 if (tracesFile.exists()) {
3256 tracesTmp.delete();
3257 tracesFile.renameTo(tracesTmp);
3258 }
3259 StringBuilder sb = new StringBuilder();
3260 Time tobj = new Time();
3261 tobj.set(System.currentTimeMillis());
3262 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3263 sb.append(": ");
3264 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3265 sb.append(" since ");
3266 sb.append(msg);
3267 FileOutputStream fos = new FileOutputStream(tracesFile);
3268 fos.write(sb.toString().getBytes());
3269 if (app == null) {
3270 fos.write("\n*** No application process!".getBytes());
3271 }
3272 fos.close();
3273 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3274 } catch (IOException e) {
3275 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3276 return;
3277 }
3278
3279 if (app != null) {
3280 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3281 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003282 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003283 }
3284
3285 File lastTracesFile = null;
3286 File curTracesFile = null;
3287 for (int i=9; i>=0; i--) {
3288 String name = String.format("slow%02d.txt", i);
3289 curTracesFile = new File(tracesDir, name);
3290 if (curTracesFile.exists()) {
3291 if (lastTracesFile != null) {
3292 curTracesFile.renameTo(lastTracesFile);
3293 } else {
3294 curTracesFile.delete();
3295 }
3296 }
3297 lastTracesFile = curTracesFile;
3298 }
3299 tracesFile.renameTo(curTracesFile);
3300 if (tracesTmp.exists()) {
3301 tracesTmp.renameTo(tracesFile);
3302 }
3303 } finally {
3304 StrictMode.setThreadPolicy(oldPolicy);
3305 }
3306 }
3307
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003308 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003309 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003310 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3311 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3312
Dianne Hackborn287952c2010-09-22 22:34:31 -07003313 if (mController != null) {
3314 try {
3315 // 0 == continue, -1 = kill process immediately
3316 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3317 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3318 } catch (RemoteException e) {
3319 mController = null;
3320 }
3321 }
3322
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003323 long anrTime = SystemClock.uptimeMillis();
3324 if (MONITOR_CPU_USAGE) {
3325 updateCpuStatsNow();
3326 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003327
3328 synchronized (this) {
3329 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3330 if (mShuttingDown) {
3331 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3332 return;
3333 } else if (app.notResponding) {
3334 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3335 return;
3336 } else if (app.crashing) {
3337 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3338 return;
3339 }
3340
3341 // In case we come through here for the same app before completing
3342 // this one, mark as anring now so we will bail out.
3343 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003344
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003345 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003346 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3347 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003348
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003349 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003350 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003351
3352 int parentPid = app.pid;
3353 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003354 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003355
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003356 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003357
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003358 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3359 ProcessRecord r = mLruProcesses.get(i);
3360 if (r != null && r.thread != null) {
3361 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003362 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3363 if (r.persistent) {
3364 firstPids.add(pid);
3365 } else {
3366 lastPids.put(pid, Boolean.TRUE);
3367 }
3368 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
3371 }
3372
Dan Egnor42471dd2010-01-07 17:25:22 -08003373 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003374 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003375 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003376 info.append("ANR in ").append(app.processName);
3377 if (activity != null && activity.shortComponentName != null) {
3378 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003379 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003380 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003382 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003384 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003385 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387
Dianne Hackborn287952c2010-09-22 22:34:31 -07003388 final ProcessStats processStats = new ProcessStats(true);
3389
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003390 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003391
Dan Egnor42471dd2010-01-07 17:25:22 -08003392 String cpuInfo = null;
3393 if (MONITOR_CPU_USAGE) {
3394 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003395 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003396 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003397 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003398 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003399 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003402 info.append(processStats.printCurrentState(anrTime));
3403
Joe Onorato8a9b2202010-02-26 18:56:32 -08003404 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003405 if (tracesFile == null) {
3406 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3407 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3408 }
3409
Jeff Sharkeya353d262011-10-28 11:12:06 -07003410 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3411 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003412
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003413 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003415 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3416 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003418 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3419 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 }
3421 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003422 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 }
3424 }
3425
Dan Egnor42471dd2010-01-07 17:25:22 -08003426 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3427 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3428 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003429
3430 synchronized (this) {
3431 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003432 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003433 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003434 app.processName, app.setAdj, "background ANR");
3435 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003436 return;
3437 }
3438
3439 // Set the app's notResponding state, and look up the errorReportReceiver
3440 makeAppNotRespondingLocked(app,
3441 activity != null ? activity.shortComponentName : null,
3442 annotation != null ? "ANR " + annotation : "ANR",
3443 info.toString());
3444
3445 // Bring up the infamous App Not Responding dialog
3446 Message msg = Message.obtain();
3447 HashMap map = new HashMap();
3448 msg.what = SHOW_NOT_RESPONDING_MSG;
3449 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003450 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003451 map.put("app", app);
3452 if (activity != null) {
3453 map.put("activity", activity);
3454 }
3455
3456 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 }
3459
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003460 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3461 if (!mLaunchWarningShown) {
3462 mLaunchWarningShown = true;
3463 mHandler.post(new Runnable() {
3464 @Override
3465 public void run() {
3466 synchronized (ActivityManagerService.this) {
3467 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3468 d.show();
3469 mHandler.postDelayed(new Runnable() {
3470 @Override
3471 public void run() {
3472 synchronized (ActivityManagerService.this) {
3473 d.dismiss();
3474 mLaunchWarningShown = false;
3475 }
3476 }
3477 }, 4000);
3478 }
3479 }
3480 });
3481 }
3482 }
3483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003484 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003485 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003486 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 int uid = Binder.getCallingUid();
3488 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003489 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003490 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 long callingId = Binder.clearCallingIdentity();
3492 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003493 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 int pkgUid = -1;
3495 synchronized(this) {
3496 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003497 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003498 } catch (RemoteException e) {
3499 }
3500 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003501 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 return false;
3503 }
3504 if (uid == pkgUid || checkComponentPermission(
3505 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003506 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003508 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 } else {
3510 throw new SecurityException(pid+" does not have permission:"+
3511 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3512 "for process:"+packageName);
3513 }
3514 }
3515
3516 try {
3517 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003518 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3520 Uri.fromParts("package", packageName, null));
3521 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003522 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003523 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 } catch (RemoteException e) {
3525 }
3526 } finally {
3527 Binder.restoreCallingIdentity(callingId);
3528 }
3529 return true;
3530 }
3531
Dianne Hackborn1676c852012-09-10 14:52:30 -07003532 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003533 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3534 != PackageManager.PERMISSION_GRANTED &&
3535 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3536 != PackageManager.PERMISSION_GRANTED) {
3537 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 + Binder.getCallingPid()
3539 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003540 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003541 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 throw new SecurityException(msg);
3543 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003544
Dianne Hackborn139748f2012-09-24 11:36:57 -07003545 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003546 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 long callingId = Binder.clearCallingIdentity();
3548 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003549 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003551 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003553 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 } catch (RemoteException e) {
3555 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003556 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003557 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 return;
3559 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003560 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003561 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3562 }
3563 } finally {
3564 Binder.restoreCallingIdentity(callingId);
3565 }
3566 }
3567
3568 public void killAllBackgroundProcesses() {
3569 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3570 != PackageManager.PERMISSION_GRANTED) {
3571 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3572 + Binder.getCallingPid()
3573 + ", uid=" + Binder.getCallingUid()
3574 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3575 Slog.w(TAG, msg);
3576 throw new SecurityException(msg);
3577 }
3578
3579 long callingId = Binder.clearCallingIdentity();
3580 try {
3581 synchronized(this) {
3582 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3583 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3584 final int NA = apps.size();
3585 for (int ia=0; ia<NA; ia++) {
3586 ProcessRecord app = apps.valueAt(ia);
3587 if (app.persistent) {
3588 // we don't kill persistent processes
3589 continue;
3590 }
3591 if (app.removed) {
3592 procs.add(app);
3593 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3594 app.removed = true;
3595 procs.add(app);
3596 }
3597 }
3598 }
3599
3600 int N = procs.size();
3601 for (int i=0; i<N; i++) {
3602 removeProcessLocked(procs.get(i), false, true, "kill all background");
3603 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003604 }
3605 } finally {
3606 Binder.restoreCallingIdentity(callingId);
3607 }
3608 }
3609
Dianne Hackborn1676c852012-09-10 14:52:30 -07003610 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3612 != PackageManager.PERMISSION_GRANTED) {
3613 String msg = "Permission Denial: forceStopPackage() from pid="
3614 + Binder.getCallingPid()
3615 + ", uid=" + Binder.getCallingUid()
3616 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003617 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003618 throw new SecurityException(msg);
3619 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003620 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003621 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003622 long callingId = Binder.clearCallingIdentity();
3623 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003624 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003625 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003626 int[] users = userId == UserHandle.USER_ALL
3627 ? getUsersLocked() : new int[] { userId };
3628 for (int user : users) {
3629 int pkgUid = -1;
3630 try {
3631 pkgUid = pm.getPackageUid(packageName, user);
3632 } catch (RemoteException e) {
3633 }
3634 if (pkgUid == -1) {
3635 Slog.w(TAG, "Invalid packageName: " + packageName);
3636 continue;
3637 }
3638 try {
3639 pm.setPackageStoppedState(packageName, true, user);
3640 } catch (RemoteException e) {
3641 } catch (IllegalArgumentException e) {
3642 Slog.w(TAG, "Failed trying to unstop package "
3643 + packageName + ": " + e);
3644 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003645 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003646 forceStopPackageLocked(packageName, pkgUid);
3647 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 }
3650 } finally {
3651 Binder.restoreCallingIdentity(callingId);
3652 }
3653 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003654
3655 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003656 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003657 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003658 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003659 if (pkg == null) {
3660 return;
3661 }
3662 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003663 if (appid < 0) {
3664 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003665 return;
3666 }
3667 int callerUid = Binder.getCallingUid();
3668 // Only the system server can kill an application
3669 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003670 // Post an aysnc message to kill the application
3671 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003672 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003673 msg.arg2 = 0;
3674 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003675 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003676 } else {
3677 throw new SecurityException(callerUid + " cannot kill pkg: " +
3678 pkg);
3679 }
3680 }
3681
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003682 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003683 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003684
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003685 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003686 final int uid = Binder.getCallingUid();
3687 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003688 try {
3689 synchronized (this) {
3690 // Only allow this from foreground processes, so that background
3691 // applications can't abuse it to prevent system UI from being shown.
3692 if (uid >= Process.FIRST_APPLICATION_UID) {
3693 ProcessRecord proc;
3694 synchronized (mPidsSelfLocked) {
3695 proc = mPidsSelfLocked.get(pid);
3696 }
3697 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3698 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3699 + " from background process " + proc);
3700 return;
3701 }
3702 }
3703 closeSystemDialogsLocked(reason);
3704 }
3705 } finally {
3706 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003707 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003708 }
3709
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003710 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003711 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3713 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003714 if (reason != null) {
3715 intent.putExtra("reason", reason);
3716 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003717 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003718
Dianne Hackborne302a162012-05-15 14:58:32 -07003719 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3720 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003721 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003722 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003723 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003724 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003725 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003726
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003727 broadcastIntentLocked(null, null, intent, null,
3728 null, 0, null, null, null, false, false, -1,
3729 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003730 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003731
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003732 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003733 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003734 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003735 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3736 for (int i=pids.length-1; i>=0; i--) {
3737 infos[i] = new Debug.MemoryInfo();
3738 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003739 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003740 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003741 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003742
Dianne Hackbornb437e092011-08-05 17:50:29 -07003743 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003744 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003745 long[] pss = new long[pids.length];
3746 for (int i=pids.length-1; i>=0; i--) {
3747 pss[i] = Debug.getPss(pids[i]);
3748 }
3749 return pss;
3750 }
3751
Christopher Tate5e1ab332009-09-01 20:32:49 -07003752 public void killApplicationProcess(String processName, int uid) {
3753 if (processName == null) {
3754 return;
3755 }
3756
3757 int callerUid = Binder.getCallingUid();
3758 // Only the system server can kill an application
3759 if (callerUid == Process.SYSTEM_UID) {
3760 synchronized (this) {
3761 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003762 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003763 try {
3764 app.thread.scheduleSuicide();
3765 } catch (RemoteException e) {
3766 // If the other end already died, then our work here is done.
3767 }
3768 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003769 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003770 + processName + " / " + uid);
3771 }
3772 }
3773 } else {
3774 throw new SecurityException(callerUid + " cannot kill app process: " +
3775 processName);
3776 }
3777 }
3778
Dianne Hackborn03abb812010-01-04 18:43:19 -08003779 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003780 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3781 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3783 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003784 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003785 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3786 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003789 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 broadcastIntentLocked(null, null, intent,
3791 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003792 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003793 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003795
3796 private void forceStopUserLocked(int userId) {
3797 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3798 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003799 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3800 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003801 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3802 broadcastIntentLocked(null, null, intent,
3803 null, null, 0, null, null, null,
3804 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003805 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003806 }
3807
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003808 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003809 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3810 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003811 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812
Dianne Hackborn03abb812010-01-04 18:43:19 -08003813 // Remove all processes this package may have touched: all with the
3814 // same UID (except for the system or root user), and all whose name
3815 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003816 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003817 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3818 final int NA = apps.size();
3819 for (int ia=0; ia<NA; ia++) {
3820 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003821 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003822 // we don't kill persistent processes
3823 continue;
3824 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003825 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003826 if (doit) {
3827 procs.add(app);
3828 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003829 continue;
3830 }
3831
3832 // Skip process if it doesn't meet our oom adj requirement.
3833 if (app.setAdj < minOomAdj) {
3834 continue;
3835 }
3836
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003837 // If no package is specified, we call all processes under the
3838 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003839 if (packageName == null) {
3840 if (app.userId != userId) {
3841 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003842 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003843 // Package has been specified, we want to hit all processes
3844 // that match it. We need to qualify this by the processes
3845 // that are running under the specified app and user ID.
3846 } else {
3847 if (UserHandle.getAppId(app.uid) != appId) {
3848 continue;
3849 }
3850 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3851 continue;
3852 }
3853 if (!app.pkgList.contains(packageName)) {
3854 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003855 }
3856 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003857
3858 // Process has passed all conditions, kill it!
3859 if (!doit) {
3860 return true;
3861 }
3862 app.removed = true;
3863 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003864 }
3865 }
3866
3867 int N = procs.size();
3868 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003869 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003870 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003871 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003872 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003873
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003874 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003875 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003876 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003877 int i;
3878 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003880 if (userId == UserHandle.USER_ALL && name == null) {
3881 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3882 }
3883
3884 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003886 appId = UserHandle.getAppId(
3887 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } catch (RemoteException e) {
3889 }
3890 }
3891
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003892 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003893 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003894 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3895 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003896 } else {
3897 Slog.i(TAG, "Force stopping user " + userId);
3898 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003899
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003900 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3901 while (badApps.hasNext()) {
3902 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003903 for (i=ba.size()-1; i>=0; i--) {
3904 boolean remove = false;
3905 final int entUid = ba.keyAt(i);
3906 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003907 if (userId == UserHandle.USER_ALL) {
3908 if (UserHandle.getAppId(entUid) == appId) {
3909 remove = true;
3910 }
3911 } else {
3912 if (entUid == UserHandle.getUid(userId, appId)) {
3913 remove = true;
3914 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003915 }
3916 } else if (UserHandle.getUserId(entUid) == userId) {
3917 remove = true;
3918 }
3919 if (remove) {
3920 ba.removeAt(i);
3921 }
3922 }
3923 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003924 badApps.remove();
3925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 }
3927 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003928
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003929 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003930 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003931 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003933 TaskRecord lastTask = null;
3934 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003935 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003936 final boolean samePackage = r.packageName.equals(name)
3937 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003938 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003939 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003940 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003941 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003942 if (r.finishing) {
3943 // If this activity is just finishing, then it is not
3944 // interesting as far as something to stop.
3945 continue;
3946 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003947 return true;
3948 }
3949 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003950 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003951 if (samePackage) {
3952 if (r.app != null) {
3953 r.app.removed = true;
3954 }
3955 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003957 lastTask = r.task;
3958 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003959 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003960 i--;
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 }
3963 }
3964
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003965 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3966 if (!doit) {
3967 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003969 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003971
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003972 if (name == null) {
3973 // Remove all sticky broadcasts from this user.
3974 mStickyBroadcasts.remove(userId);
3975 }
3976
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003977 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003978 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3979 userId, providers)) {
3980 if (!doit) {
3981 return true;
3982 }
3983 didSomething = true;
3984 }
3985 N = providers.size();
3986 for (i=0; i<N; i++) {
3987 removeDyingProviderLocked(null, providers.get(i), true);
3988 }
3989
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003990 if (name == null) {
3991 // Remove pending intents. For now we only do this when force
3992 // stopping users, because we have some problems when doing this
3993 // for packages -- app widgets are not currently cleaned up for
3994 // such packages, so they can be left with bad pending intents.
3995 if (mIntentSenderRecords.size() > 0) {
3996 Iterator<WeakReference<PendingIntentRecord>> it
3997 = mIntentSenderRecords.values().iterator();
3998 while (it.hasNext()) {
3999 WeakReference<PendingIntentRecord> wpir = it.next();
4000 if (wpir == null) {
4001 it.remove();
4002 continue;
4003 }
4004 PendingIntentRecord pir = wpir.get();
4005 if (pir == null) {
4006 it.remove();
4007 continue;
4008 }
4009 if (name == null) {
4010 // Stopping user, remove all objects for the user.
4011 if (pir.key.userId != userId) {
4012 // Not the same user, skip it.
4013 continue;
4014 }
4015 } else {
4016 if (UserHandle.getAppId(pir.uid) != appId) {
4017 // Different app id, skip it.
4018 continue;
4019 }
4020 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
4021 // Different user, skip it.
4022 continue;
4023 }
4024 if (!pir.key.packageName.equals(name)) {
4025 // Different package, skip it.
4026 continue;
4027 }
4028 }
4029 if (!doit) {
4030 return true;
4031 }
4032 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004033 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004034 pir.canceled = true;
4035 if (pir.key.activity != null) {
4036 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004037 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004038 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004039 }
4040 }
4041
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004042 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004043 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004044 AttributeCache ac = AttributeCache.instance();
4045 if (ac != null) {
4046 ac.removePackage(name);
4047 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004048 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004049 if (mBooted) {
4050 mMainStack.resumeTopActivityLocked(null);
4051 mMainStack.scheduleIdleLocked();
4052 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004053 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004054
4055 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 }
4057
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004058 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004059 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004061 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004062 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004063 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 + "/" + uid + ")");
4065
4066 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004067 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004068 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004069 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4070 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004071 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 boolean needRestart = false;
4074 if (app.pid > 0 && app.pid != MY_PID) {
4075 int pid = app.pid;
4076 synchronized (mPidsSelfLocked) {
4077 mPidsSelfLocked.remove(pid);
4078 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4079 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004080 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004081 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004082 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004083 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004085 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004087 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 } else {
4089 needRestart = true;
4090 }
4091 }
4092 } else {
4093 mRemovedProcesses.add(app);
4094 }
4095
4096 return needRestart;
4097 }
4098
4099 private final void processStartTimedOutLocked(ProcessRecord app) {
4100 final int pid = app.pid;
4101 boolean gone = false;
4102 synchronized (mPidsSelfLocked) {
4103 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4104 if (knownApp != null && knownApp.thread == null) {
4105 mPidsSelfLocked.remove(pid);
4106 gone = true;
4107 }
4108 }
4109
4110 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004111 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004112 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4113 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004114 mProcessNames.remove(app.processName, app.uid);
4115 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004116 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004117 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4118 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004119 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004120 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004121 // Take care of any launching providers waiting for this process.
4122 checkAppInLaunchingProvidersLocked(app, true);
4123 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004124 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004125 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004126 app.processName, app.setAdj, "start timeout");
4127 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004128 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004129 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004130 try {
4131 IBackupManager bm = IBackupManager.Stub.asInterface(
4132 ServiceManager.getService(Context.BACKUP_SERVICE));
4133 bm.agentDisconnected(app.info.packageName);
4134 } catch (RemoteException e) {
4135 // Can't happen; the backup manager is local
4136 }
4137 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004138 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004139 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004140 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004143 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 }
4145 }
4146
4147 private final boolean attachApplicationLocked(IApplicationThread thread,
4148 int pid) {
4149
4150 // Find the application record that is being attached... either via
4151 // the pid if we are running in multiple processes, or just pull the
4152 // next app record if we are emulating process with anonymous threads.
4153 ProcessRecord app;
4154 if (pid != MY_PID && pid >= 0) {
4155 synchronized (mPidsSelfLocked) {
4156 app = mPidsSelfLocked.get(pid);
4157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 } else {
4159 app = null;
4160 }
4161
4162 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004163 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004165 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004167 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 } else {
4169 try {
4170 thread.scheduleExit();
4171 } catch (Exception e) {
4172 // Ignore exceptions.
4173 }
4174 }
4175 return false;
4176 }
4177
4178 // If this application record is still attached to a previous
4179 // process, clean it up now.
4180 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004181 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 }
4183
4184 // Tell the process all about itself.
4185
Joe Onorato8a9b2202010-02-26 18:56:32 -08004186 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 TAG, "Binding process pid " + pid + " to record " + app);
4188
4189 String processName = app.processName;
4190 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004191 AppDeathRecipient adr = new AppDeathRecipient(
4192 app, pid, thread);
4193 thread.asBinder().linkToDeath(adr, 0);
4194 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 } catch (RemoteException e) {
4196 app.resetPackageList();
4197 startProcessLocked(app, "link fail", processName);
4198 return false;
4199 }
4200
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004201 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202
4203 app.thread = thread;
4204 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004205 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4206 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 app.forcingToForeground = null;
4208 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004209 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 app.debugging = false;
4211
4212 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4213
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004214 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004217 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004218 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004219 }
4220
Joe Onorato8a9b2202010-02-26 18:56:32 -08004221 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 TAG, "New app record " + app
4223 + " thread=" + thread.asBinder() + " pid=" + pid);
4224 try {
4225 int testMode = IApplicationThread.DEBUG_OFF;
4226 if (mDebugApp != null && mDebugApp.equals(processName)) {
4227 testMode = mWaitForDebugger
4228 ? IApplicationThread.DEBUG_WAIT
4229 : IApplicationThread.DEBUG_ON;
4230 app.debugging = true;
4231 if (mDebugTransient) {
4232 mDebugApp = mOrigDebugApp;
4233 mWaitForDebugger = mOrigWaitForDebugger;
4234 }
4235 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004236 String profileFile = app.instrumentationProfileFile;
4237 ParcelFileDescriptor profileFd = null;
4238 boolean profileAutoStop = false;
4239 if (mProfileApp != null && mProfileApp.equals(processName)) {
4240 mProfileProc = app;
4241 profileFile = mProfileFile;
4242 profileFd = mProfileFd;
4243 profileAutoStop = mAutoStopProfiler;
4244 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004245 boolean enableOpenGlTrace = false;
4246 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4247 enableOpenGlTrace = true;
4248 mOpenGlTraceApp = null;
4249 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004250
Christopher Tate181fafa2009-05-14 11:12:14 -07004251 // If the app is being launched for restore or full backup, set it up specially
4252 boolean isRestrictedBackupMode = false;
4253 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4254 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004255 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004256 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4257 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004258
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004259 ensurePackageDexOpt(app.instrumentationInfo != null
4260 ? app.instrumentationInfo.packageName
4261 : app.info.packageName);
4262 if (app.instrumentationClass != null) {
4263 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004264 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004265 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004266 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004267 ApplicationInfo appInfo = app.instrumentationInfo != null
4268 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004269 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004270 if (profileFd != null) {
4271 profileFd = profileFd.dup();
4272 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004273 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004274 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08004275 app.instrumentationArguments, app.instrumentationWatcher,
4276 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
4277 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004278 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004279 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004280 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004281 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004282 } catch (Exception e) {
4283 // todo: Yikes! What should we do? For now we will try to
4284 // start another process, but that could easily get us in
4285 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004286 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287
4288 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004289 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 startProcessLocked(app, "bind fail", processName);
4291 return false;
4292 }
4293
4294 // Remove this record from the list of starting applications.
4295 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004296 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4297 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004298 mProcessesOnHold.remove(app);
4299
4300 boolean badApp = false;
4301 boolean didSomething = false;
4302
4303 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004304 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004305 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004306 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 && processName.equals(hr.processName)) {
4308 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004309 if (mHeadless) {
4310 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4311 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 didSomething = true;
4313 }
4314 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004315 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 + hr.intent.getComponent().flattenToShortString(), e);
4317 badApp = true;
4318 }
4319 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004320 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 }
4322 }
4323
4324 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004325 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004327 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 badApp = true;
4330 }
4331 }
4332
Christopher Tatef46723b2012-01-26 14:19:24 -08004333 // Check if a next-broadcast receiver is in this process...
4334 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004336 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004338 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 }
4341 }
4342
Christopher Tate181fafa2009-05-14 11:12:14 -07004343 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004344 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004345 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004346 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004347 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004348 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4349 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4350 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004351 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004352 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004353 e.printStackTrace();
4354 }
4355 }
4356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 if (badApp) {
4358 // todo: Also need to kill application to deal with all
4359 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004360 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 return false;
4362 }
4363
4364 if (!didSomething) {
4365 updateOomAdjLocked();
4366 }
4367
4368 return true;
4369 }
4370
4371 public final void attachApplication(IApplicationThread thread) {
4372 synchronized (this) {
4373 int callingPid = Binder.getCallingPid();
4374 final long origId = Binder.clearCallingIdentity();
4375 attachApplicationLocked(thread, callingPid);
4376 Binder.restoreCallingIdentity(origId);
4377 }
4378 }
4379
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004380 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004382 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4383 if (stopProfiling) {
4384 synchronized (this) {
4385 if (mProfileProc == r.app) {
4386 if (mProfileFd != null) {
4387 try {
4388 mProfileFd.close();
4389 } catch (IOException e) {
4390 }
4391 clearProfilerLocked();
4392 }
4393 }
4394 }
4395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 Binder.restoreCallingIdentity(origId);
4397 }
4398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004400 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004401 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004403
4404 synchronized (this) {
4405 updateEventDispatchingLocked();
4406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 }
4408
Dianne Hackborn661cd522011-08-22 00:26:20 -07004409 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004410 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004411 mWindowManager.showBootMessage(msg, always);
4412 }
4413
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004414 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004415 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004416 final long token = Binder.clearCallingIdentity();
4417 try {
4418 synchronized (this) {
4419 if (mLockScreenShown) {
4420 mLockScreenShown = false;
4421 comeOutOfSleepIfNeededLocked();
4422 }
4423 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004424 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004425 } finally {
4426 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004427 }
4428 }
4429
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004430 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004431 IntentFilter pkgFilter = new IntentFilter();
4432 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4433 pkgFilter.addDataScheme("package");
4434 mContext.registerReceiver(new BroadcastReceiver() {
4435 @Override
4436 public void onReceive(Context context, Intent intent) {
4437 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4438 if (pkgs != null) {
4439 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004440 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004441 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4442 setResultCode(Activity.RESULT_OK);
4443 return;
4444 }
4445 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004446 }
4447 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004448 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004449 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004450
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004451 synchronized (this) {
4452 // Ensure that any processes we had put on hold are now started
4453 // up.
4454 final int NP = mProcessesOnHold.size();
4455 if (NP > 0) {
4456 ArrayList<ProcessRecord> procs =
4457 new ArrayList<ProcessRecord>(mProcessesOnHold);
4458 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004459 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4460 + procs.get(ip));
4461 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004462 }
4463 }
4464
4465 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004466 // Start looking for apps that are abusing wake locks.
4467 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004468 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004469 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004470 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004471 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004472 for (int i=0; i<mStartedUsers.size(); i++) {
4473 UserStartedState uss = mStartedUsers.valueAt(i);
4474 if (uss.mState == UserStartedState.STATE_BOOTING) {
4475 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004476 final int userId = mStartedUsers.keyAt(i);
4477 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4478 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4479 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004480 null, null, 0, null, null,
4481 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004482 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004483 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004484 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004485 }
4486 }
4487 }
4488
4489 final void ensureBootCompleted() {
4490 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004491 boolean enableScreen;
4492 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004493 booting = mBooting;
4494 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004495 enableScreen = !mBooted;
4496 mBooted = true;
4497 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004498
4499 if (booting) {
4500 finishBooting();
4501 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004502
4503 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004504 enableScreenAfterBoot();
4505 }
4506 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004507
4508 public final void activityResumed(IBinder token) {
4509 final long origId = Binder.clearCallingIdentity();
4510 mMainStack.activityResumed(token);
4511 Binder.restoreCallingIdentity(origId);
4512 }
4513
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004514 public final void activityPaused(IBinder token) {
4515 final long origId = Binder.clearCallingIdentity();
4516 mMainStack.activityPaused(token, false);
4517 Binder.restoreCallingIdentity(origId);
4518 }
4519
4520 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4521 CharSequence description) {
4522 if (localLOGV) Slog.v(
4523 TAG, "Activity stopped: token=" + token);
4524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 // Refuse possible leaked file descriptors
4526 if (icicle != null && icicle.hasFileDescriptors()) {
4527 throw new IllegalArgumentException("File descriptors passed in Bundle");
4528 }
4529
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004530 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531
4532 final long origId = Binder.clearCallingIdentity();
4533
4534 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004535 r = mMainStack.isInStackLocked(token);
4536 if (r != null) {
4537 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 }
4539 }
4540
4541 if (r != null) {
4542 sendPendingThumbnail(r, null, null, null, false);
4543 }
4544
4545 trimApplications();
4546
4547 Binder.restoreCallingIdentity(origId);
4548 }
4549
4550 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004551 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004552 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 }
4554
4555 public String getCallingPackage(IBinder token) {
4556 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004557 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004558 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 }
4560 }
4561
4562 public ComponentName getCallingActivity(IBinder token) {
4563 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004564 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 return r != null ? r.intent.getComponent() : null;
4566 }
4567 }
4568
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004569 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004570 ActivityRecord r = mMainStack.isInStackLocked(token);
4571 if (r == null) {
4572 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004573 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004574 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
4576
4577 public ComponentName getActivityClassForToken(IBinder token) {
4578 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004579 ActivityRecord r = mMainStack.isInStackLocked(token);
4580 if (r == null) {
4581 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004582 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004583 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
4585 }
4586
4587 public String getPackageForToken(IBinder token) {
4588 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004589 ActivityRecord r = mMainStack.isInStackLocked(token);
4590 if (r == null) {
4591 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004592 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004593 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
4595 }
4596
4597 public IIntentSender getIntentSender(int type,
4598 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004599 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004600 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004601 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004603 if (intents != null) {
4604 if (intents.length < 1) {
4605 throw new IllegalArgumentException("Intents array length must be >= 1");
4606 }
4607 for (int i=0; i<intents.length; i++) {
4608 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004609 if (intent != null) {
4610 if (intent.hasFileDescriptors()) {
4611 throw new IllegalArgumentException("File descriptors passed in Intent");
4612 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004613 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004614 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4615 throw new IllegalArgumentException(
4616 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4617 }
4618 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004619 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004620 }
4621 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004622 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004623 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004624 }
4625 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004626 if (options != null) {
4627 if (options.hasFileDescriptors()) {
4628 throw new IllegalArgumentException("File descriptors passed in options");
4629 }
4630 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 synchronized(this) {
4633 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004634 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004635 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004636 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004637 "getIntentSender", null);
4638 if (origUserId == UserHandle.USER_CURRENT) {
4639 // We don't want to evaluate this until the pending intent is
4640 // actually executed. However, we do want to always do the
4641 // security checking for it above.
4642 userId = UserHandle.USER_CURRENT;
4643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004645 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004646 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004647 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4648 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 String msg = "Permission Denial: getIntentSender() from pid="
4650 + Binder.getCallingPid()
4651 + ", uid=" + Binder.getCallingUid()
4652 + ", (need uid=" + uid + ")"
4653 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004654 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004655 throw new SecurityException(msg);
4656 }
4657 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004658
4659 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004660 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004662 } catch (RemoteException e) {
4663 throw new SecurityException(e);
4664 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004665 }
4666 }
4667
Dianne Hackborn41203752012-08-31 14:05:51 -07004668 IIntentSender getIntentSenderLocked(int type, String packageName,
4669 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004670 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4671 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004672 if (DEBUG_MU)
4673 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004674 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004675 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004676 activity = mMainStack.isInStackLocked(token);
4677 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004678 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004679 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004680 if (activity.finishing) {
4681 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004683 }
4684
4685 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4686 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4687 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4688 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4689 |PendingIntent.FLAG_UPDATE_CURRENT);
4690
4691 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4692 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004693 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004694 WeakReference<PendingIntentRecord> ref;
4695 ref = mIntentSenderRecords.get(key);
4696 PendingIntentRecord rec = ref != null ? ref.get() : null;
4697 if (rec != null) {
4698 if (!cancelCurrent) {
4699 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004700 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004701 rec.key.requestIntent.replaceExtras(intents != null ?
4702 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004703 }
4704 if (intents != null) {
4705 intents[intents.length-1] = rec.key.requestIntent;
4706 rec.key.allIntents = intents;
4707 rec.key.allResolvedTypes = resolvedTypes;
4708 } else {
4709 rec.key.allIntents = null;
4710 rec.key.allResolvedTypes = null;
4711 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 return rec;
4714 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004715 rec.canceled = true;
4716 mIntentSenderRecords.remove(key);
4717 }
4718 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004719 return rec;
4720 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004721 rec = new PendingIntentRecord(this, key, callingUid);
4722 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004723 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004724 if (activity.pendingResults == null) {
4725 activity.pendingResults
4726 = new HashSet<WeakReference<PendingIntentRecord>>();
4727 }
4728 activity.pendingResults.add(rec.ref);
4729 }
4730 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 }
4732
4733 public void cancelIntentSender(IIntentSender sender) {
4734 if (!(sender instanceof PendingIntentRecord)) {
4735 return;
4736 }
4737 synchronized(this) {
4738 PendingIntentRecord rec = (PendingIntentRecord)sender;
4739 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004740 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004741 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4742 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 String msg = "Permission Denial: cancelIntentSender() from pid="
4744 + Binder.getCallingPid()
4745 + ", uid=" + Binder.getCallingUid()
4746 + " is not allowed to cancel packges "
4747 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004748 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749 throw new SecurityException(msg);
4750 }
4751 } catch (RemoteException e) {
4752 throw new SecurityException(e);
4753 }
4754 cancelIntentSenderLocked(rec, true);
4755 }
4756 }
4757
4758 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4759 rec.canceled = true;
4760 mIntentSenderRecords.remove(rec.key);
4761 if (cleanActivity && rec.key.activity != null) {
4762 rec.key.activity.pendingResults.remove(rec.ref);
4763 }
4764 }
4765
4766 public String getPackageForIntentSender(IIntentSender pendingResult) {
4767 if (!(pendingResult instanceof PendingIntentRecord)) {
4768 return null;
4769 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004770 try {
4771 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4772 return res.key.packageName;
4773 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 }
4775 return null;
4776 }
4777
Christopher Tatec4a07d12012-04-06 14:19:13 -07004778 public int getUidForIntentSender(IIntentSender sender) {
4779 if (sender instanceof PendingIntentRecord) {
4780 try {
4781 PendingIntentRecord res = (PendingIntentRecord)sender;
4782 return res.uid;
4783 } catch (ClassCastException e) {
4784 }
4785 }
4786 return -1;
4787 }
4788
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004789 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4790 if (!(pendingResult instanceof PendingIntentRecord)) {
4791 return false;
4792 }
4793 try {
4794 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4795 if (res.key.allIntents == null) {
4796 return false;
4797 }
4798 for (int i=0; i<res.key.allIntents.length; i++) {
4799 Intent intent = res.key.allIntents[i];
4800 if (intent.getPackage() != null && intent.getComponent() != null) {
4801 return false;
4802 }
4803 }
4804 return true;
4805 } catch (ClassCastException e) {
4806 }
4807 return false;
4808 }
4809
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004810 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4811 if (!(pendingResult instanceof PendingIntentRecord)) {
4812 return false;
4813 }
4814 try {
4815 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4816 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4817 return true;
4818 }
4819 return false;
4820 } catch (ClassCastException e) {
4821 }
4822 return false;
4823 }
4824
Dianne Hackborn81038902012-11-26 17:04:09 -08004825 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4826 if (!(pendingResult instanceof PendingIntentRecord)) {
4827 return null;
4828 }
4829 try {
4830 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4831 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4832 } catch (ClassCastException e) {
4833 }
4834 return null;
4835 }
4836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 public void setProcessLimit(int max) {
4838 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4839 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004840 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004841 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004842 mProcessLimitOverride = max;
4843 }
4844 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 }
4846
4847 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004848 synchronized (this) {
4849 return mProcessLimitOverride;
4850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 }
4852
4853 void foregroundTokenDied(ForegroundToken token) {
4854 synchronized (ActivityManagerService.this) {
4855 synchronized (mPidsSelfLocked) {
4856 ForegroundToken cur
4857 = mForegroundProcesses.get(token.pid);
4858 if (cur != token) {
4859 return;
4860 }
4861 mForegroundProcesses.remove(token.pid);
4862 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4863 if (pr == null) {
4864 return;
4865 }
4866 pr.forcingToForeground = null;
4867 pr.foregroundServices = false;
4868 }
4869 updateOomAdjLocked();
4870 }
4871 }
4872
4873 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4874 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4875 "setProcessForeground()");
4876 synchronized(this) {
4877 boolean changed = false;
4878
4879 synchronized (mPidsSelfLocked) {
4880 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004881 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004882 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 return;
4884 }
4885 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4886 if (oldToken != null) {
4887 oldToken.token.unlinkToDeath(oldToken, 0);
4888 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004889 if (pr != null) {
4890 pr.forcingToForeground = null;
4891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 changed = true;
4893 }
4894 if (isForeground && token != null) {
4895 ForegroundToken newToken = new ForegroundToken() {
4896 public void binderDied() {
4897 foregroundTokenDied(this);
4898 }
4899 };
4900 newToken.pid = pid;
4901 newToken.token = token;
4902 try {
4903 token.linkToDeath(newToken, 0);
4904 mForegroundProcesses.put(pid, newToken);
4905 pr.forcingToForeground = token;
4906 changed = true;
4907 } catch (RemoteException e) {
4908 // If the process died while doing this, we will later
4909 // do the cleanup with the process death link.
4910 }
4911 }
4912 }
4913
4914 if (changed) {
4915 updateOomAdjLocked();
4916 }
4917 }
4918 }
4919
4920 // =========================================================
4921 // PERMISSIONS
4922 // =========================================================
4923
4924 static class PermissionController extends IPermissionController.Stub {
4925 ActivityManagerService mActivityManagerService;
4926 PermissionController(ActivityManagerService activityManagerService) {
4927 mActivityManagerService = activityManagerService;
4928 }
4929
4930 public boolean checkPermission(String permission, int pid, int uid) {
4931 return mActivityManagerService.checkPermission(permission, pid,
4932 uid) == PackageManager.PERMISSION_GRANTED;
4933 }
4934 }
4935
4936 /**
4937 * This can be called with or without the global lock held.
4938 */
4939 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004940 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 // We might be performing an operation on behalf of an indirect binder
4942 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4943 // client identity accordingly before proceeding.
4944 Identity tlsIdentity = sCallerIdentity.get();
4945 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004946 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004947 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4948 uid = tlsIdentity.uid;
4949 pid = tlsIdentity.pid;
4950 }
4951
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004952 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004953 return PackageManager.PERMISSION_GRANTED;
4954 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004955
4956 return ActivityManager.checkComponentPermission(permission, uid,
4957 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004958 }
4959
4960 /**
4961 * As the only public entry point for permissions checking, this method
4962 * can enforce the semantic that requesting a check on a null global
4963 * permission is automatically denied. (Internally a null permission
4964 * string is used when calling {@link #checkComponentPermission} in cases
4965 * when only uid-based security is needed.)
4966 *
4967 * This can be called with or without the global lock held.
4968 */
4969 public int checkPermission(String permission, int pid, int uid) {
4970 if (permission == null) {
4971 return PackageManager.PERMISSION_DENIED;
4972 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004973 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 }
4975
4976 /**
4977 * Binder IPC calls go through the public entry point.
4978 * This can be called with or without the global lock held.
4979 */
4980 int checkCallingPermission(String permission) {
4981 return checkPermission(permission,
4982 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004983 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 }
4985
4986 /**
4987 * This can be called with or without the global lock held.
4988 */
4989 void enforceCallingPermission(String permission, String func) {
4990 if (checkCallingPermission(permission)
4991 == PackageManager.PERMISSION_GRANTED) {
4992 return;
4993 }
4994
4995 String msg = "Permission Denial: " + func + " from pid="
4996 + Binder.getCallingPid()
4997 + ", uid=" + Binder.getCallingUid()
4998 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004999 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 throw new SecurityException(msg);
5001 }
5002
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005003 /**
5004 * Determine if UID is holding permissions required to access {@link Uri} in
5005 * the given {@link ProviderInfo}. Final permission checking is always done
5006 * in {@link ContentProvider}.
5007 */
5008 private final boolean checkHoldingPermissionsLocked(
5009 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005010 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5011 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005012
5013 if (pi.applicationInfo.uid == uid) {
5014 return true;
5015 } else if (!pi.exported) {
5016 return false;
5017 }
5018
5019 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5020 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005022 // check if target holds top-level <provider> permissions
5023 if (!readMet && pi.readPermission != null
5024 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5025 readMet = true;
5026 }
5027 if (!writeMet && pi.writePermission != null
5028 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5029 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005031
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005032 // track if unprotected read/write is allowed; any denied
5033 // <path-permission> below removes this ability
5034 boolean allowDefaultRead = pi.readPermission == null;
5035 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005036
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005037 // check if target holds any <path-permission> that match uri
5038 final PathPermission[] pps = pi.pathPermissions;
5039 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005040 final String path = uri.getPath();
5041 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005042 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005043 i--;
5044 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005045 if (pp.match(path)) {
5046 if (!readMet) {
5047 final String pprperm = pp.getReadPermission();
5048 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5049 + pprperm + " for " + pp.getPath()
5050 + ": match=" + pp.match(path)
5051 + " check=" + pm.checkUidPermission(pprperm, uid));
5052 if (pprperm != null) {
5053 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5054 readMet = true;
5055 } else {
5056 allowDefaultRead = false;
5057 }
5058 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005059 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005060 if (!writeMet) {
5061 final String ppwperm = pp.getWritePermission();
5062 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5063 + ppwperm + " for " + pp.getPath()
5064 + ": match=" + pp.match(path)
5065 + " check=" + pm.checkUidPermission(ppwperm, uid));
5066 if (ppwperm != null) {
5067 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5068 writeMet = true;
5069 } else {
5070 allowDefaultWrite = false;
5071 }
5072 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005073 }
5074 }
5075 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005076 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005077
5078 // grant unprotected <provider> read/write, if not blocked by
5079 // <path-permission> above
5080 if (allowDefaultRead) readMet = true;
5081 if (allowDefaultWrite) writeMet = true;
5082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 } catch (RemoteException e) {
5084 return false;
5085 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005086
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005087 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005088 }
5089
5090 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5091 int modeFlags) {
5092 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005093 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 return true;
5095 }
5096 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5097 if (perms == null) return false;
5098 UriPermission perm = perms.get(uri);
5099 if (perm == null) return false;
5100 return (modeFlags&perm.modeFlags) == modeFlags;
5101 }
5102
5103 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005104 enforceNotIsolatedCaller("checkUriPermission");
5105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 // Another redirected-binder-call permissions check as in
5107 // {@link checkComponentPermission}.
5108 Identity tlsIdentity = sCallerIdentity.get();
5109 if (tlsIdentity != null) {
5110 uid = tlsIdentity.uid;
5111 pid = tlsIdentity.pid;
5112 }
5113
5114 // Our own process gets to do everything.
5115 if (pid == MY_PID) {
5116 return PackageManager.PERMISSION_GRANTED;
5117 }
5118 synchronized(this) {
5119 return checkUriPermissionLocked(uri, uid, modeFlags)
5120 ? PackageManager.PERMISSION_GRANTED
5121 : PackageManager.PERMISSION_DENIED;
5122 }
5123 }
5124
Dianne Hackborn39792d22010-08-19 18:01:52 -07005125 /**
5126 * Check if the targetPkg can be granted permission to access uri by
5127 * the callingUid using the given modeFlags. Throws a security exception
5128 * if callingUid is not allowed to do this. Returns the uid of the target
5129 * if the URI permission grant should be performed; returns -1 if it is not
5130 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005131 * If you already know the uid of the target, you can supply it in
5132 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005133 */
5134 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005135 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5137 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5138 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005139 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 }
5141
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005142 if (targetPkg != null) {
5143 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5144 "Checking grant " + targetPkg + " permission to " + uri);
5145 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005146
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005147 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148
5149 // If this is not a content: uri, we can't do anything with it.
5150 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005151 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005152 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005153 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 }
5155
5156 String name = uri.getAuthority();
5157 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005158 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005159 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 if (cpr != null) {
5161 pi = cpr.info;
5162 } else {
5163 try {
5164 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005165 PackageManager.GET_URI_PERMISSION_PATTERNS,
5166 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005167 } catch (RemoteException ex) {
5168 }
5169 }
5170 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005171 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005172 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 }
5174
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005175 int targetUid = lastTargetUid;
5176 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005177 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005178 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005179 if (targetUid < 0) {
5180 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5181 "Can't grant URI permission no uid for: " + targetPkg);
5182 return -1;
5183 }
5184 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005185 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 }
5188
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005189 if (targetUid >= 0) {
5190 // First... does the target actually need this permission?
5191 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5192 // No need to grant the target this permission.
5193 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5194 "Target " + targetPkg + " already has full permission to " + uri);
5195 return -1;
5196 }
5197 } else {
5198 // First... there is no target package, so can anyone access it?
5199 boolean allowed = pi.exported;
5200 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5201 if (pi.readPermission != null) {
5202 allowed = false;
5203 }
5204 }
5205 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5206 if (pi.writePermission != null) {
5207 allowed = false;
5208 }
5209 }
5210 if (allowed) {
5211 return -1;
5212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 }
5214
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005215 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005216 if (!pi.grantUriPermissions) {
5217 throw new SecurityException("Provider " + pi.packageName
5218 + "/" + pi.name
5219 + " does not allow granting of Uri permissions (uri "
5220 + uri + ")");
5221 }
5222 if (pi.uriPermissionPatterns != null) {
5223 final int N = pi.uriPermissionPatterns.length;
5224 boolean allowed = false;
5225 for (int i=0; i<N; i++) {
5226 if (pi.uriPermissionPatterns[i] != null
5227 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5228 allowed = true;
5229 break;
5230 }
5231 }
5232 if (!allowed) {
5233 throw new SecurityException("Provider " + pi.packageName
5234 + "/" + pi.name
5235 + " does not allow granting of permission to path of Uri "
5236 + uri);
5237 }
5238 }
5239
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005240 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005242 if (callingUid != Process.myUid()) {
5243 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5244 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5245 throw new SecurityException("Uid " + callingUid
5246 + " does not have permission to uri " + uri);
5247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005248 }
5249 }
5250
Dianne Hackborn39792d22010-08-19 18:01:52 -07005251 return targetUid;
5252 }
5253
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005254 public int checkGrantUriPermission(int callingUid, String targetPkg,
5255 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005256 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005257 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005258 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005259 }
5260 }
5261
Dianne Hackborn39792d22010-08-19 18:01:52 -07005262 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5263 Uri uri, int modeFlags, UriPermissionOwner owner) {
5264 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5265 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5266 if (modeFlags == 0) {
5267 return;
5268 }
5269
5270 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005271 // to the uri, and the target doesn't. Let's now give this to
5272 // the target.
5273
Joe Onorato8a9b2202010-02-26 18:56:32 -08005274 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005275 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 HashMap<Uri, UriPermission> targetUris
5278 = mGrantedUriPermissions.get(targetUid);
5279 if (targetUris == null) {
5280 targetUris = new HashMap<Uri, UriPermission>();
5281 mGrantedUriPermissions.put(targetUid, targetUris);
5282 }
5283
5284 UriPermission perm = targetUris.get(uri);
5285 if (perm == null) {
5286 perm = new UriPermission(targetUid, uri);
5287 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005288 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005291 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005293 } else {
5294 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5295 perm.readOwners.add(owner);
5296 owner.addReadPermission(perm);
5297 }
5298 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5299 perm.writeOwners.add(owner);
5300 owner.addWritePermission(perm);
5301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 }
5303 }
5304
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005305 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5306 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005307 if (targetPkg == null) {
5308 throw new NullPointerException("targetPkg");
5309 }
5310
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005311 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005312 if (targetUid < 0) {
5313 return;
5314 }
5315
5316 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5317 }
5318
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005319 static class NeededUriGrants extends ArrayList<Uri> {
5320 final String targetPkg;
5321 final int targetUid;
5322 final int flags;
5323
5324 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5325 targetPkg = _targetPkg;
5326 targetUid = _targetUid;
5327 flags = _flags;
5328 }
5329 }
5330
Dianne Hackborn39792d22010-08-19 18:01:52 -07005331 /**
5332 * Like checkGrantUriPermissionLocked, but takes an Intent.
5333 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005334 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5335 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005336 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005337 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5338 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005339 + " from " + intent + "; flags=0x"
5340 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5341
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005342 if (targetPkg == null) {
5343 throw new NullPointerException("targetPkg");
5344 }
5345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005347 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 }
5349 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005350 ClipData clip = intent.getClipData();
5351 if (data == null && clip == null) {
5352 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005353 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005354 if (data != null) {
5355 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
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(data);
5362 }
5363 }
5364 if (clip != null) {
5365 for (int i=0; i<clip.getItemCount(); i++) {
5366 Uri uri = clip.getItemAt(i).getUri();
5367 if (uri != null) {
5368 int target = -1;
5369 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5370 mode, needed != null ? needed.targetUid : -1);
5371 if (target > 0) {
5372 if (needed == null) {
5373 needed = new NeededUriGrants(targetPkg, target, mode);
5374 }
5375 needed.add(uri);
5376 }
5377 } else {
5378 Intent clipIntent = clip.getItemAt(i).getIntent();
5379 if (clipIntent != null) {
5380 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5381 callingUid, targetPkg, clipIntent, mode, needed);
5382 if (newNeeded != null) {
5383 needed = newNeeded;
5384 }
5385 }
5386 }
5387 }
5388 }
5389
5390 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005391 }
5392
5393 /**
5394 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5395 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005396 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5397 UriPermissionOwner owner) {
5398 if (needed != null) {
5399 for (int i=0; i<needed.size(); i++) {
5400 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5401 needed.get(i), needed.flags, owner);
5402 }
5403 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005404 }
5405
5406 void grantUriPermissionFromIntentLocked(int callingUid,
5407 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005408 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005409 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005410 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 return;
5412 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005413
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005414 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 }
5416
5417 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5418 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005419 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 synchronized(this) {
5421 final ProcessRecord r = getRecordForAppLocked(caller);
5422 if (r == null) {
5423 throw new SecurityException("Unable to find app for caller "
5424 + caller
5425 + " when granting permission to uri " + uri);
5426 }
5427 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005428 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 }
5430 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005431 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005432 }
5433
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005434 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 null);
5436 }
5437 }
5438
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005439 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5441 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5442 HashMap<Uri, UriPermission> perms
5443 = mGrantedUriPermissions.get(perm.uid);
5444 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005445 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005446 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 perms.remove(perm.uri);
5448 if (perms.size() == 0) {
5449 mGrantedUriPermissions.remove(perm.uid);
5450 }
5451 }
5452 }
5453 }
5454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5456 int modeFlags) {
5457 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5458 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5459 if (modeFlags == 0) {
5460 return;
5461 }
5462
Joe Onorato8a9b2202010-02-26 18:56:32 -08005463 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005464 "Revoking all granted permissions to " + uri);
5465
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005466 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467
5468 final String authority = uri.getAuthority();
5469 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005470 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005471 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 if (cpr != null) {
5473 pi = cpr.info;
5474 } else {
5475 try {
5476 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005477 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 } catch (RemoteException ex) {
5479 }
5480 }
5481 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005482 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 return;
5484 }
5485
5486 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005487 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 // Right now, if you are not the original owner of the permission,
5489 // you are not allowed to revoke it.
5490 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5491 throw new SecurityException("Uid " + callingUid
5492 + " does not have permission to uri " + uri);
5493 //}
5494 }
5495
5496 // Go through all of the permissions and remove any that match.
5497 final List<String> SEGMENTS = uri.getPathSegments();
5498 if (SEGMENTS != null) {
5499 final int NS = SEGMENTS.size();
5500 int N = mGrantedUriPermissions.size();
5501 for (int i=0; i<N; i++) {
5502 HashMap<Uri, UriPermission> perms
5503 = mGrantedUriPermissions.valueAt(i);
5504 Iterator<UriPermission> it = perms.values().iterator();
5505 toploop:
5506 while (it.hasNext()) {
5507 UriPermission perm = it.next();
5508 Uri targetUri = perm.uri;
5509 if (!authority.equals(targetUri.getAuthority())) {
5510 continue;
5511 }
5512 List<String> targetSegments = targetUri.getPathSegments();
5513 if (targetSegments == null) {
5514 continue;
5515 }
5516 if (targetSegments.size() < NS) {
5517 continue;
5518 }
5519 for (int j=0; j<NS; j++) {
5520 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5521 continue toploop;
5522 }
5523 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005524 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005525 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 perm.clearModes(modeFlags);
5527 if (perm.modeFlags == 0) {
5528 it.remove();
5529 }
5530 }
5531 if (perms.size() == 0) {
5532 mGrantedUriPermissions.remove(
5533 mGrantedUriPermissions.keyAt(i));
5534 N--;
5535 i--;
5536 }
5537 }
5538 }
5539 }
5540
5541 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5542 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005543 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 synchronized(this) {
5545 final ProcessRecord r = getRecordForAppLocked(caller);
5546 if (r == null) {
5547 throw new SecurityException("Unable to find app for caller "
5548 + caller
5549 + " when revoking permission to uri " + uri);
5550 }
5551 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005552 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 return;
5554 }
5555
5556 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5557 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5558 if (modeFlags == 0) {
5559 return;
5560 }
5561
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005562 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563
5564 final String authority = uri.getAuthority();
5565 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005566 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 if (cpr != null) {
5568 pi = cpr.info;
5569 } else {
5570 try {
5571 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005572 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 } catch (RemoteException ex) {
5574 }
5575 }
5576 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005577 Slog.w(TAG, "No content provider found for permission revoke: "
5578 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 return;
5580 }
5581
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005582 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 }
5584 }
5585
Dianne Hackborn7e269642010-08-25 19:50:20 -07005586 @Override
5587 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005588 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005589 synchronized(this) {
5590 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5591 return owner.getExternalTokenLocked();
5592 }
5593 }
5594
5595 @Override
5596 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5597 Uri uri, int modeFlags) {
5598 synchronized(this) {
5599 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5600 if (owner == null) {
5601 throw new IllegalArgumentException("Unknown owner: " + token);
5602 }
5603 if (fromUid != Binder.getCallingUid()) {
5604 if (Binder.getCallingUid() != Process.myUid()) {
5605 // Only system code can grant URI permissions on behalf
5606 // of other users.
5607 throw new SecurityException("nice try");
5608 }
5609 }
5610 if (targetPkg == null) {
5611 throw new IllegalArgumentException("null target");
5612 }
5613 if (uri == null) {
5614 throw new IllegalArgumentException("null uri");
5615 }
5616
5617 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5618 }
5619 }
5620
5621 @Override
5622 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5623 synchronized(this) {
5624 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5625 if (owner == null) {
5626 throw new IllegalArgumentException("Unknown owner: " + token);
5627 }
5628
5629 if (uri == null) {
5630 owner.removeUriPermissionsLocked(mode);
5631 } else {
5632 owner.removeUriPermissionLocked(uri, mode);
5633 }
5634 }
5635 }
5636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5638 synchronized (this) {
5639 ProcessRecord app =
5640 who != null ? getRecordForAppLocked(who) : null;
5641 if (app == null) return;
5642
5643 Message msg = Message.obtain();
5644 msg.what = WAIT_FOR_DEBUGGER_MSG;
5645 msg.obj = app;
5646 msg.arg1 = waiting ? 1 : 0;
5647 mHandler.sendMessage(msg);
5648 }
5649 }
5650
5651 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005652 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5653 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005655 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005656 outInfo.threshold = homeAppMem;
5657 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5658 outInfo.hiddenAppThreshold = hiddenAppMem;
5659 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005660 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005661 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5662 ProcessList.VISIBLE_APP_ADJ);
5663 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5664 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
5666
5667 // =========================================================
5668 // TASK MANAGEMENT
5669 // =========================================================
5670
5671 public List getTasks(int maxNum, int flags,
5672 IThumbnailReceiver receiver) {
5673 ArrayList list = new ArrayList();
5674
5675 PendingThumbnailsRecord pending = null;
5676 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005677 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678
5679 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005680 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5682 + ", receiver=" + receiver);
5683
5684 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5685 != PackageManager.PERMISSION_GRANTED) {
5686 if (receiver != null) {
5687 // If the caller wants to wait for pending thumbnails,
5688 // it ain't gonna get them.
5689 try {
5690 receiver.finished();
5691 } catch (RemoteException ex) {
5692 }
5693 }
5694 String msg = "Permission Denial: getTasks() from pid="
5695 + Binder.getCallingPid()
5696 + ", uid=" + Binder.getCallingUid()
5697 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005698 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 throw new SecurityException(msg);
5700 }
5701
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005702 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005703 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005704 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005705 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 TaskRecord curTask = null;
5707 int numActivities = 0;
5708 int numRunning = 0;
5709 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005710 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005712 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713
5714 // Initialize state for next task if needed.
5715 if (top == null ||
5716 (top.state == ActivityState.INITIALIZING
5717 && top.task == r.task)) {
5718 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005719 curTask = r.task;
5720 numActivities = numRunning = 0;
5721 }
5722
5723 // Add 'r' into the current task.
5724 numActivities++;
5725 if (r.app != null && r.app.thread != null) {
5726 numRunning++;
5727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728
Joe Onorato8a9b2202010-02-26 18:56:32 -08005729 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 TAG, r.intent.getComponent().flattenToShortString()
5731 + ": task=" + r.task);
5732
5733 // If the next one is a different task, generate a new
5734 // TaskInfo entry for what we have.
5735 if (next == null || next.task != curTask) {
5736 ActivityManager.RunningTaskInfo ci
5737 = new ActivityManager.RunningTaskInfo();
5738 ci.id = curTask.taskId;
5739 ci.baseActivity = r.intent.getComponent();
5740 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005741 if (top.thumbHolder != null) {
5742 ci.description = top.thumbHolder.lastDescription;
5743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005744 ci.numActivities = numActivities;
5745 ci.numRunning = numRunning;
5746 //System.out.println(
5747 // "#" + maxNum + ": " + " descr=" + ci.description);
5748 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005749 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 TAG, "State=" + top.state + "Idle=" + top.idle
5751 + " app=" + top.app
5752 + " thr=" + (top.app != null ? top.app.thread : null));
5753 if (top.state == ActivityState.RESUMED
5754 || top.state == ActivityState.PAUSING) {
5755 if (top.idle && top.app != null
5756 && top.app.thread != null) {
5757 topRecord = top;
5758 topThumbnail = top.app.thread;
5759 } else {
5760 top.thumbnailNeeded = true;
5761 }
5762 }
5763 if (pending == null) {
5764 pending = new PendingThumbnailsRecord(receiver);
5765 }
5766 pending.pendingRecords.add(top);
5767 }
5768 list.add(ci);
5769 maxNum--;
5770 top = null;
5771 }
5772 }
5773
5774 if (pending != null) {
5775 mPendingThumbnails.add(pending);
5776 }
5777 }
5778
Joe Onorato8a9b2202010-02-26 18:56:32 -08005779 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780
5781 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005782 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005784 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005786 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005787 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005788 }
5789 }
5790
5791 if (pending == null && receiver != null) {
5792 // In this case all thumbnails were available and the client
5793 // is being asked to be told when the remaining ones come in...
5794 // which is unusually, since the top-most currently running
5795 // activity should never have a canned thumbnail! Oh well.
5796 try {
5797 receiver.finished();
5798 } catch (RemoteException ex) {
5799 }
5800 }
5801
5802 return list;
5803 }
5804
5805 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005806 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005807 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5808 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 synchronized (this) {
5811 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5812 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005813 final boolean detailed = checkCallingPermission(
5814 android.Manifest.permission.GET_DETAILED_TASKS)
5815 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005817 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 final int N = mRecentTasks.size();
5820 ArrayList<ActivityManager.RecentTaskInfo> res
5821 = new ArrayList<ActivityManager.RecentTaskInfo>(
5822 maxNum < N ? maxNum : N);
5823 for (int i=0; i<N && maxNum > 0; i++) {
5824 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005825 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005826 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005827 // Return the entry if desired by the caller. We always return
5828 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005829 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005830 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5831 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005832
Dianne Hackborn905577f2011-09-07 18:31:28 -07005833 if (i == 0
5834 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 || (tr.intent == null)
5836 || ((tr.intent.getFlags()
5837 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5838 ActivityManager.RecentTaskInfo rti
5839 = new ActivityManager.RecentTaskInfo();
5840 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005841 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 rti.baseIntent = new Intent(
5843 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005844 if (!detailed) {
5845 rti.baseIntent.replaceExtras((Bundle)null);
5846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005848 rti.description = tr.lastDescription;
5849
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005850 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5851 // Check whether this activity is currently available.
5852 try {
5853 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005854 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005855 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005856 continue;
5857 }
5858 } else if (rti.baseIntent != null) {
5859 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005860 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005861 continue;
5862 }
5863 }
5864 } catch (RemoteException e) {
5865 // Will never happen.
5866 }
5867 }
5868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 res.add(rti);
5870 maxNum--;
5871 }
5872 }
5873 return res;
5874 }
5875 }
5876
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005877 private TaskRecord taskForIdLocked(int id) {
5878 final int N = mRecentTasks.size();
5879 for (int i=0; i<N; i++) {
5880 TaskRecord tr = mRecentTasks.get(i);
5881 if (tr.taskId == id) {
5882 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005883 }
5884 }
5885 return null;
5886 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005887
5888 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5889 synchronized (this) {
5890 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5891 "getTaskThumbnails()");
5892 TaskRecord tr = taskForIdLocked(id);
5893 if (tr != null) {
5894 return mMainStack.getTaskThumbnailsLocked(tr);
5895 }
5896 }
5897 return null;
5898 }
5899
Dianne Hackborn15491c62012-09-19 10:59:14 -07005900 public Bitmap getTaskTopThumbnail(int id) {
5901 synchronized (this) {
5902 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5903 "getTaskTopThumbnail()");
5904 TaskRecord tr = taskForIdLocked(id);
5905 if (tr != null) {
5906 return mMainStack.getTaskTopThumbnailLocked(tr);
5907 }
5908 }
5909 return null;
5910 }
5911
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005912 public boolean removeSubTask(int taskId, int subTaskIndex) {
5913 synchronized (this) {
5914 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5915 "removeSubTask()");
5916 long ident = Binder.clearCallingIdentity();
5917 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005918 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5919 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005920 } finally {
5921 Binder.restoreCallingIdentity(ident);
5922 }
5923 }
5924 }
5925
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005926 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5927 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005928 Intent baseIntent = new Intent(
5929 tr.intent != null ? tr.intent : tr.affinityIntent);
5930 ComponentName component = baseIntent.getComponent();
5931 if (component == null) {
5932 Slog.w(TAG, "Now component for base intent of task: " + tr);
5933 return;
5934 }
5935
5936 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005937 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005938
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005939 if (killProcesses) {
5940 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005941 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005942 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005943 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5944 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5945 for (int i=0; i<uids.size(); i++) {
5946 ProcessRecord proc = uids.valueAt(i);
5947 if (proc.userId != tr.userId) {
5948 continue;
5949 }
5950 if (!proc.pkgList.contains(pkg)) {
5951 continue;
5952 }
5953 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005954 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005955 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005956
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005957 // Kill the running processes.
5958 for (int i=0; i<procs.size(); i++) {
5959 ProcessRecord pr = procs.get(i);
5960 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5961 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005962 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005963 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005964 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005965 Process.killProcessQuiet(pr.pid);
5966 } else {
5967 pr.waitingToKill = "remove task";
5968 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005969 }
5970 }
5971 }
5972
5973 public boolean removeTask(int taskId, int flags) {
5974 synchronized (this) {
5975 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5976 "removeTask()");
5977 long ident = Binder.clearCallingIdentity();
5978 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005979 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5980 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005981 if (r != null) {
5982 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005983 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005984 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005985 } else {
5986 TaskRecord tr = null;
5987 int i=0;
5988 while (i < mRecentTasks.size()) {
5989 TaskRecord t = mRecentTasks.get(i);
5990 if (t.taskId == taskId) {
5991 tr = t;
5992 break;
5993 }
5994 i++;
5995 }
5996 if (tr != null) {
5997 if (tr.numActivities <= 0) {
5998 // Caller is just removing a recent task that is
5999 // not actively running. That is easy!
6000 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006001 cleanUpRemovedTaskLocked(tr, flags);
6002 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006003 } else {
6004 Slog.w(TAG, "removeTask: task " + taskId
6005 + " does not have activities to remove, "
6006 + " but numActivities=" + tr.numActivities
6007 + ": " + tr);
6008 }
6009 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006010 }
6011 } finally {
6012 Binder.restoreCallingIdentity(ident);
6013 }
6014 }
6015 return false;
6016 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6019 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006020 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 TaskRecord jt = startTask;
6022
6023 // First look backwards
6024 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006025 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 if (r.task != jt) {
6027 jt = r.task;
6028 if (affinity.equals(jt.affinity)) {
6029 return j;
6030 }
6031 }
6032 }
6033
6034 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006035 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 jt = startTask;
6037 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006038 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 if (r.task != jt) {
6040 if (affinity.equals(jt.affinity)) {
6041 return j;
6042 }
6043 jt = r.task;
6044 }
6045 }
6046
6047 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006048 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 return N-1;
6050 }
6051
6052 return -1;
6053 }
6054
6055 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006056 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006057 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006058 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6060 "moveTaskToFront()");
6061
6062 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006063 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6064 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006065 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006066 return;
6067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 final long origId = Binder.clearCallingIdentity();
6069 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006070 TaskRecord tr = taskForIdLocked(task);
6071 if (tr != null) {
6072 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6073 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006075 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(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006081 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006083 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6084 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006086 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6087 mMainStack.mUserLeaving = true;
6088 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006089 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6090 // Caller wants the home activity moved with it. To accomplish this,
6091 // we'll just move the home task to the top first.
6092 mMainStack.moveHomeToFrontLocked();
6093 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006094 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 return;
6096 }
6097 }
6098 } finally {
6099 Binder.restoreCallingIdentity(origId);
6100 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006101 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 }
6103 }
6104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 public void moveTaskToBack(int task) {
6106 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6107 "moveTaskToBack()");
6108
6109 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006110 if (mMainStack.mResumedActivity != null
6111 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006112 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6113 Binder.getCallingUid(), "Task to back")) {
6114 return;
6115 }
6116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006118 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 Binder.restoreCallingIdentity(origId);
6120 }
6121 }
6122
6123 /**
6124 * Moves an activity, and all of the other activities within the same task, to the bottom
6125 * of the history stack. The activity's order within the task is unchanged.
6126 *
6127 * @param token A reference to the activity we wish to move
6128 * @param nonRoot If false then this only works if the activity is the root
6129 * of a task; if true it will work for any activity in a task.
6130 * @return Returns true if the move completed, false if not.
6131 */
6132 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006133 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 synchronized(this) {
6135 final long origId = Binder.clearCallingIdentity();
6136 int taskId = getTaskForActivityLocked(token, !nonRoot);
6137 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006138 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 }
6140 Binder.restoreCallingIdentity(origId);
6141 }
6142 return false;
6143 }
6144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006145 public void moveTaskBackwards(int task) {
6146 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6147 "moveTaskBackwards()");
6148
6149 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006150 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6151 Binder.getCallingUid(), "Task backwards")) {
6152 return;
6153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 final long origId = Binder.clearCallingIdentity();
6155 moveTaskBackwardsLocked(task);
6156 Binder.restoreCallingIdentity(origId);
6157 }
6158 }
6159
6160 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006161 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163
6164 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6165 synchronized(this) {
6166 return getTaskForActivityLocked(token, onlyRoot);
6167 }
6168 }
6169
6170 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006171 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 TaskRecord lastTask = null;
6173 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006174 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006175 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 if (!onlyRoot || lastTask != r.task) {
6177 return r.task.taskId;
6178 }
6179 return -1;
6180 }
6181 lastTask = r.task;
6182 }
6183
6184 return -1;
6185 }
6186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 // =========================================================
6188 // THUMBNAILS
6189 // =========================================================
6190
6191 public void reportThumbnail(IBinder token,
6192 Bitmap thumbnail, CharSequence description) {
6193 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6194 final long origId = Binder.clearCallingIdentity();
6195 sendPendingThumbnail(null, token, thumbnail, description, true);
6196 Binder.restoreCallingIdentity(origId);
6197 }
6198
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006199 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 Bitmap thumbnail, CharSequence description, boolean always) {
6201 TaskRecord task = null;
6202 ArrayList receivers = null;
6203
6204 //System.out.println("Send pending thumbnail: " + r);
6205
6206 synchronized(this) {
6207 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006208 r = mMainStack.isInStackLocked(token);
6209 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 return;
6211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006213 if (thumbnail == null && r.thumbHolder != null) {
6214 thumbnail = r.thumbHolder.lastThumbnail;
6215 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217 if (thumbnail == null && !always) {
6218 // If there is no thumbnail, and this entry is not actually
6219 // going away, then abort for now and pick up the next
6220 // thumbnail we get.
6221 return;
6222 }
6223 task = r.task;
6224
6225 int N = mPendingThumbnails.size();
6226 int i=0;
6227 while (i<N) {
6228 PendingThumbnailsRecord pr =
6229 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6230 //System.out.println("Looking in " + pr.pendingRecords);
6231 if (pr.pendingRecords.remove(r)) {
6232 if (receivers == null) {
6233 receivers = new ArrayList();
6234 }
6235 receivers.add(pr);
6236 if (pr.pendingRecords.size() == 0) {
6237 pr.finished = true;
6238 mPendingThumbnails.remove(i);
6239 N--;
6240 continue;
6241 }
6242 }
6243 i++;
6244 }
6245 }
6246
6247 if (receivers != null) {
6248 final int N = receivers.size();
6249 for (int i=0; i<N; i++) {
6250 try {
6251 PendingThumbnailsRecord pr =
6252 (PendingThumbnailsRecord)receivers.get(i);
6253 pr.receiver.newThumbnail(
6254 task != null ? task.taskId : -1, thumbnail, description);
6255 if (pr.finished) {
6256 pr.receiver.finished();
6257 }
6258 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006259 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
6261 }
6262 }
6263 }
6264
6265 // =========================================================
6266 // CONTENT PROVIDERS
6267 // =========================================================
6268
Jeff Brown10e89712011-07-08 18:52:57 -07006269 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6270 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006272 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006273 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006274 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 } catch (RemoteException ex) {
6276 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006277 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006278 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6279 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006281 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 for (int i=0; i<N; i++) {
6283 ProviderInfo cpi =
6284 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006285 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6286 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006287 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006288 // This is a singleton provider, but a user besides the
6289 // default user is asking to initialize a process it runs
6290 // in... well, no, it doesn't actually run in this process,
6291 // it runs in the process of the default user. Get rid of it.
6292 providers.remove(i);
6293 N--;
6294 continue;
6295 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006296
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006297 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006298 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006300 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006301 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006303 if (DEBUG_MU)
6304 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 app.pubProviders.put(cpi.name, cpr);
6306 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006307 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 }
6309 }
6310 return providers;
6311 }
6312
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006313 /**
6314 * Check if {@link ProcessRecord} has a possible chance at accessing the
6315 * given {@link ProviderInfo}. Final permission checking is always done
6316 * in {@link ContentProvider}.
6317 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006319 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006321 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006323 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006324 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 return null;
6326 }
6327 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006328 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 == PackageManager.PERMISSION_GRANTED) {
6330 return null;
6331 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006332
6333 PathPermission[] pps = cpi.pathPermissions;
6334 if (pps != null) {
6335 int i = pps.length;
6336 while (i > 0) {
6337 i--;
6338 PathPermission pp = pps[i];
6339 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006340 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006341 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006342 return null;
6343 }
6344 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006345 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006346 == PackageManager.PERMISSION_GRANTED) {
6347 return null;
6348 }
6349 }
6350 }
6351
Dianne Hackbornb424b632010-08-18 15:59:05 -07006352 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6353 if (perms != null) {
6354 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6355 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6356 return null;
6357 }
6358 }
6359 }
6360
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006361 String msg;
6362 if (!cpi.exported) {
6363 msg = "Permission Denial: opening provider " + cpi.name
6364 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6365 + ", uid=" + callingUid + ") that is not exported from uid "
6366 + cpi.applicationInfo.uid;
6367 } else {
6368 msg = "Permission Denial: opening provider " + cpi.name
6369 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6370 + ", uid=" + callingUid + ") requires "
6371 + cpi.readPermission + " or " + cpi.writePermission;
6372 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006373 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return msg;
6375 }
6376
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006377 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6378 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006379 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006380 for (int i=0; i<r.conProviders.size(); i++) {
6381 ContentProviderConnection conn = r.conProviders.get(i);
6382 if (conn.provider == cpr) {
6383 if (DEBUG_PROVIDER) Slog.v(TAG,
6384 "Adding provider requested by "
6385 + r.processName + " from process "
6386 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6387 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6388 if (stable) {
6389 conn.stableCount++;
6390 conn.numStableIncs++;
6391 } else {
6392 conn.unstableCount++;
6393 conn.numUnstableIncs++;
6394 }
6395 return conn;
6396 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006397 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006398 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6399 if (stable) {
6400 conn.stableCount = 1;
6401 conn.numStableIncs = 1;
6402 } else {
6403 conn.unstableCount = 1;
6404 conn.numUnstableIncs = 1;
6405 }
6406 cpr.connections.add(conn);
6407 r.conProviders.add(conn);
6408 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006409 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006410 cpr.addExternalProcessHandleLocked(externalProcessToken);
6411 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006412 }
6413
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006414 boolean decProviderCountLocked(ContentProviderConnection conn,
6415 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6416 if (conn != null) {
6417 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006418 if (DEBUG_PROVIDER) Slog.v(TAG,
6419 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006420 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006421 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006422 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6423 if (stable) {
6424 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006425 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006426 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006427 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006428 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6429 cpr.connections.remove(conn);
6430 conn.client.conProviders.remove(conn);
6431 return true;
6432 }
6433 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006434 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006435 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 return false;
6437 }
6438
Amith Yamasani742a6712011-05-04 14:49:28 -07006439 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006440 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006441 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006442 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 ProviderInfo cpi = null;
6444
6445 synchronized(this) {
6446 ProcessRecord r = null;
6447 if (caller != null) {
6448 r = getRecordForAppLocked(caller);
6449 if (r == null) {
6450 throw new SecurityException(
6451 "Unable to find app for caller " + caller
6452 + " (pid=" + Binder.getCallingPid()
6453 + ") when getting content provider " + name);
6454 }
6455 }
6456
6457 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006458 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006459 boolean providerRunning = cpr != null;
6460 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006462 String msg;
6463 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6464 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 }
6466
6467 if (r != null && cpr.canRunHere(r)) {
6468 // This provider has been published or is in the process
6469 // of being published... but it is also allowed to run
6470 // in the caller's process, so don't make a connection
6471 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006472 ContentProviderHolder holder = cpr.newHolder(null);
6473 // don't give caller the provider object, it needs
6474 // to make its own.
6475 holder.provider = null;
6476 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
6479 final long origId = Binder.clearCallingIdentity();
6480
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006481 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006483 conn = incProviderCountLocked(r, cpr, token, stable);
6484 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006485 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006486 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006487 // make sure to count it as being accessed and thus
6488 // back up on the LRU list. This is good because
6489 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006490 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006491 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006492 }
6493
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006494 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006495 if (false) {
6496 if (cpr.name.flattenToShortString().equals(
6497 "com.android.providers.calendar/.CalendarProvider2")) {
6498 Slog.v(TAG, "****************** KILLING "
6499 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006500 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006501 }
6502 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006503 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006504 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6505 // NOTE: there is still a race here where a signal could be
6506 // pending on the process even though we managed to update its
6507 // adj level. Not sure what to do about this, but at least
6508 // the race is now smaller.
6509 if (!success) {
6510 // Uh oh... it looks like the provider's process
6511 // has been killed on us. We need to wait for a new
6512 // process to be started, and make sure its death
6513 // doesn't kill our process.
6514 Slog.i(TAG,
6515 "Existing provider " + cpr.name.flattenToShortString()
6516 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006517 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006518 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006519 if (!lastRef) {
6520 // This wasn't the last ref our process had on
6521 // the provider... we have now been killed, bail.
6522 return null;
6523 }
6524 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006525 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 }
6528
6529 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006532 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006533 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006535 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006536 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006537 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 } catch (RemoteException ex) {
6539 }
6540 if (cpi == null) {
6541 return null;
6542 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006543 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6544 cpi.name, cpi.flags);
6545 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006546 userId = 0;
6547 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006548 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006549
Dianne Hackbornb424b632010-08-18 15:59:05 -07006550 String msg;
6551 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6552 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006553 }
6554
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006555 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006556 && !cpi.processName.equals("system")) {
6557 // If this content provider does not run in the system
6558 // process, and the system is not yet ready to run other
6559 // processes, then fail fast instead of hanging.
6560 throw new IllegalArgumentException(
6561 "Attempt to launch content provider before system ready");
6562 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006563
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006564 // Make sure that the user who owns this provider is started. If not,
6565 // we don't want to allow it to run.
6566 if (mStartedUsers.get(userId) == null) {
6567 Slog.w(TAG, "Unable to launch app "
6568 + cpi.applicationInfo.packageName + "/"
6569 + cpi.applicationInfo.uid + " for provider "
6570 + name + ": user " + userId + " is stopped");
6571 return null;
6572 }
6573
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006574 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006575 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 final boolean firstClass = cpr == null;
6577 if (firstClass) {
6578 try {
6579 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006580 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 getApplicationInfo(
6582 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006583 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006585 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 + cpi.name);
6587 return null;
6588 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006589 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006590 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006591 } catch (RemoteException ex) {
6592 // pm is in same process, this will never happen.
6593 }
6594 }
6595
6596 if (r != null && cpr.canRunHere(r)) {
6597 // If this is a multiprocess provider, then just return its
6598 // info and allow the caller to instantiate it. Only do
6599 // this if the provider is the same user as the caller's
6600 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006601 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006604 if (DEBUG_PROVIDER) {
6605 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006606 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006607 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006608 }
6609
6610 // This is single process, and our app is now connecting to it.
6611 // See if we are already in the process of launching this
6612 // provider.
6613 final int N = mLaunchingProviders.size();
6614 int i;
6615 for (i=0; i<N; i++) {
6616 if (mLaunchingProviders.get(i) == cpr) {
6617 break;
6618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 }
6620
6621 // If the provider is not already being launched, then get it
6622 // started.
6623 if (i >= N) {
6624 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006625
6626 try {
6627 // Content provider is now in use, its package can't be stopped.
6628 try {
6629 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006630 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006631 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006632 } catch (IllegalArgumentException e) {
6633 Slog.w(TAG, "Failed trying to unstop package "
6634 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006635 }
6636
6637 ProcessRecord proc = startProcessLocked(cpi.processName,
6638 cpr.appInfo, false, 0, "content provider",
6639 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006640 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006641 if (proc == null) {
6642 Slog.w(TAG, "Unable to launch app "
6643 + cpi.applicationInfo.packageName + "/"
6644 + cpi.applicationInfo.uid + " for provider "
6645 + name + ": process is bad");
6646 return null;
6647 }
6648 cpr.launchingApp = proc;
6649 mLaunchingProviders.add(cpr);
6650 } finally {
6651 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
6654
6655 // Make sure the provider is published (the same provider class
6656 // may be published under multiple names).
6657 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006658 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006660
Amith Yamasani742a6712011-05-04 14:49:28 -07006661 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006662 conn = incProviderCountLocked(r, cpr, token, stable);
6663 if (conn != null) {
6664 conn.waiting = true;
6665 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006666 }
6667 }
6668
6669 // Wait for the provider to be published...
6670 synchronized (cpr) {
6671 while (cpr.provider == null) {
6672 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006673 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 + cpi.applicationInfo.packageName + "/"
6675 + cpi.applicationInfo.uid + " for provider "
6676 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006677 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006678 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 cpi.applicationInfo.packageName,
6680 cpi.applicationInfo.uid, name);
6681 return null;
6682 }
6683 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006684 if (DEBUG_MU) {
6685 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6686 + cpr.launchingApp);
6687 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006688 if (conn != null) {
6689 conn.waiting = true;
6690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 cpr.wait();
6692 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006693 } finally {
6694 if (conn != null) {
6695 conn.waiting = false;
6696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 }
6698 }
6699 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006700 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
6702
6703 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006704 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006705 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 if (caller == null) {
6707 String msg = "null IApplicationThread when getting content provider "
6708 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006709 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 throw new SecurityException(msg);
6711 }
6712
Dianne Hackborn139748f2012-09-24 11:36:57 -07006713 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006714 false, true, "getContentProvider", null);
6715 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 }
6717
Jeff Sharkey6d515712012-09-20 16:06:08 -07006718 public ContentProviderHolder getContentProviderExternal(
6719 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006720 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6721 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006722 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006723 false, true, "getContentProvider", null);
6724 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006725 }
6726
Dianne Hackborn41203752012-08-31 14:05:51 -07006727 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6728 IBinder token, int userId) {
6729 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006730 }
6731
6732 /**
6733 * Drop a content provider from a ProcessRecord's bookkeeping
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006735 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006736 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006738 ContentProviderConnection conn;
6739 try {
6740 conn = (ContentProviderConnection)connection;
6741 } catch (ClassCastException e) {
6742 String msg ="removeContentProvider: " + connection
6743 + " not a ContentProviderConnection";
6744 Slog.w(TAG, msg);
6745 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006747 if (conn == null) {
6748 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006750 if (decProviderCountLocked(conn, null, null, stable)) {
6751 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 }
6754 }
6755
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006756 public void removeContentProviderExternal(String name, IBinder token) {
6757 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6758 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006759 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006760 }
6761
Dianne Hackborn41203752012-08-31 14:05:51 -07006762 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006764 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 if(cpr == null) {
6766 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006767 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 return;
6769 }
6770
6771 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006772 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006773 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006774 if (localCpr.hasExternalProcessHandles()) {
6775 if (localCpr.removeExternalProcessHandleLocked(token)) {
6776 updateOomAdjLocked();
6777 } else {
6778 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6779 + " with no external reference for token: "
6780 + token + ".");
6781 }
6782 } else {
6783 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6784 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 }
6787 }
6788
6789 public final void publishContentProviders(IApplicationThread caller,
6790 List<ContentProviderHolder> providers) {
6791 if (providers == null) {
6792 return;
6793 }
6794
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006795 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006796 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006798 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006799 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006800 if (r == null) {
6801 throw new SecurityException(
6802 "Unable to find app for caller " + caller
6803 + " (pid=" + Binder.getCallingPid()
6804 + ") when publishing content providers");
6805 }
6806
6807 final long origId = Binder.clearCallingIdentity();
6808
6809 final int N = providers.size();
6810 for (int i=0; i<N; i++) {
6811 ContentProviderHolder src = providers.get(i);
6812 if (src == null || src.info == null || src.provider == null) {
6813 continue;
6814 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006815 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006816 if (DEBUG_MU)
6817 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006818 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006819 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006820 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 String names[] = dst.info.authority.split(";");
6822 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006823 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006824 }
6825
6826 int NL = mLaunchingProviders.size();
6827 int j;
6828 for (j=0; j<NL; j++) {
6829 if (mLaunchingProviders.get(j) == dst) {
6830 mLaunchingProviders.remove(j);
6831 j--;
6832 NL--;
6833 }
6834 }
6835 synchronized (dst) {
6836 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006837 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006838 dst.notifyAll();
6839 }
6840 updateOomAdjLocked(r);
6841 }
6842 }
6843
6844 Binder.restoreCallingIdentity(origId);
6845 }
6846 }
6847
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006848 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6849 ContentProviderConnection conn;
6850 try {
6851 conn = (ContentProviderConnection)connection;
6852 } catch (ClassCastException e) {
6853 String msg ="refContentProvider: " + connection
6854 + " not a ContentProviderConnection";
6855 Slog.w(TAG, msg);
6856 throw new IllegalArgumentException(msg);
6857 }
6858 if (conn == null) {
6859 throw new NullPointerException("connection is null");
6860 }
6861
6862 synchronized (this) {
6863 if (stable > 0) {
6864 conn.numStableIncs += stable;
6865 }
6866 stable = conn.stableCount + stable;
6867 if (stable < 0) {
6868 throw new IllegalStateException("stableCount < 0: " + stable);
6869 }
6870
6871 if (unstable > 0) {
6872 conn.numUnstableIncs += unstable;
6873 }
6874 unstable = conn.unstableCount + unstable;
6875 if (unstable < 0) {
6876 throw new IllegalStateException("unstableCount < 0: " + unstable);
6877 }
6878
6879 if ((stable+unstable) <= 0) {
6880 throw new IllegalStateException("ref counts can't go to zero here: stable="
6881 + stable + " unstable=" + unstable);
6882 }
6883 conn.stableCount = stable;
6884 conn.unstableCount = unstable;
6885 return !conn.dead;
6886 }
6887 }
6888
6889 public void unstableProviderDied(IBinder connection) {
6890 ContentProviderConnection conn;
6891 try {
6892 conn = (ContentProviderConnection)connection;
6893 } catch (ClassCastException e) {
6894 String msg ="refContentProvider: " + connection
6895 + " not a ContentProviderConnection";
6896 Slog.w(TAG, msg);
6897 throw new IllegalArgumentException(msg);
6898 }
6899 if (conn == null) {
6900 throw new NullPointerException("connection is null");
6901 }
6902
6903 // Safely retrieve the content provider associated with the connection.
6904 IContentProvider provider;
6905 synchronized (this) {
6906 provider = conn.provider.provider;
6907 }
6908
6909 if (provider == null) {
6910 // Um, yeah, we're way ahead of you.
6911 return;
6912 }
6913
6914 // Make sure the caller is being honest with us.
6915 if (provider.asBinder().pingBinder()) {
6916 // Er, no, still looks good to us.
6917 synchronized (this) {
6918 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6919 + " says " + conn + " died, but we don't agree");
6920 return;
6921 }
6922 }
6923
6924 // Well look at that! It's dead!
6925 synchronized (this) {
6926 if (conn.provider.provider != provider) {
6927 // But something changed... good enough.
6928 return;
6929 }
6930
6931 ProcessRecord proc = conn.provider.proc;
6932 if (proc == null || proc.thread == null) {
6933 // Seems like the process is already cleaned up.
6934 return;
6935 }
6936
6937 // As far as we're concerned, this is just like receiving a
6938 // death notification... just a bit prematurely.
6939 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6940 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006941 final long ident = Binder.clearCallingIdentity();
6942 try {
6943 appDiedLocked(proc, proc.pid, proc.thread);
6944 } finally {
6945 Binder.restoreCallingIdentity(ident);
6946 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006947 }
6948 }
6949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006951 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006952 synchronized (mSelf) {
6953 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6954 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006955 if (providers != null) {
6956 for (int i=providers.size()-1; i>=0; i--) {
6957 ProviderInfo pi = (ProviderInfo)providers.get(i);
6958 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6959 Slog.w(TAG, "Not installing system proc provider " + pi.name
6960 + ": not system .apk");
6961 providers.remove(i);
6962 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006963 }
6964 }
6965 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006966 if (providers != null) {
6967 mSystemThread.installSystemProviders(providers);
6968 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006969
6970 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006971
6972 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 }
6974
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006975 /**
6976 * Allows app to retrieve the MIME type of a URI without having permission
6977 * to access its content provider.
6978 *
6979 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6980 *
6981 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6982 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6983 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006984 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006985 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006986 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006987 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006988 final String name = uri.getAuthority();
6989 final long ident = Binder.clearCallingIdentity();
6990 ContentProviderHolder holder = null;
6991
6992 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006993 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006994 if (holder != null) {
6995 return holder.provider.getType(uri);
6996 }
6997 } catch (RemoteException e) {
6998 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6999 return null;
7000 } finally {
7001 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07007002 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007003 }
7004 Binder.restoreCallingIdentity(ident);
7005 }
7006
7007 return null;
7008 }
7009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 // =========================================================
7011 // GLOBAL MANAGEMENT
7012 // =========================================================
7013
7014 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007015 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007016 String proc = customProcess != null ? customProcess : info.processName;
7017 BatteryStatsImpl.Uid.Proc ps = null;
7018 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007019 int uid = info.uid;
7020 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007021 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007022 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7023 uid = 0;
7024 while (true) {
7025 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7026 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7027 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7028 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007029 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007030 mNextIsolatedProcessUid++;
7031 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7032 // No process for this uid, use it.
7033 break;
7034 }
7035 stepsLeft--;
7036 if (stepsLeft <= 0) {
7037 return null;
7038 }
7039 }
7040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 synchronized (stats) {
7042 ps = stats.getProcessStatsLocked(info.uid, proc);
7043 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007044 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 }
7046
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007047 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7048 ProcessRecord app;
7049 if (!isolated) {
7050 app = getProcessRecordLocked(info.processName, info.uid);
7051 } else {
7052 app = null;
7053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054
7055 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007056 app = newProcessRecordLocked(null, info, null, isolated);
7057 mProcessNames.put(info.processName, app.uid, app);
7058 if (isolated) {
7059 mIsolatedProcesses.put(app.uid, app);
7060 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007061 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063
Dianne Hackborne7f97212011-02-24 14:40:20 -08007064 // This package really, really can not be stopped.
7065 try {
7066 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007067 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007068 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007069 } catch (IllegalArgumentException e) {
7070 Slog.w(TAG, "Failed trying to unstop package "
7071 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007072 }
7073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7075 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7076 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007077 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007078 }
7079 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7080 mPersistentStartingProcesses.add(app);
7081 startProcessLocked(app, "added application", app.processName);
7082 }
7083
7084 return app;
7085 }
7086
7087 public void unhandledBack() {
7088 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7089 "unhandledBack()");
7090
7091 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007092 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007093 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 TAG, "Performing unhandledBack(): stack size = " + count);
7095 if (count > 1) {
7096 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007097 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007098 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 Binder.restoreCallingIdentity(origId);
7100 }
7101 }
7102 }
7103
7104 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007105 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007106 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007108 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 ParcelFileDescriptor pfd = null;
7110 if (cph != null) {
7111 // We record the binder invoker's uid in thread-local storage before
7112 // going to the content provider to open the file. Later, in the code
7113 // that handles all permissions checks, we look for this uid and use
7114 // that rather than the Activity Manager's own uid. The effect is that
7115 // we do the check against the caller's permissions even though it looks
7116 // to the content provider like the Activity Manager itself is making
7117 // the request.
7118 sCallerIdentity.set(new Identity(
7119 Binder.getCallingPid(), Binder.getCallingUid()));
7120 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08007121 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 } catch (FileNotFoundException e) {
7123 // do nothing; pfd will be returned null
7124 } finally {
7125 // Ensure that whatever happens, we clean up the identity state
7126 sCallerIdentity.remove();
7127 }
7128
7129 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007130 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007131 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007132 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 }
7134 return pfd;
7135 }
7136
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007137 // Actually is sleeping or shutting down or whatever else in the future
7138 // is an inactive state.
7139 public boolean isSleeping() {
7140 return mSleeping || mShuttingDown;
7141 }
7142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007144 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7145 != PackageManager.PERMISSION_GRANTED) {
7146 throw new SecurityException("Requires permission "
7147 + android.Manifest.permission.DEVICE_POWER);
7148 }
7149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007151 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007152 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007154 if (!mSleeping) {
7155 mSleeping = true;
7156 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007157
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007158 // Initialize the wake times of all processes.
7159 checkExcessivePowerUsageLocked(false);
7160 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7161 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7162 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 }
7165 }
7166
Dianne Hackborn55280a92009-05-07 15:53:46 -07007167 public boolean shutdown(int timeout) {
7168 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7169 != PackageManager.PERMISSION_GRANTED) {
7170 throw new SecurityException("Requires permission "
7171 + android.Manifest.permission.SHUTDOWN);
7172 }
7173
7174 boolean timedout = false;
7175
7176 synchronized(this) {
7177 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007178 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007179
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007180 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007181 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007182 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007183 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007184 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007185 long delay = endTime - System.currentTimeMillis();
7186 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007187 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007188 timedout = true;
7189 break;
7190 }
7191 try {
7192 this.wait();
7193 } catch (InterruptedException e) {
7194 }
7195 }
7196 }
7197 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007198
7199 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007200 mUsageStatsService.shutdown();
7201 mBatteryStatsService.shutdown();
7202
7203 return timedout;
7204 }
7205
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007206 public final void activitySlept(IBinder token) {
7207 if (localLOGV) Slog.v(
7208 TAG, "Activity slept: token=" + token);
7209
7210 ActivityRecord r = null;
7211
7212 final long origId = Binder.clearCallingIdentity();
7213
7214 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007215 r = mMainStack.isInStackLocked(token);
7216 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007217 mMainStack.activitySleptLocked(r);
7218 }
7219 }
7220
7221 Binder.restoreCallingIdentity(origId);
7222 }
7223
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007224 private void comeOutOfSleepIfNeededLocked() {
7225 if (!mWentToSleep && !mLockScreenShown) {
7226 if (mSleeping) {
7227 mSleeping = false;
7228 mMainStack.awakeFromSleepingLocked();
7229 mMainStack.resumeTopActivityLocked(null);
7230 }
7231 }
7232 }
7233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007234 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007235 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7236 != PackageManager.PERMISSION_GRANTED) {
7237 throw new SecurityException("Requires permission "
7238 + android.Manifest.permission.DEVICE_POWER);
7239 }
7240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007241 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007242 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007243 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007244 comeOutOfSleepIfNeededLocked();
7245 }
7246 }
7247
Jeff Brownc042ee22012-05-08 13:03:42 -07007248 private void updateEventDispatchingLocked() {
7249 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7250 }
7251
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007252 public void setLockScreenShown(boolean shown) {
7253 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7254 != PackageManager.PERMISSION_GRANTED) {
7255 throw new SecurityException("Requires permission "
7256 + android.Manifest.permission.DEVICE_POWER);
7257 }
7258
7259 synchronized(this) {
7260 mLockScreenShown = shown;
7261 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 }
7263 }
7264
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007265 public void stopAppSwitches() {
7266 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7267 != PackageManager.PERMISSION_GRANTED) {
7268 throw new SecurityException("Requires permission "
7269 + android.Manifest.permission.STOP_APP_SWITCHES);
7270 }
7271
7272 synchronized(this) {
7273 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7274 + APP_SWITCH_DELAY_TIME;
7275 mDidAppSwitch = false;
7276 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7277 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7278 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7279 }
7280 }
7281
7282 public void resumeAppSwitches() {
7283 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7284 != PackageManager.PERMISSION_GRANTED) {
7285 throw new SecurityException("Requires permission "
7286 + android.Manifest.permission.STOP_APP_SWITCHES);
7287 }
7288
7289 synchronized(this) {
7290 // Note that we don't execute any pending app switches... we will
7291 // let those wait until either the timeout, or the next start
7292 // activity request.
7293 mAppSwitchesAllowedTime = 0;
7294 }
7295 }
7296
7297 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7298 String name) {
7299 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7300 return true;
7301 }
7302
7303 final int perm = checkComponentPermission(
7304 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007305 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007306 if (perm == PackageManager.PERMISSION_GRANTED) {
7307 return true;
7308 }
7309
Joe Onorato8a9b2202010-02-26 18:56:32 -08007310 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007311 return false;
7312 }
7313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 public void setDebugApp(String packageName, boolean waitForDebugger,
7315 boolean persistent) {
7316 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7317 "setDebugApp()");
7318
7319 // Note that this is not really thread safe if there are multiple
7320 // callers into it at the same time, but that's not a situation we
7321 // care about.
7322 if (persistent) {
7323 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007324 Settings.Global.putString(
7325 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007327 Settings.Global.putInt(
7328 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 waitForDebugger ? 1 : 0);
7330 }
7331
7332 synchronized (this) {
7333 if (!persistent) {
7334 mOrigDebugApp = mDebugApp;
7335 mOrigWaitForDebugger = mWaitForDebugger;
7336 }
7337 mDebugApp = packageName;
7338 mWaitForDebugger = waitForDebugger;
7339 mDebugTransient = !persistent;
7340 if (packageName != null) {
7341 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007342 forceStopPackageLocked(packageName, -1, false, false, true, true,
7343 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 Binder.restoreCallingIdentity(origId);
7345 }
7346 }
7347 }
7348
Siva Velusamy92a8b222012-03-09 16:24:04 -08007349 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7350 synchronized (this) {
7351 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7352 if (!isDebuggable) {
7353 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7354 throw new SecurityException("Process not debuggable: " + app.packageName);
7355 }
7356 }
7357
7358 mOpenGlTraceApp = processName;
7359 }
7360 }
7361
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007362 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7363 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7364 synchronized (this) {
7365 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7366 if (!isDebuggable) {
7367 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7368 throw new SecurityException("Process not debuggable: " + app.packageName);
7369 }
7370 }
7371 mProfileApp = processName;
7372 mProfileFile = profileFile;
7373 if (mProfileFd != null) {
7374 try {
7375 mProfileFd.close();
7376 } catch (IOException e) {
7377 }
7378 mProfileFd = null;
7379 }
7380 mProfileFd = profileFd;
7381 mProfileType = 0;
7382 mAutoStopProfiler = autoStopProfiler;
7383 }
7384 }
7385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 public void setAlwaysFinish(boolean enabled) {
7387 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7388 "setAlwaysFinish()");
7389
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007390 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007391 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007392 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393
7394 synchronized (this) {
7395 mAlwaysFinishActivities = enabled;
7396 }
7397 }
7398
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007399 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007401 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007403 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 }
7405 }
7406
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007407 public boolean isUserAMonkey() {
7408 // For now the fact that there is a controller implies
7409 // we have a monkey.
7410 synchronized (this) {
7411 return mController != null;
7412 }
7413 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007414
7415 public void requestBugReport() {
Jeff Sharkeyb9323192013-02-05 13:32:18 -08007416 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007417 SystemProperties.set("ctl.start", "bugreport");
7418 }
7419
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007420 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7421 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7422 != PackageManager.PERMISSION_GRANTED) {
7423 throw new SecurityException("Requires permission "
7424 + android.Manifest.permission.FILTER_EVENTS);
7425 }
7426
7427 ProcessRecord proc;
7428
7429 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7430 synchronized (this) {
7431 synchronized (mPidsSelfLocked) {
7432 proc = mPidsSelfLocked.get(pid);
7433 }
7434 if (proc != null) {
7435 if (proc.debugging) {
7436 return -1;
7437 }
7438
7439 if (mDidDexOpt) {
7440 // Give more time since we were dexopting.
7441 mDidDexOpt = false;
7442 return -1;
7443 }
7444
7445 if (proc.instrumentationClass != null) {
7446 Bundle info = new Bundle();
7447 info.putString("shortMsg", "keyDispatchingTimedOut");
7448 info.putString("longMsg", "Timed out while dispatching key event");
7449 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7450 proc = null;
7451 }
7452 }
7453 }
7454
7455 if (proc != null) {
7456 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7457 if (proc.instrumentationClass != null || proc.usingWrapper) {
7458 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7459 }
7460 }
7461
7462 return KEY_DISPATCHING_TIMEOUT;
7463 }
7464
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007465 public Bundle getTopActivityExtras(int requestType) {
7466 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7467 "getTopActivityExtras()");
7468 PendingActivityExtras pae;
7469 Bundle extras = new Bundle();
7470 synchronized (this) {
7471 ActivityRecord activity = mMainStack.mResumedActivity;
7472 if (activity == null) {
7473 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7474 return null;
7475 }
7476 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7477 if (activity.app == null || activity.app.thread == null) {
7478 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7479 return extras;
7480 }
7481 if (activity.app.pid == Binder.getCallingPid()) {
7482 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7483 return extras;
7484 }
7485 pae = new PendingActivityExtras(activity);
7486 try {
7487 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7488 mPendingActivityExtras.add(pae);
7489 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7490 } catch (RemoteException e) {
7491 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7492 return extras;
7493 }
7494 }
7495 synchronized (pae) {
7496 while (!pae.haveResult) {
7497 try {
7498 pae.wait();
7499 } catch (InterruptedException e) {
7500 }
7501 }
7502 if (pae.result != null) {
7503 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7504 }
7505 }
7506 synchronized (this) {
7507 mPendingActivityExtras.remove(pae);
7508 mHandler.removeCallbacks(pae);
7509 }
7510 return extras;
7511 }
7512
7513 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7514 PendingActivityExtras pae = (PendingActivityExtras)token;
7515 synchronized (pae) {
7516 pae.result = extras;
7517 pae.haveResult = true;
7518 pae.notifyAll();
7519 }
7520 }
7521
Jeff Sharkeya4620792011-05-20 15:29:23 -07007522 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007523 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7524 "registerProcessObserver()");
7525 synchronized (this) {
7526 mProcessObservers.register(observer);
7527 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007528 }
7529
7530 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007531 synchronized (this) {
7532 mProcessObservers.unregister(observer);
7533 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007534 }
7535
Daniel Sandler69a48172010-06-23 16:29:36 -04007536 public void setImmersive(IBinder token, boolean immersive) {
7537 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007538 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007539 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007540 throw new IllegalArgumentException();
7541 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007542 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007543
7544 // update associated state if we're frontmost
7545 if (r == mFocusedActivity) {
7546 if (DEBUG_IMMERSIVE) {
7547 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7548 }
7549 applyUpdateLockStateLocked(r);
7550 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007551 }
7552 }
7553
7554 public boolean isImmersive(IBinder token) {
7555 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007556 ActivityRecord r = mMainStack.isInStackLocked(token);
7557 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007558 throw new IllegalArgumentException();
7559 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007560 return r.immersive;
7561 }
7562 }
7563
7564 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007565 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007566 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007567 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007568 return (r != null) ? r.immersive : false;
7569 }
7570 }
7571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 public final void enterSafeMode() {
7573 synchronized(this) {
7574 // It only makes sense to do this before the system is ready
7575 // and started launching other packages.
7576 if (!mSystemReady) {
7577 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007578 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 } catch (RemoteException e) {
7580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 }
7582 }
7583 }
7584
Jeff Brownb09abc12011-01-13 21:08:27 -08007585 public final void showSafeModeOverlay() {
7586 View v = LayoutInflater.from(mContext).inflate(
7587 com.android.internal.R.layout.safe_mode, null);
7588 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7589 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7590 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7591 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007592 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007593 lp.format = v.getBackground().getOpacity();
7594 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7595 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007596 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007597 ((WindowManager)mContext.getSystemService(
7598 Context.WINDOW_SERVICE)).addView(v, lp);
7599 }
7600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 public void noteWakeupAlarm(IIntentSender sender) {
7602 if (!(sender instanceof PendingIntentRecord)) {
7603 return;
7604 }
7605 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7606 synchronized (stats) {
7607 if (mBatteryStatsService.isOnBattery()) {
7608 mBatteryStatsService.enforceCallingPermission();
7609 PendingIntentRecord rec = (PendingIntentRecord)sender;
7610 int MY_UID = Binder.getCallingUid();
7611 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7612 BatteryStatsImpl.Uid.Pkg pkg =
7613 stats.getPackageStatsLocked(uid, rec.key.packageName);
7614 pkg.incWakeupsLocked();
7615 }
7616 }
7617 }
7618
Dianne Hackborn64825172011-03-02 21:32:58 -08007619 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007621 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007623 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 // XXX Note: don't acquire main activity lock here, because the window
7625 // manager calls in with its locks held.
7626
7627 boolean killed = false;
7628 synchronized (mPidsSelfLocked) {
7629 int[] types = new int[pids.length];
7630 int worstType = 0;
7631 for (int i=0; i<pids.length; i++) {
7632 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7633 if (proc != null) {
7634 int type = proc.setAdj;
7635 types[i] = type;
7636 if (type > worstType) {
7637 worstType = type;
7638 }
7639 }
7640 }
7641
Dianne Hackborn64825172011-03-02 21:32:58 -08007642 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007644 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7645 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007646 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007648
7649 // If this is not a secure call, don't let it kill processes that
7650 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007651 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7652 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007653 }
7654
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007655 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 for (int i=0; i<pids.length; i++) {
7657 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7658 if (proc == null) {
7659 continue;
7660 }
7661 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007662 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007663 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007664 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007665 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007667 proc.killedBackground = true;
7668 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 }
7670 }
7671 }
7672 return killed;
7673 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007674
7675 @Override
7676 public boolean killProcessesBelowForeground(String reason) {
7677 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7678 throw new SecurityException("killProcessesBelowForeground() only available to system");
7679 }
7680
7681 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7682 }
7683
7684 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7685 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7686 throw new SecurityException("killProcessesBelowAdj() only available to system");
7687 }
7688
7689 boolean killed = false;
7690 synchronized (mPidsSelfLocked) {
7691 final int size = mPidsSelfLocked.size();
7692 for (int i = 0; i < size; i++) {
7693 final int pid = mPidsSelfLocked.keyAt(i);
7694 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7695 if (proc == null) continue;
7696
7697 final int adj = proc.setAdj;
7698 if (adj > belowAdj && !proc.killedBackground) {
7699 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007700 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7701 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007702 killed = true;
7703 proc.killedBackground = true;
7704 Process.killProcessQuiet(pid);
7705 }
7706 }
7707 }
7708 return killed;
7709 }
7710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 public final void startRunning(String pkg, String cls, String action,
7712 String data) {
7713 synchronized(this) {
7714 if (mStartRunning) {
7715 return;
7716 }
7717 mStartRunning = true;
7718 mTopComponent = pkg != null && cls != null
7719 ? new ComponentName(pkg, cls) : null;
7720 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7721 mTopData = data;
7722 if (!mSystemReady) {
7723 return;
7724 }
7725 }
7726
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007727 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 }
7729
7730 private void retrieveSettings() {
7731 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007732 String debugApp = Settings.Global.getString(
7733 resolver, Settings.Global.DEBUG_APP);
7734 boolean waitForDebugger = Settings.Global.getInt(
7735 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7736 boolean alwaysFinishActivities = Settings.Global.getInt(
7737 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738
7739 Configuration configuration = new Configuration();
7740 Settings.System.getConfiguration(resolver, configuration);
7741
7742 synchronized (this) {
7743 mDebugApp = mOrigDebugApp = debugApp;
7744 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7745 mAlwaysFinishActivities = alwaysFinishActivities;
7746 // This happens before any activities are started, so we can
7747 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007748 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007749 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 }
7751 }
7752
7753 public boolean testIsSystemReady() {
7754 // no need to synchronize(this) just to read & return the value
7755 return mSystemReady;
7756 }
7757
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007758 private static File getCalledPreBootReceiversFile() {
7759 File dataDir = Environment.getDataDirectory();
7760 File systemDir = new File(dataDir, "system");
7761 File fname = new File(systemDir, "called_pre_boots.dat");
7762 return fname;
7763 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007764
7765 static final int LAST_DONE_VERSION = 10000;
7766
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007767 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7768 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7769 File file = getCalledPreBootReceiversFile();
7770 FileInputStream fis = null;
7771 try {
7772 fis = new FileInputStream(file);
7773 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007774 int fvers = dis.readInt();
7775 if (fvers == LAST_DONE_VERSION) {
7776 String vers = dis.readUTF();
7777 String codename = dis.readUTF();
7778 String build = dis.readUTF();
7779 if (android.os.Build.VERSION.RELEASE.equals(vers)
7780 && android.os.Build.VERSION.CODENAME.equals(codename)
7781 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7782 int num = dis.readInt();
7783 while (num > 0) {
7784 num--;
7785 String pkg = dis.readUTF();
7786 String cls = dis.readUTF();
7787 lastDoneReceivers.add(new ComponentName(pkg, cls));
7788 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007789 }
7790 }
7791 } catch (FileNotFoundException e) {
7792 } catch (IOException e) {
7793 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7794 } finally {
7795 if (fis != null) {
7796 try {
7797 fis.close();
7798 } catch (IOException e) {
7799 }
7800 }
7801 }
7802 return lastDoneReceivers;
7803 }
7804
7805 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7806 File file = getCalledPreBootReceiversFile();
7807 FileOutputStream fos = null;
7808 DataOutputStream dos = null;
7809 try {
7810 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7811 fos = new FileOutputStream(file);
7812 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007813 dos.writeInt(LAST_DONE_VERSION);
7814 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007815 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007816 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007817 dos.writeInt(list.size());
7818 for (int i=0; i<list.size(); i++) {
7819 dos.writeUTF(list.get(i).getPackageName());
7820 dos.writeUTF(list.get(i).getClassName());
7821 }
7822 } catch (IOException e) {
7823 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7824 file.delete();
7825 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007826 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007827 if (dos != null) {
7828 try {
7829 dos.close();
7830 } catch (IOException e) {
7831 // TODO Auto-generated catch block
7832 e.printStackTrace();
7833 }
7834 }
7835 }
7836 }
7837
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007838 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 synchronized(this) {
7840 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007841 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 return;
7843 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007844
7845 // Check to see if there are any update receivers to run.
7846 if (!mDidUpdate) {
7847 if (mWaitingUpdate) {
7848 return;
7849 }
7850 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7851 List<ResolveInfo> ris = null;
7852 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007853 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007854 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007855 } catch (RemoteException e) {
7856 }
7857 if (ris != null) {
7858 for (int i=ris.size()-1; i>=0; i--) {
7859 if ((ris.get(i).activityInfo.applicationInfo.flags
7860 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7861 ris.remove(i);
7862 }
7863 }
7864 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007865
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007866 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007867
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007868 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007869 for (int i=0; i<ris.size(); i++) {
7870 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007871 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7872 if (lastDoneReceivers.contains(comp)) {
7873 ris.remove(i);
7874 i--;
7875 }
7876 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007877
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007878 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007879 for (int i=0; i<ris.size(); i++) {
7880 ActivityInfo ai = ris.get(i).activityInfo;
7881 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7882 doneReceivers.add(comp);
7883 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007884 for (int j=0; j<users.length; j++) {
7885 IIntentReceiver finisher = null;
7886 if (i == ris.size()-1 && j == users.length-1) {
7887 finisher = new IIntentReceiver.Stub() {
7888 public void performReceive(Intent intent, int resultCode,
7889 String data, Bundle extras, boolean ordered,
7890 boolean sticky, int sendingUser) {
7891 // The raw IIntentReceiver interface is called
7892 // with the AM lock held, so redispatch to
7893 // execute our code without the lock.
7894 mHandler.post(new Runnable() {
7895 public void run() {
7896 synchronized (ActivityManagerService.this) {
7897 mDidUpdate = true;
7898 }
7899 writeLastDonePreBootReceivers(doneReceivers);
7900 showBootMessage(mContext.getText(
7901 R.string.android_upgrading_complete),
7902 false);
7903 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007904 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007905 });
7906 }
7907 };
7908 }
7909 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7910 + " for user " + users[j]);
7911 broadcastIntentLocked(null, null, intent, null, finisher,
7912 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
7913 users[j]);
7914 if (finisher != null) {
7915 mWaitingUpdate = true;
7916 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007917 }
7918 }
7919 }
7920 if (mWaitingUpdate) {
7921 return;
7922 }
7923 mDidUpdate = true;
7924 }
7925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 mSystemReady = true;
7927 if (!mStartRunning) {
7928 return;
7929 }
7930 }
7931
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007932 ArrayList<ProcessRecord> procsToKill = null;
7933 synchronized(mPidsSelfLocked) {
7934 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7935 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7936 if (!isAllowedWhileBooting(proc.info)){
7937 if (procsToKill == null) {
7938 procsToKill = new ArrayList<ProcessRecord>();
7939 }
7940 procsToKill.add(proc);
7941 }
7942 }
7943 }
7944
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007945 synchronized(this) {
7946 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007947 for (int i=procsToKill.size()-1; i>=0; i--) {
7948 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007949 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007950 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007951 }
7952 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007953
7954 // Now that we have cleaned up any update processes, we
7955 // are ready to start launching real processes and know that
7956 // we won't trample on them any more.
7957 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007958 }
7959
Joe Onorato8a9b2202010-02-26 18:56:32 -08007960 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007961 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 SystemClock.uptimeMillis());
7963
7964 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007965 // Make sure we have no pre-ready processes sitting around.
7966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7968 ResolveInfo ri = mContext.getPackageManager()
7969 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007970 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 CharSequence errorMsg = null;
7972 if (ri != null) {
7973 ActivityInfo ai = ri.activityInfo;
7974 ApplicationInfo app = ai.applicationInfo;
7975 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7976 mTopAction = Intent.ACTION_FACTORY_TEST;
7977 mTopData = null;
7978 mTopComponent = new ComponentName(app.packageName,
7979 ai.name);
7980 } else {
7981 errorMsg = mContext.getResources().getText(
7982 com.android.internal.R.string.factorytest_not_system);
7983 }
7984 } else {
7985 errorMsg = mContext.getResources().getText(
7986 com.android.internal.R.string.factorytest_no_action);
7987 }
7988 if (errorMsg != null) {
7989 mTopAction = null;
7990 mTopData = null;
7991 mTopComponent = null;
7992 Message msg = Message.obtain();
7993 msg.what = SHOW_FACTORY_ERROR_MSG;
7994 msg.getData().putCharSequence("msg", errorMsg);
7995 mHandler.sendMessage(msg);
7996 }
7997 }
7998 }
7999
8000 retrieveSettings();
8001
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008002 if (goingCallback != null) goingCallback.run();
8003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 synchronized (this) {
8005 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8006 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008007 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008008 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 if (apps != null) {
8010 int N = apps.size();
8011 int i;
8012 for (i=0; i<N; i++) {
8013 ApplicationInfo info
8014 = (ApplicationInfo)apps.get(i);
8015 if (info != null &&
8016 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008017 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008018 }
8019 }
8020 }
8021 } catch (RemoteException ex) {
8022 // pm is in same process, this will never happen.
8023 }
8024 }
8025
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008026 // Start up initial activity.
8027 mBooting = true;
8028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008030 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 Message msg = Message.obtain();
8032 msg.what = SHOW_UID_ERROR_MSG;
8033 mHandler.sendMessage(msg);
8034 }
8035 } catch (RemoteException e) {
8036 }
8037
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008038 long ident = Binder.clearCallingIdentity();
8039 try {
8040 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008041 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
8042 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008043 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8044 broadcastIntentLocked(null, null, intent,
8045 null, null, 0, null, null, null,
8046 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008047 intent = new Intent(Intent.ACTION_USER_STARTING);
8048 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8049 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8050 broadcastIntentLocked(null, null, intent,
8051 null, new IIntentReceiver.Stub() {
8052 @Override
8053 public void performReceive(Intent intent, int resultCode, String data,
8054 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
8055 throws RemoteException {
8056 }
8057 }, 0, null, null,
8058 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08008059 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008060 } finally {
8061 Binder.restoreCallingIdentity(ident);
8062 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008063 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008064 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 }
8066 }
8067
Dan Egnorb7f03672009-12-09 16:22:32 -08008068 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008069 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008071 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008072 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 startAppProblemLocked(app);
8074 app.stopFreezingAllLocked();
8075 return handleAppCrashLocked(app);
8076 }
8077
Dan Egnorb7f03672009-12-09 16:22:32 -08008078 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008079 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008081 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008082 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8083 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 startAppProblemLocked(app);
8085 app.stopFreezingAllLocked();
8086 }
8087
8088 /**
8089 * Generate a process error record, suitable for attachment to a ProcessRecord.
8090 *
8091 * @param app The ProcessRecord in which the error occurred.
8092 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8093 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008094 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 * @param shortMsg Short message describing the crash.
8096 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008097 * @param stackTrace Full crash stack trace, may be null.
8098 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 * @return Returns a fully-formed AppErrorStateInfo record.
8100 */
8101 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008102 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 report.condition = condition;
8106 report.processName = app.processName;
8107 report.pid = app.pid;
8108 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008109 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 report.shortMsg = shortMsg;
8111 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008112 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008113
8114 return report;
8115 }
8116
Dan Egnor42471dd2010-01-07 17:25:22 -08008117 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118 synchronized (this) {
8119 app.crashing = false;
8120 app.crashingReport = null;
8121 app.notResponding = false;
8122 app.notRespondingReport = null;
8123 if (app.anrDialog == fromDialog) {
8124 app.anrDialog = null;
8125 }
8126 if (app.waitDialog == fromDialog) {
8127 app.waitDialog = null;
8128 }
8129 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008130 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008131 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008132 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008133 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008134 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008136 }
8137 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008138
Dan Egnorb7f03672009-12-09 16:22:32 -08008139 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008140 if (mHeadless) {
8141 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8142 return false;
8143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008144 long now = SystemClock.uptimeMillis();
8145
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008146 Long crashTime;
8147 if (!app.isolated) {
8148 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8149 } else {
8150 crashTime = null;
8151 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008152 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008154 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008155 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008156 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008157 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008158 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8159 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008161 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008163 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8164 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 }
8166 }
8167 if (!app.persistent) {
8168 // We don't want to start this process again until the user
8169 // explicitly does so... but for persistent process, we really
8170 // need to keep it running. If a persistent process is actually
8171 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008172 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008174 if (!app.isolated) {
8175 // XXX We don't have a way to mark isolated processes
8176 // as bad, since they don't have a peristent identity.
8177 mBadProcesses.put(app.info.processName, app.uid, now);
8178 mProcessCrashTimes.remove(app.info.processName, app.uid);
8179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008181 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008182 // Don't let services in this process be restarted and potentially
8183 // annoy the user repeatedly. Unless it is persistent, since those
8184 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008185 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008186 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 return false;
8188 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008189 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008190 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008191 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008192 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008193 // If the top running activity is from this crashing
8194 // process, then terminate it to avoid getting in a loop.
8195 Slog.w(TAG, " Force finishing activity "
8196 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008197 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008198 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008199 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008200 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008201 // stopped, to avoid a situation where one will get
8202 // re-start our crashing activity once it gets resumed again.
8203 index--;
8204 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008205 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008206 if (r.state == ActivityState.RESUMED
8207 || r.state == ActivityState.PAUSING
8208 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008209 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008210 Slog.w(TAG, " Force finishing activity "
8211 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008212 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008213 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008214 }
8215 }
8216 }
8217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 }
8219
8220 // Bump up the crash count of any services currently running in the proc.
8221 if (app.services.size() != 0) {
8222 // Any services running in the application need to be placed
8223 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008224 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008226 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008227 sr.crashCount++;
8228 }
8229 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008230
8231 // If the crashing process is what we consider to be the "home process" and it has been
8232 // replaced by a third-party app, clear the package preferred activities from packages
8233 // with a home activity running in the process to prevent a repeatedly crashing app
8234 // from blocking the user to manually clear the list.
8235 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8236 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8237 Iterator it = mHomeProcess.activities.iterator();
8238 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008239 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008240 if (r.isHomeActivity) {
8241 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8242 try {
8243 ActivityThread.getPackageManager()
8244 .clearPackagePreferredActivities(r.packageName);
8245 } catch (RemoteException c) {
8246 // pm is in same process, this will never happen.
8247 }
8248 }
8249 }
8250 }
8251
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008252 if (!app.isolated) {
8253 // XXX Can't keep track of crash times for isolated processes,
8254 // because they don't have a perisistent identity.
8255 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8256 }
8257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 return true;
8259 }
8260
8261 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008262 if (app.userId == mCurrentUserId) {
8263 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8264 mContext, app.info.packageName, app.info.flags);
8265 } else {
8266 // If this app is not running under the current user, then we
8267 // can't give it a report button because that would require
8268 // launching the report UI under a different user.
8269 app.errorReportReceiver = null;
8270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 skipCurrentReceiverLocked(app);
8272 }
8273
8274 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008275 for (BroadcastQueue queue : mBroadcastQueues) {
8276 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008277 }
8278 }
8279
Dan Egnor60d87622009-12-16 16:32:58 -08008280 /**
8281 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8282 * The application process will exit immediately after this call returns.
8283 * @param app object of the crashing app, null for the system server
8284 * @param crashInfo describing the exception
8285 */
8286 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008287 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008288 final String processName = app == null ? "system_server"
8289 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008290
8291 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008292 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008293 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008294 crashInfo.exceptionClassName,
8295 crashInfo.exceptionMessage,
8296 crashInfo.throwFileName,
8297 crashInfo.throwLineNumber);
8298
Jeff Sharkeya353d262011-10-28 11:12:06 -07008299 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008300
8301 crashApplication(r, crashInfo);
8302 }
8303
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008304 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008305 IBinder app,
8306 int violationMask,
8307 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008308 ProcessRecord r = findAppProcess(app, "StrictMode");
8309 if (r == null) {
8310 return;
8311 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008312
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008313 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008314 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008315 boolean logIt = true;
8316 synchronized (mAlreadyLoggedViolatedStacks) {
8317 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8318 logIt = false;
8319 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008320 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008321 // the relative pain numbers, without logging all
8322 // the stack traces repeatedly. We'd want to do
8323 // likewise in the client code, which also does
8324 // dup suppression, before the Binder call.
8325 } else {
8326 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8327 mAlreadyLoggedViolatedStacks.clear();
8328 }
8329 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8330 }
8331 }
8332 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008333 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008334 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008335 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008336
8337 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8338 AppErrorResult result = new AppErrorResult();
8339 synchronized (this) {
8340 final long origId = Binder.clearCallingIdentity();
8341
8342 Message msg = Message.obtain();
8343 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8344 HashMap<String, Object> data = new HashMap<String, Object>();
8345 data.put("result", result);
8346 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008347 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008348 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008349 msg.obj = data;
8350 mHandler.sendMessage(msg);
8351
8352 Binder.restoreCallingIdentity(origId);
8353 }
8354 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008355 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008356 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008357 }
8358
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008359 // Depending on the policy in effect, there could be a bunch of
8360 // these in quick succession so we try to batch these together to
8361 // minimize disk writes, number of dropbox entries, and maximize
8362 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008363 private void logStrictModeViolationToDropBox(
8364 ProcessRecord process,
8365 StrictMode.ViolationInfo info) {
8366 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008367 return;
8368 }
8369 final boolean isSystemApp = process == null ||
8370 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8371 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008372 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008373 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8374 final DropBoxManager dbox = (DropBoxManager)
8375 mContext.getSystemService(Context.DROPBOX_SERVICE);
8376
8377 // Exit early if the dropbox isn't configured to accept this report type.
8378 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8379
8380 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008381 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008382 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8383 synchronized (sb) {
8384 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008385 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008386 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8387 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008388 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8389 if (info.violationNumThisLoop != 0) {
8390 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8391 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008392 if (info.numAnimationsRunning != 0) {
8393 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8394 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008395 if (info.broadcastIntentAction != null) {
8396 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8397 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008398 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008399 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008400 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008401 if (info.numInstances != -1) {
8402 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8403 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008404 if (info.tags != null) {
8405 for (String tag : info.tags) {
8406 sb.append("Span-Tag: ").append(tag).append("\n");
8407 }
8408 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008409 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008410 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8411 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008412 }
8413 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008414
8415 // Only buffer up to ~64k. Various logging bits truncate
8416 // things at 128k.
8417 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008418 }
8419
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008420 // Flush immediately if the buffer's grown too large, or this
8421 // is a non-system app. Non-system apps are isolated with a
8422 // different tag & policy and not batched.
8423 //
8424 // Batching is useful during internal testing with
8425 // StrictMode settings turned up high. Without batching,
8426 // thousands of separate files could be created on boot.
8427 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008428 new Thread("Error dump: " + dropboxTag) {
8429 @Override
8430 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008431 String report;
8432 synchronized (sb) {
8433 report = sb.toString();
8434 sb.delete(0, sb.length());
8435 sb.trimToSize();
8436 }
8437 if (report.length() != 0) {
8438 dbox.addText(dropboxTag, report);
8439 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008440 }
8441 }.start();
8442 return;
8443 }
8444
8445 // System app batching:
8446 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008447 // An existing dropbox-writing thread is outstanding, so
8448 // we don't need to start it up. The existing thread will
8449 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008450 return;
8451 }
8452
8453 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8454 // (After this point, we shouldn't access AMS internal data structures.)
8455 new Thread("Error dump: " + dropboxTag) {
8456 @Override
8457 public void run() {
8458 // 5 second sleep to let stacks arrive and be batched together
8459 try {
8460 Thread.sleep(5000); // 5 seconds
8461 } catch (InterruptedException e) {}
8462
8463 String errorReport;
8464 synchronized (mStrictModeBuffer) {
8465 errorReport = mStrictModeBuffer.toString();
8466 if (errorReport.length() == 0) {
8467 return;
8468 }
8469 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8470 mStrictModeBuffer.trimToSize();
8471 }
8472 dbox.addText(dropboxTag, errorReport);
8473 }
8474 }.start();
8475 }
8476
Dan Egnor60d87622009-12-16 16:32:58 -08008477 /**
8478 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8479 * @param app object of the crashing app, null for the system server
8480 * @param tag reported by the caller
8481 * @param crashInfo describing the context of the error
8482 * @return true if the process should exit immediately (WTF is fatal)
8483 */
8484 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008485 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008486 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008487 final String processName = app == null ? "system_server"
8488 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008489
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008490 EventLog.writeEvent(EventLogTags.AM_WTF,
8491 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008492 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008493 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008494 tag, crashInfo.exceptionMessage);
8495
Jeff Sharkeya353d262011-10-28 11:12:06 -07008496 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008497
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008498 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008499 Settings.Global.getInt(mContext.getContentResolver(),
8500 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008501 crashApplication(r, crashInfo);
8502 return true;
8503 } else {
8504 return false;
8505 }
8506 }
8507
8508 /**
8509 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8510 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8511 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008512 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008513 if (app == null) {
8514 return null;
8515 }
8516
8517 synchronized (this) {
8518 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8519 final int NA = apps.size();
8520 for (int ia=0; ia<NA; ia++) {
8521 ProcessRecord p = apps.valueAt(ia);
8522 if (p.thread != null && p.thread.asBinder() == app) {
8523 return p;
8524 }
8525 }
8526 }
8527
Dianne Hackborncb44d962011-03-10 17:02:27 -08008528 Slog.w(TAG, "Can't find mystery application for " + reason
8529 + " from pid=" + Binder.getCallingPid()
8530 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008531 return null;
8532 }
8533 }
8534
8535 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008536 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8537 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008538 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008539 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8540 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008541 // Watchdog thread ends up invoking this function (with
8542 // a null ProcessRecord) to add the stack file to dropbox.
8543 // Do not acquire a lock on this (am) in such cases, as it
8544 // could cause a potential deadlock, if and when watchdog
8545 // is invoked due to unavailability of lock on am and it
8546 // would prevent watchdog from killing system_server.
8547 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008548 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008549 return;
8550 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008551 // Note: ProcessRecord 'process' is guarded by the service
8552 // instance. (notably process.pkgList, which could otherwise change
8553 // concurrently during execution of this method)
8554 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008555 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008556 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008557 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008558 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8559 for (String pkg : process.pkgList) {
8560 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008561 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008562 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008563 if (pi != null) {
8564 sb.append(" v").append(pi.versionCode);
8565 if (pi.versionName != null) {
8566 sb.append(" (").append(pi.versionName).append(")");
8567 }
8568 }
8569 } catch (RemoteException e) {
8570 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008571 }
Dan Egnora455d192010-03-12 08:52:28 -08008572 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008573 }
Dan Egnora455d192010-03-12 08:52:28 -08008574 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008575 }
8576
8577 private static String processClass(ProcessRecord process) {
8578 if (process == null || process.pid == MY_PID) {
8579 return "system_server";
8580 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8581 return "system_app";
8582 } else {
8583 return "data_app";
8584 }
8585 }
8586
8587 /**
8588 * Write a description of an error (crash, WTF, ANR) to the drop box.
8589 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8590 * @param process which caused the error, null means the system server
8591 * @param activity which triggered the error, null if unknown
8592 * @param parent activity related to the error, null if unknown
8593 * @param subject line related to the error, null if absent
8594 * @param report in long form describing the error, null if absent
8595 * @param logFile to include in the report, null if none
8596 * @param crashInfo giving an application stack trace, null if absent
8597 */
8598 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008599 ProcessRecord process, String processName, ActivityRecord activity,
8600 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008601 final String report, final File logFile,
8602 final ApplicationErrorReport.CrashInfo crashInfo) {
8603 // NOTE -- this must never acquire the ActivityManagerService lock,
8604 // otherwise the watchdog may be prevented from resetting the system.
8605
8606 final String dropboxTag = processClass(process) + "_" + eventType;
8607 final DropBoxManager dbox = (DropBoxManager)
8608 mContext.getSystemService(Context.DROPBOX_SERVICE);
8609
8610 // Exit early if the dropbox isn't configured to accept this report type.
8611 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8612
8613 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008614 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008615 if (activity != null) {
8616 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8617 }
8618 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8619 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8620 }
8621 if (parent != null && parent != activity) {
8622 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8623 }
8624 if (subject != null) {
8625 sb.append("Subject: ").append(subject).append("\n");
8626 }
8627 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008628 if (Debug.isDebuggerConnected()) {
8629 sb.append("Debugger: Connected\n");
8630 }
Dan Egnora455d192010-03-12 08:52:28 -08008631 sb.append("\n");
8632
8633 // Do the rest in a worker thread to avoid blocking the caller on I/O
8634 // (After this point, we shouldn't access AMS internal data structures.)
8635 Thread worker = new Thread("Error dump: " + dropboxTag) {
8636 @Override
8637 public void run() {
8638 if (report != null) {
8639 sb.append(report);
8640 }
8641 if (logFile != null) {
8642 try {
8643 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8644 } catch (IOException e) {
8645 Slog.e(TAG, "Error reading " + logFile, e);
8646 }
8647 }
8648 if (crashInfo != null && crashInfo.stackTrace != null) {
8649 sb.append(crashInfo.stackTrace);
8650 }
8651
Jeff Sharkey625239a2012-09-26 22:03:49 -07008652 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8653 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008654 if (lines > 0) {
8655 sb.append("\n");
8656
8657 // Merge several logcat streams, and take the last N lines
8658 InputStreamReader input = null;
8659 try {
8660 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8661 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8662 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8663
8664 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8665 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8666 input = new InputStreamReader(logcat.getInputStream());
8667
8668 int num;
8669 char[] buf = new char[8192];
8670 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8671 } catch (IOException e) {
8672 Slog.e(TAG, "Error running logcat", e);
8673 } finally {
8674 if (input != null) try { input.close(); } catch (IOException e) {}
8675 }
8676 }
8677
8678 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008679 }
Dan Egnora455d192010-03-12 08:52:28 -08008680 };
8681
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008682 if (process == null) {
8683 // If process is null, we are being called from some internal code
8684 // and may be about to die -- run this synchronously.
8685 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008686 } else {
8687 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008688 }
8689 }
8690
8691 /**
8692 * Bring up the "unexpected error" dialog box for a crashing app.
8693 * Deal with edge cases (intercepts from instrumented applications,
8694 * ActivityController, error intent receivers, that sort of thing).
8695 * @param r the application crashing
8696 * @param crashInfo describing the failure
8697 */
8698 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008699 long timeMillis = System.currentTimeMillis();
8700 String shortMsg = crashInfo.exceptionClassName;
8701 String longMsg = crashInfo.exceptionMessage;
8702 String stackTrace = crashInfo.stackTrace;
8703 if (shortMsg != null && longMsg != null) {
8704 longMsg = shortMsg + ": " + longMsg;
8705 } else if (shortMsg != null) {
8706 longMsg = shortMsg;
8707 }
8708
Dan Egnor60d87622009-12-16 16:32:58 -08008709 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008711 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008712 try {
8713 String name = r != null ? r.processName : null;
8714 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008715 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008716 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008717 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 + " at watcher's request");
8719 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008720 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721 }
8722 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008723 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008724 }
8725 }
8726
8727 final long origId = Binder.clearCallingIdentity();
8728
8729 // If this process is running instrumentation, finish it.
8730 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008731 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008733 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8734 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008735 Bundle info = new Bundle();
8736 info.putString("shortMsg", shortMsg);
8737 info.putString("longMsg", longMsg);
8738 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8739 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008740 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 }
8742
Dan Egnor60d87622009-12-16 16:32:58 -08008743 // If we can't identify the process or it's already exceeded its crash quota,
8744 // quit right away without showing a crash dialog.
8745 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008747 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 }
8749
8750 Message msg = Message.obtain();
8751 msg.what = SHOW_ERROR_MSG;
8752 HashMap data = new HashMap();
8753 data.put("result", result);
8754 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755 msg.obj = data;
8756 mHandler.sendMessage(msg);
8757
8758 Binder.restoreCallingIdentity(origId);
8759 }
8760
8761 int res = result.get();
8762
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008763 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008765 if (r != null && !r.isolated) {
8766 // XXX Can't keep track of crash time for isolated processes,
8767 // since they don't have a persistent identity.
8768 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 SystemClock.uptimeMillis());
8770 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008771 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008772 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008773 }
8774 }
8775
8776 if (appErrorIntent != null) {
8777 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008778 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008779 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008780 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008784
8785 Intent createAppErrorIntentLocked(ProcessRecord r,
8786 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8787 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008788 if (report == null) {
8789 return null;
8790 }
8791 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8792 result.setComponent(r.errorReportReceiver);
8793 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8794 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8795 return result;
8796 }
8797
Dan Egnorb7f03672009-12-09 16:22:32 -08008798 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8799 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008800 if (r.errorReportReceiver == null) {
8801 return null;
8802 }
8803
8804 if (!r.crashing && !r.notResponding) {
8805 return null;
8806 }
8807
Dan Egnorb7f03672009-12-09 16:22:32 -08008808 ApplicationErrorReport report = new ApplicationErrorReport();
8809 report.packageName = r.info.packageName;
8810 report.installerPackageName = r.errorReportReceiver.getPackageName();
8811 report.processName = r.processName;
8812 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008813 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008814
Dan Egnorb7f03672009-12-09 16:22:32 -08008815 if (r.crashing) {
8816 report.type = ApplicationErrorReport.TYPE_CRASH;
8817 report.crashInfo = crashInfo;
8818 } else if (r.notResponding) {
8819 report.type = ApplicationErrorReport.TYPE_ANR;
8820 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008821
Dan Egnorb7f03672009-12-09 16:22:32 -08008822 report.anrInfo.activity = r.notRespondingReport.tag;
8823 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8824 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008825 }
8826
Dan Egnorb7f03672009-12-09 16:22:32 -08008827 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008828 }
8829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008830 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008831 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 // assume our apps are happy - lazy create the list
8833 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8834
Dianne Hackborn0c380492012-08-20 17:23:30 -07008835 final boolean allUsers = ActivityManager.checkUidPermission(
8836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8837 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8838 int userId = UserHandle.getUserId(Binder.getCallingUid());
8839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008840 synchronized (this) {
8841
8842 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008843 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8844 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008845 if (!allUsers && app.userId != userId) {
8846 continue;
8847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8849 // This one's in trouble, so we'll generate a report for it
8850 // crashes are higher priority (in case there's a crash *and* an anr)
8851 ActivityManager.ProcessErrorStateInfo report = null;
8852 if (app.crashing) {
8853 report = app.crashingReport;
8854 } else if (app.notResponding) {
8855 report = app.notRespondingReport;
8856 }
8857
8858 if (report != null) {
8859 if (errList == null) {
8860 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8861 }
8862 errList.add(report);
8863 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008864 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 " crashing = " + app.crashing +
8866 " notResponding = " + app.notResponding);
8867 }
8868 }
8869 }
8870 }
8871
8872 return errList;
8873 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008874
8875 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008876 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008877 if (currApp != null) {
8878 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8879 }
8880 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008881 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8882 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008883 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8884 if (currApp != null) {
8885 currApp.lru = 0;
8886 }
8887 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008888 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008889 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8890 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8891 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8892 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8893 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8894 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8895 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8896 } else {
8897 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8898 }
8899 }
8900
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008901 private void fillInProcMemInfo(ProcessRecord app,
8902 ActivityManager.RunningAppProcessInfo outInfo) {
8903 outInfo.pid = app.pid;
8904 outInfo.uid = app.info.uid;
8905 if (mHeavyWeightProcess == app) {
8906 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8907 }
8908 if (app.persistent) {
8909 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8910 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008911 if (app.hasActivities) {
8912 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8913 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008914 outInfo.lastTrimLevel = app.trimMemoryLevel;
8915 int adj = app.curAdj;
8916 outInfo.importance = oomAdjToImportance(adj, outInfo);
8917 outInfo.importanceReasonCode = app.adjTypeCode;
8918 }
8919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008921 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 // Lazy instantiation of list
8923 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008924 final boolean allUsers = ActivityManager.checkUidPermission(
8925 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8926 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8927 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 synchronized (this) {
8929 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008930 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8931 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008932 if (!allUsers && app.userId != userId) {
8933 continue;
8934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8936 // Generate process state info for running application
8937 ActivityManager.RunningAppProcessInfo currApp =
8938 new ActivityManager.RunningAppProcessInfo(app.processName,
8939 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008940 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008941 if (app.adjSource instanceof ProcessRecord) {
8942 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008943 currApp.importanceReasonImportance = oomAdjToImportance(
8944 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008945 } else if (app.adjSource instanceof ActivityRecord) {
8946 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008947 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8948 }
8949 if (app.adjTarget instanceof ComponentName) {
8950 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8951 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008952 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 // + " lru=" + currApp.lru);
8954 if (runList == null) {
8955 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8956 }
8957 runList.add(currApp);
8958 }
8959 }
8960 }
8961 return runList;
8962 }
8963
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008964 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008965 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008966 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8967 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8968 if (runningApps != null && runningApps.size() > 0) {
8969 Set<String> extList = new HashSet<String>();
8970 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8971 if (app.pkgList != null) {
8972 for (String pkg : app.pkgList) {
8973 extList.add(pkg);
8974 }
8975 }
8976 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008977 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008978 for (String pkg : extList) {
8979 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008980 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008981 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8982 retList.add(info);
8983 }
8984 } catch (RemoteException e) {
8985 }
8986 }
8987 }
8988 return retList;
8989 }
8990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008992 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8993 enforceNotIsolatedCaller("getMyMemoryState");
8994 synchronized (this) {
8995 ProcessRecord proc;
8996 synchronized (mPidsSelfLocked) {
8997 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8998 }
8999 fillInProcMemInfo(proc, outInfo);
9000 }
9001 }
9002
9003 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005 if (checkCallingPermission(android.Manifest.permission.DUMP)
9006 != PackageManager.PERMISSION_GRANTED) {
9007 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9008 + Binder.getCallingPid()
9009 + ", uid=" + Binder.getCallingUid()
9010 + " without permission "
9011 + android.Manifest.permission.DUMP);
9012 return;
9013 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009014
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009016 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018
9019 int opti = 0;
9020 while (opti < args.length) {
9021 String opt = args[opti];
9022 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9023 break;
9024 }
9025 opti++;
9026 if ("-a".equals(opt)) {
9027 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 } else if ("-c".equals(opt)) {
9029 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009030 } else if ("-h".equals(opt)) {
9031 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009033 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009034 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009035 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009036 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
9037 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009038 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009039 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08009040 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009041 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009042 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009043 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009044 pw.println(" all: dump all activities");
9045 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009047 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
9048 pw.println(" a partial substring in a component name, a");
9049 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009050 pw.println(" -a: include all available server state.");
9051 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053 } else {
9054 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009057
9058 long origId = Binder.clearCallingIdentity();
9059 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060 // Is the caller requesting to dump a particular piece of data?
9061 if (opti < args.length) {
9062 String cmd = args[opti];
9063 opti++;
9064 if ("activities".equals(cmd) || "a".equals(cmd)) {
9065 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009066 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009069 String[] newArgs;
9070 String name;
9071 if (opti >= args.length) {
9072 name = null;
9073 newArgs = EMPTY_STRING_ARRAY;
9074 } else {
9075 name = args[opti];
9076 opti++;
9077 newArgs = new String[args.length - opti];
9078 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9079 args.length - opti);
9080 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009082 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009083 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009085 String[] newArgs;
9086 String name;
9087 if (opti >= args.length) {
9088 name = null;
9089 newArgs = EMPTY_STRING_ARRAY;
9090 } else {
9091 name = args[opti];
9092 opti++;
9093 newArgs = new String[args.length - opti];
9094 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9095 args.length - opti);
9096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009101 String[] newArgs;
9102 String name;
9103 if (opti >= args.length) {
9104 name = null;
9105 newArgs = EMPTY_STRING_ARRAY;
9106 } else {
9107 name = args[opti];
9108 opti++;
9109 newArgs = new String[args.length - opti];
9110 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9111 args.length - opti);
9112 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009113 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009114 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009115 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009116 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9117 synchronized (this) {
9118 dumpOomLocked(fd, pw, args, opti, true);
9119 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009120 } else if ("provider".equals(cmd)) {
9121 String[] newArgs;
9122 String name;
9123 if (opti >= args.length) {
9124 name = null;
9125 newArgs = EMPTY_STRING_ARRAY;
9126 } else {
9127 name = args[opti];
9128 opti++;
9129 newArgs = new String[args.length - opti];
9130 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9131 }
9132 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9133 pw.println("No providers match: " + name);
9134 pw.println("Use -h for help.");
9135 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009136 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9137 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009139 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009141 String[] newArgs;
9142 String name;
9143 if (opti >= args.length) {
9144 name = null;
9145 newArgs = EMPTY_STRING_ARRAY;
9146 } else {
9147 name = args[opti];
9148 opti++;
9149 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009150 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9151 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009153 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009154 pw.println("No services match: " + name);
9155 pw.println("Use -h for help.");
9156 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009157 } else if ("package".equals(cmd)) {
9158 String[] newArgs;
9159 if (opti >= args.length) {
9160 pw.println("package: no package name specified");
9161 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 } else {
9163 dumpPackage = args[opti];
9164 opti++;
9165 newArgs = new String[args.length - opti];
9166 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9167 args.length - opti);
9168 args = newArgs;
9169 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009170 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009171 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9173 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009174 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009176 } else {
9177 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9179 pw.println("Bad activity command, or no activities match: " + cmd);
9180 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009181 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009182 }
9183 if (!more) {
9184 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009185 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009187 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009188
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009189 // No piece of data specified, dump everything.
9190 synchronized (this) {
9191 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009192 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009193 if (needSep) {
9194 pw.println(" ");
9195 }
9196 if (dumpAll) {
9197 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009198 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009200 if (needSep) {
9201 pw.println(" ");
9202 }
9203 if (dumpAll) {
9204 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009206 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009207 if (needSep) {
9208 pw.println(" ");
9209 }
9210 if (dumpAll) {
9211 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009213 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214 if (needSep) {
9215 pw.println(" ");
9216 }
9217 if (dumpAll) {
9218 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009219 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009220 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009221 if (needSep) {
9222 pw.println(" ");
9223 }
9224 if (dumpAll) {
9225 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009226 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009227 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009228 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009229 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009231
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009232 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009233 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009234 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9235 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009236 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9237 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 pw.println(" ");
9239 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009240 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9241 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009242 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009244 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009245 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009246 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009247 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009248 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009251 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009252 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009253 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009254 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9255 pw.println(" ");
9256 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009257 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009258 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009259 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009260 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 pw.println(" ");
9262 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009263 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009264 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009267 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009268 if (mMainStack.mPausingActivity != null) {
9269 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009271 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009273 if (dumpAll) {
9274 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9275 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009276 pw.println(" mDismissKeyguardOnNextActivity: "
9277 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009279
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009280 if (mRecentTasks.size() > 0) {
9281 pw.println();
9282 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009283
9284 final int N = mRecentTasks.size();
9285 for (int i=0; i<N; i++) {
9286 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009287 if (dumpPackage != null) {
9288 if (tr.realActivity == null ||
9289 !dumpPackage.equals(tr.realActivity)) {
9290 continue;
9291 }
9292 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009293 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9294 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009295 if (dumpAll) {
9296 mRecentTasks.get(i).dump(pw, " ");
9297 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009298 }
9299 }
9300
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 if (dumpAll) {
9302 pw.println(" ");
9303 pw.println(" mCurTask: " + mCurTask);
9304 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305
9306 return true;
9307 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009308
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009311 boolean needSep = false;
9312 int numPers = 0;
9313
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009314 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9315
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9318 final int NA = procs.size();
9319 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009320 ProcessRecord r = procs.valueAt(ia);
9321 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9322 continue;
9323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 if (!needSep) {
9325 pw.println(" All known processes:");
9326 needSep = true;
9327 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009328 pw.print(r.persistent ? " *PERS*" : " *APP*");
9329 pw.print(" UID "); pw.print(procs.keyAt(ia));
9330 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 r.dump(pw, " ");
9332 if (r.persistent) {
9333 numPers++;
9334 }
9335 }
9336 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009337 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009338
9339 if (mIsolatedProcesses.size() > 0) {
9340 if (needSep) pw.println(" ");
9341 needSep = true;
9342 pw.println(" Isolated process list (sorted by uid):");
9343 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9344 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9345 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9346 continue;
9347 }
9348 pw.println(String.format("%sIsolated #%2d: %s",
9349 " ", i, r.toString()));
9350 }
9351 }
9352
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009353 if (mLruProcesses.size() > 0) {
9354 if (needSep) pw.println(" ");
9355 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009356 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009357 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009358 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009359 needSep = true;
9360 }
9361
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009362 if (dumpAll) {
9363 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009364 boolean printed = false;
9365 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9366 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9367 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9368 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009369 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009370 if (!printed) {
9371 if (needSep) pw.println(" ");
9372 needSep = true;
9373 pw.println(" PID mappings:");
9374 printed = true;
9375 }
9376 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9377 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 }
9379 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009380 }
9381
9382 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009383 synchronized (mPidsSelfLocked) {
9384 boolean printed = false;
9385 for (int i=0; i<mForegroundProcesses.size(); i++) {
9386 ProcessRecord r = mPidsSelfLocked.get(
9387 mForegroundProcesses.valueAt(i).pid);
9388 if (dumpPackage != null && (r == null
9389 || !dumpPackage.equals(r.info.packageName))) {
9390 continue;
9391 }
9392 if (!printed) {
9393 if (needSep) pw.println(" ");
9394 needSep = true;
9395 pw.println(" Foreground Processes:");
9396 printed = true;
9397 }
9398 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9399 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 }
9403
9404 if (mPersistentStartingProcesses.size() > 0) {
9405 if (needSep) pw.println(" ");
9406 needSep = true;
9407 pw.println(" Persisent processes that are starting:");
9408 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009409 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009412 if (mRemovedProcesses.size() > 0) {
9413 if (needSep) pw.println(" ");
9414 needSep = true;
9415 pw.println(" Processes that are being removed:");
9416 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009418 }
9419
9420 if (mProcessesOnHold.size() > 0) {
9421 if (needSep) pw.println(" ");
9422 needSep = true;
9423 pw.println(" Processes that are on old until the system is ready:");
9424 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009425 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009427
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009428 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009429
9430 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009431 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432 long now = SystemClock.uptimeMillis();
9433 for (Map.Entry<String, SparseArray<Long>> procs
9434 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009435 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009436 SparseArray<Long> uids = procs.getValue();
9437 final int N = uids.size();
9438 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009439 int puid = uids.keyAt(i);
9440 ProcessRecord r = mProcessNames.get(pname, puid);
9441 if (dumpPackage != null && (r == null
9442 || !dumpPackage.equals(r.info.packageName))) {
9443 continue;
9444 }
9445 if (!printed) {
9446 if (needSep) pw.println(" ");
9447 needSep = true;
9448 pw.println(" Time since processes crashed:");
9449 printed = true;
9450 }
9451 pw.print(" Process "); pw.print(pname);
9452 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009453 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009454 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9455 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009456 }
9457 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009459
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 for (Map.Entry<String, SparseArray<Long>> procs
9463 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009464 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 SparseArray<Long> uids = procs.getValue();
9466 final int N = uids.size();
9467 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009468 int puid = uids.keyAt(i);
9469 ProcessRecord r = mProcessNames.get(pname, puid);
9470 if (dumpPackage != null && (r == null
9471 || !dumpPackage.equals(r.info.packageName))) {
9472 continue;
9473 }
9474 if (!printed) {
9475 if (needSep) pw.println(" ");
9476 needSep = true;
9477 pw.println(" Bad processes:");
9478 }
9479 pw.print(" Bad process "); pw.print(pname);
9480 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009481 pw.print(": crashed at time ");
9482 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 }
9484 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009487 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009488 pw.println(" mStartedUsers:");
9489 for (int i=0; i<mStartedUsers.size(); i++) {
9490 UserStartedState uss = mStartedUsers.valueAt(i);
9491 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009492 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009493 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009494 pw.print(" mStartedUserArray: [");
9495 for (int i=0; i<mStartedUserArray.length; i++) {
9496 if (i > 0) pw.print(", ");
9497 pw.print(mStartedUserArray[i]);
9498 }
9499 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009500 pw.print(" mUserLru: [");
9501 for (int i=0; i<mUserLru.size(); i++) {
9502 if (i > 0) pw.print(", ");
9503 pw.print(mUserLru.get(i));
9504 }
9505 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009506 if (dumpAll) {
9507 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9508 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009510 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009511 if (dumpAll) {
9512 StringBuilder sb = new StringBuilder(128);
9513 sb.append(" mPreviousProcessVisibleTime: ");
9514 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9515 pw.println(sb);
9516 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009517 if (mHeavyWeightProcess != null) {
9518 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9519 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009520 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009521 if (dumpAll) {
9522 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009523 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009524 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009525 for (Map.Entry<String, Integer> entry
9526 : mCompatModePackages.getPackages().entrySet()) {
9527 String pkg = entry.getKey();
9528 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9530 continue;
9531 }
9532 if (!printed) {
9533 pw.println(" mScreenCompatPackages:");
9534 printed = true;
9535 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009536 pw.print(" "); pw.print(pkg); pw.print(": ");
9537 pw.print(mode); pw.println();
9538 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009539 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009540 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009541 if (mSleeping || mWentToSleep || mLockScreenShown) {
9542 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9543 + " mLockScreenShown " + mLockScreenShown);
9544 }
9545 if (mShuttingDown) {
9546 pw.println(" mShuttingDown=" + mShuttingDown);
9547 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009548 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9549 || mOrigWaitForDebugger) {
9550 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9551 + " mDebugTransient=" + mDebugTransient
9552 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9553 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009554 if (mOpenGlTraceApp != null) {
9555 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9556 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009557 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9558 || mProfileFd != null) {
9559 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9560 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9561 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9562 + mAutoStopProfiler);
9563 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009564 if (mAlwaysFinishActivities || mController != null) {
9565 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9566 + " mController=" + mController);
9567 }
9568 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009571 + " mProcessesReady=" + mProcessesReady
9572 + " mSystemReady=" + mSystemReady);
9573 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 + " mBooted=" + mBooted
9575 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009576 pw.print(" mLastPowerCheckRealtime=");
9577 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9578 pw.println("");
9579 pw.print(" mLastPowerCheckUptime=");
9580 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9581 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009582 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9583 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009584 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009585 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9586 + " mNumHiddenProcs=" + mNumHiddenProcs
9587 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009588 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009589 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009590
9591 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 }
9593
Dianne Hackborn287952c2010-09-22 22:34:31 -07009594 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009595 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009596 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009597 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009598 long now = SystemClock.uptimeMillis();
9599 for (int i=0; i<mProcessesToGc.size(); i++) {
9600 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009601 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9602 continue;
9603 }
9604 if (!printed) {
9605 if (needSep) pw.println(" ");
9606 needSep = true;
9607 pw.println(" Processes that are waiting to GC:");
9608 printed = true;
9609 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009610 pw.print(" Process "); pw.println(proc);
9611 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9612 pw.print(", last gced=");
9613 pw.print(now-proc.lastRequestedGc);
9614 pw.print(" ms ago, last lowMem=");
9615 pw.print(now-proc.lastLowMemory);
9616 pw.println(" ms ago");
9617
9618 }
9619 }
9620 return needSep;
9621 }
9622
9623 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9624 int opti, boolean dumpAll) {
9625 boolean needSep = false;
9626
9627 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009628 if (needSep) pw.println(" ");
9629 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009630 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009631 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009632 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009633 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9634 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9635 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9636 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9637 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009638 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009639 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009640 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009641 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009642 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009643 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009644
9645 if (needSep) pw.println(" ");
9646 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009647 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009648 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009649 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009650 needSep = true;
9651 }
9652
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009653 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009654
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009655 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009656 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009657 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009658 if (mHeavyWeightProcess != null) {
9659 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9660 }
9661
9662 return true;
9663 }
9664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009665 /**
9666 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009667 * - no provider specified: dump all the providers
9668 * - a flattened component name that matched an existing provider was specified as the
9669 * first arg: dump that one provider
9670 * - the first arg isn't the flattened component name of an existing provider:
9671 * dump all providers whose component contains the first arg as a substring
9672 */
9673 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9674 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009675 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009676 }
9677
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009678 static class ItemMatcher {
9679 ArrayList<ComponentName> components;
9680 ArrayList<String> strings;
9681 ArrayList<Integer> objects;
9682 boolean all;
9683
9684 ItemMatcher() {
9685 all = true;
9686 }
9687
9688 void build(String name) {
9689 ComponentName componentName = ComponentName.unflattenFromString(name);
9690 if (componentName != null) {
9691 if (components == null) {
9692 components = new ArrayList<ComponentName>();
9693 }
9694 components.add(componentName);
9695 all = false;
9696 } else {
9697 int objectId = 0;
9698 // Not a '/' separated full component name; maybe an object ID?
9699 try {
9700 objectId = Integer.parseInt(name, 16);
9701 if (objects == null) {
9702 objects = new ArrayList<Integer>();
9703 }
9704 objects.add(objectId);
9705 all = false;
9706 } catch (RuntimeException e) {
9707 // Not an integer; just do string match.
9708 if (strings == null) {
9709 strings = new ArrayList<String>();
9710 }
9711 strings.add(name);
9712 all = false;
9713 }
9714 }
9715 }
9716
9717 int build(String[] args, int opti) {
9718 for (; opti<args.length; opti++) {
9719 String name = args[opti];
9720 if ("--".equals(name)) {
9721 return opti+1;
9722 }
9723 build(name);
9724 }
9725 return opti;
9726 }
9727
9728 boolean match(Object object, ComponentName comp) {
9729 if (all) {
9730 return true;
9731 }
9732 if (components != null) {
9733 for (int i=0; i<components.size(); i++) {
9734 if (components.get(i).equals(comp)) {
9735 return true;
9736 }
9737 }
9738 }
9739 if (objects != null) {
9740 for (int i=0; i<objects.size(); i++) {
9741 if (System.identityHashCode(object) == objects.get(i)) {
9742 return true;
9743 }
9744 }
9745 }
9746 if (strings != null) {
9747 String flat = comp.flattenToString();
9748 for (int i=0; i<strings.size(); i++) {
9749 if (flat.contains(strings.get(i))) {
9750 return true;
9751 }
9752 }
9753 }
9754 return false;
9755 }
9756 }
9757
Dianne Hackborn625ac272010-09-17 18:29:22 -07009758 /**
9759 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009760 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009761 * - the cmd arg isn't the flattened component name of an existing activity:
9762 * dump all activity whose component contains the cmd as a substring
9763 * - A hex number of the ActivityRecord object instance.
9764 */
9765 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9766 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009767 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009768
9769 if ("all".equals(name)) {
9770 synchronized (this) {
9771 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009772 activities.add(r1);
9773 }
9774 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009775 } else if ("top".equals(name)) {
9776 synchronized (this) {
9777 final int N = mMainStack.mHistory.size();
9778 if (N > 0) {
9779 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9780 }
9781 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009782 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009783 ItemMatcher matcher = new ItemMatcher();
9784 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009785
9786 synchronized (this) {
9787 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009788 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009789 activities.add(r1);
9790 }
9791 }
9792 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009793 }
9794
9795 if (activities.size() <= 0) {
9796 return false;
9797 }
9798
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009799 String[] newArgs = new String[args.length - opti];
9800 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9801
Dianne Hackborn30d71892010-12-11 10:37:55 -08009802 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009803 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009804 for (int i=activities.size()-1; i>=0; i--) {
9805 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009806 if (needSep) {
9807 pw.println();
9808 }
9809 needSep = true;
9810 synchronized (this) {
9811 if (lastTask != r.task) {
9812 lastTask = r.task;
9813 pw.print("TASK "); pw.print(lastTask.affinity);
9814 pw.print(" id="); pw.println(lastTask.taskId);
9815 if (dumpAll) {
9816 lastTask.dump(pw, " ");
9817 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009818 }
9819 }
9820 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009821 }
9822 return true;
9823 }
9824
9825 /**
9826 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9827 * there is a thread associated with the activity.
9828 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009829 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009830 final ActivityRecord r, String[] args, boolean dumpAll) {
9831 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009832 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009833 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9834 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9835 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009836 if (r.app != null) pw.println(r.app.pid);
9837 else pw.println("(not running)");
9838 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009839 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009840 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009841 }
9842 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 // flush anything that is already in the PrintWriter since the thread is going
9844 // to write to the file descriptor directly
9845 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009846 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 TransferPipe tp = new TransferPipe();
9848 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009849 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9850 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009851 tp.go(fd);
9852 } finally {
9853 tp.kill();
9854 }
9855 } catch (IOException e) {
9856 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009857 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009858 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009859 }
9860 }
9861 }
9862
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009863 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009864 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009865 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009866 boolean onlyHistory = false;
9867
9868 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009869 if (opti < args.length && "-s".equals(args[opti])) {
9870 dumpAll = false;
9871 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009872 onlyHistory = true;
9873 dumpPackage = null;
9874 }
9875
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009876 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009877 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009879 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009880 Iterator it = mRegisteredReceivers.values().iterator();
9881 while (it.hasNext()) {
9882 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009883 if (dumpPackage != null && (r.app == null ||
9884 !dumpPackage.equals(r.app.info.packageName))) {
9885 continue;
9886 }
9887 if (!printed) {
9888 pw.println(" Registered Receivers:");
9889 needSep = true;
9890 printed = true;
9891 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009892 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009893 r.dump(pw, " ");
9894 }
9895 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009896
9897 if (mReceiverResolver.dump(pw, needSep ?
9898 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9899 " ", dumpPackage, false)) {
9900 needSep = true;
9901 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009902 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009903
9904 for (BroadcastQueue q : mBroadcastQueues) {
9905 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009907
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009908 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009909
Dianne Hackborn786b4402012-08-27 15:14:02 -07009910 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009911 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9912 if (needSep) {
9913 pw.println();
9914 }
9915 needSep = true;
9916 pw.print(" Sticky broadcasts for user ");
9917 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9918 StringBuilder sb = new StringBuilder(128);
9919 for (Map.Entry<String, ArrayList<Intent>> ent
9920 : mStickyBroadcasts.valueAt(user).entrySet()) {
9921 pw.print(" * Sticky action "); pw.print(ent.getKey());
9922 if (dumpAll) {
9923 pw.println(":");
9924 ArrayList<Intent> intents = ent.getValue();
9925 final int N = intents.size();
9926 for (int i=0; i<N; i++) {
9927 sb.setLength(0);
9928 sb.append(" Intent: ");
9929 intents.get(i).toShortString(sb, false, true, false, false);
9930 pw.println(sb.toString());
9931 Bundle bundle = intents.get(i).getExtras();
9932 if (bundle != null) {
9933 pw.print(" ");
9934 pw.println(bundle.toString());
9935 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009936 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009937 } else {
9938 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009939 }
9940 }
9941 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009942 }
9943
Dianne Hackborn786b4402012-08-27 15:14:02 -07009944 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009945 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009946 for (BroadcastQueue queue : mBroadcastQueues) {
9947 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9948 + queue.mBroadcastsScheduled);
9949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 pw.println(" mHandler:");
9951 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009952 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009953 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009954
9955 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009956 }
9957
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009958 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009959 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009960 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009962 ItemMatcher matcher = new ItemMatcher();
9963 matcher.build(args, opti);
9964
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009965 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009966
9967 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009968
9969 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009970 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009971 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009972 ContentProviderRecord r = mLaunchingProviders.get(i);
9973 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9974 continue;
9975 }
9976 if (!printed) {
9977 if (needSep) pw.println(" ");
9978 needSep = true;
9979 pw.println(" Launching content providers:");
9980 printed = true;
9981 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009982 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009983 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009984 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009985 }
9986
9987 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009988 if (needSep) pw.println();
9989 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009990 pw.println("Granted Uri Permissions:");
9991 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9992 int uid = mGrantedUriPermissions.keyAt(i);
9993 HashMap<Uri, UriPermission> perms
9994 = mGrantedUriPermissions.valueAt(i);
9995 pw.print(" * UID "); pw.print(uid);
9996 pw.println(" holds:");
9997 for (UriPermission perm : perms.values()) {
9998 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009999 if (dumpAll) {
10000 perm.dump(pw, " ");
10001 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010002 }
10003 }
10004 needSep = true;
10005 }
10006
10007 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010008 }
10009
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010010 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010011 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010012 boolean needSep = false;
10013
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010014 if (mIntentSenderRecords.size() > 0) {
10015 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010016 Iterator<WeakReference<PendingIntentRecord>> it
10017 = mIntentSenderRecords.values().iterator();
10018 while (it.hasNext()) {
10019 WeakReference<PendingIntentRecord> ref = it.next();
10020 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010021 if (dumpPackage != null && (rec == null
10022 || !dumpPackage.equals(rec.key.packageName))) {
10023 continue;
10024 }
10025 if (!printed) {
10026 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10027 printed = true;
10028 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010029 needSep = true;
10030 if (rec != null) {
10031 pw.print(" * "); pw.println(rec);
10032 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010033 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010034 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010035 } else {
10036 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 }
10038 }
10039 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010040
10041 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 }
10043
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010044 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010045 String prefix, String label, boolean complete, boolean brief, boolean client,
10046 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 boolean needNL = false;
10049 final String innerPrefix = prefix + " ";
10050 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010052 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010053 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10054 continue;
10055 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010056 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 if (needNL) {
10058 pw.println(" ");
10059 needNL = false;
10060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 if (lastTask != r.task) {
10062 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010063 pw.print(prefix);
10064 pw.print(full ? "* " : " ");
10065 pw.println(lastTask);
10066 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010067 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010068 } else if (complete) {
10069 // Complete + brief == give a summary. Isn't that obvious?!?
10070 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010071 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010072 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010073 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010075 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010076 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10077 pw.print(" #"); pw.print(i); pw.print(": ");
10078 pw.println(r);
10079 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010080 r.dump(pw, innerPrefix);
10081 } else if (complete) {
10082 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010083 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010084 if (r.app != null) {
10085 pw.print(innerPrefix); pw.println(r.app);
10086 }
10087 }
10088 if (client && r.app != null && r.app.thread != null) {
10089 // flush anything that is already in the PrintWriter since the thread is going
10090 // to write to the file descriptor directly
10091 pw.flush();
10092 try {
10093 TransferPipe tp = new TransferPipe();
10094 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010095 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10096 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010097 // Short timeout, since blocking here can
10098 // deadlock with the application.
10099 tp.go(fd, 2000);
10100 } finally {
10101 tp.kill();
10102 }
10103 } catch (IOException e) {
10104 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10105 } catch (RemoteException e) {
10106 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10107 }
10108 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010110 }
10111 }
10112
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010113 private static String buildOomTag(String prefix, String space, int val, int base) {
10114 if (val == base) {
10115 if (space == null) return prefix;
10116 return prefix + " ";
10117 }
10118 return prefix + "+" + Integer.toString(val-base);
10119 }
10120
10121 private static final int dumpProcessList(PrintWriter pw,
10122 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010123 String prefix, String normalLabel, String persistentLabel,
10124 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010125 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010126 final int N = list.size()-1;
10127 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010129 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10130 continue;
10131 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010132 pw.println(String.format("%s%s #%2d: %s",
10133 prefix, (r.persistent ? persistentLabel : normalLabel),
10134 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010135 if (r.persistent) {
10136 numPers++;
10137 }
10138 }
10139 return numPers;
10140 }
10141
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010142 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010143 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010144 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010145 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010146
Dianne Hackborn905577f2011-09-07 18:31:28 -070010147 ArrayList<Pair<ProcessRecord, Integer>> list
10148 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10149 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010150 ProcessRecord r = origList.get(i);
10151 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10152 continue;
10153 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010154 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10155 }
10156
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010157 if (list.size() <= 0) {
10158 return false;
10159 }
10160
Dianne Hackborn905577f2011-09-07 18:31:28 -070010161 Comparator<Pair<ProcessRecord, Integer>> comparator
10162 = new Comparator<Pair<ProcessRecord, Integer>>() {
10163 @Override
10164 public int compare(Pair<ProcessRecord, Integer> object1,
10165 Pair<ProcessRecord, Integer> object2) {
10166 if (object1.first.setAdj != object2.first.setAdj) {
10167 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10168 }
10169 if (object1.second.intValue() != object2.second.intValue()) {
10170 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10171 }
10172 return 0;
10173 }
10174 };
10175
10176 Collections.sort(list, comparator);
10177
Dianne Hackborn287952c2010-09-22 22:34:31 -070010178 final long curRealtime = SystemClock.elapsedRealtime();
10179 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10180 final long curUptime = SystemClock.uptimeMillis();
10181 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10182
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010183 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010184 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010185 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010186 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010187 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010188 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10189 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010190 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10191 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010192 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10193 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010194 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10195 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010196 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010197 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010198 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10199 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10200 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10201 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10202 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10203 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10204 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10205 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010206 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10207 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010208 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10209 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010210 } else {
10211 oomAdj = Integer.toString(r.setAdj);
10212 }
10213 String schedGroup;
10214 switch (r.setSchedGroup) {
10215 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10216 schedGroup = "B";
10217 break;
10218 case Process.THREAD_GROUP_DEFAULT:
10219 schedGroup = "F";
10220 break;
10221 default:
10222 schedGroup = Integer.toString(r.setSchedGroup);
10223 break;
10224 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010225 String foreground;
10226 if (r.foregroundActivities) {
10227 foreground = "A";
10228 } else if (r.foregroundServices) {
10229 foreground = "S";
10230 } else {
10231 foreground = " ";
10232 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010233 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010234 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010235 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10236 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010237 if (r.adjSource != null || r.adjTarget != null) {
10238 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010239 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010240 if (r.adjTarget instanceof ComponentName) {
10241 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10242 } else if (r.adjTarget != null) {
10243 pw.print(r.adjTarget.toString());
10244 } else {
10245 pw.print("{null}");
10246 }
10247 pw.print("<=");
10248 if (r.adjSource instanceof ProcessRecord) {
10249 pw.print("Proc{");
10250 pw.print(((ProcessRecord)r.adjSource).toShortString());
10251 pw.println("}");
10252 } else if (r.adjSource != null) {
10253 pw.println(r.adjSource.toString());
10254 } else {
10255 pw.println("{null}");
10256 }
10257 }
10258 if (inclDetails) {
10259 pw.print(prefix);
10260 pw.print(" ");
10261 pw.print("oom: max="); pw.print(r.maxAdj);
10262 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010263 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010264 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010265 pw.print(" curRaw="); pw.print(r.curRawAdj);
10266 pw.print(" setRaw="); pw.print(r.setRawAdj);
10267 pw.print(" cur="); pw.print(r.curAdj);
10268 pw.print(" set="); pw.println(r.setAdj);
10269 pw.print(prefix);
10270 pw.print(" ");
10271 pw.print("keeping="); pw.print(r.keeping);
10272 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010273 pw.print(" empty="); pw.print(r.empty);
10274 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010275
10276 if (!r.keeping) {
10277 if (r.lastWakeTime != 0) {
10278 long wtime;
10279 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10280 synchronized (stats) {
10281 wtime = stats.getProcessWakeTime(r.info.uid,
10282 r.pid, curRealtime);
10283 }
10284 long timeUsed = wtime - r.lastWakeTime;
10285 pw.print(prefix);
10286 pw.print(" ");
10287 pw.print("keep awake over ");
10288 TimeUtils.formatDuration(realtimeSince, pw);
10289 pw.print(" used ");
10290 TimeUtils.formatDuration(timeUsed, pw);
10291 pw.print(" (");
10292 pw.print((timeUsed*100)/realtimeSince);
10293 pw.println("%)");
10294 }
10295 if (r.lastCpuTime != 0) {
10296 long timeUsed = r.curCpuTime - r.lastCpuTime;
10297 pw.print(prefix);
10298 pw.print(" ");
10299 pw.print("run cpu over ");
10300 TimeUtils.formatDuration(uptimeSince, pw);
10301 pw.print(" used ");
10302 TimeUtils.formatDuration(timeUsed, pw);
10303 pw.print(" (");
10304 pw.print((timeUsed*100)/uptimeSince);
10305 pw.println("%)");
10306 }
10307 }
10308 }
10309 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010310 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010311 }
10312
Dianne Hackbornb437e092011-08-05 17:50:29 -070010313 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010314 ArrayList<ProcessRecord> procs;
10315 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316 if (args != null && args.length > start
10317 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010318 procs = new ArrayList<ProcessRecord>();
10319 int pid = -1;
10320 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010321 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010322 } catch (NumberFormatException e) {
10323
10324 }
10325 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10326 ProcessRecord proc = mLruProcesses.get(i);
10327 if (proc.pid == pid) {
10328 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010329 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010330 procs.add(proc);
10331 }
10332 }
10333 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010335 return null;
10336 }
10337 } else {
10338 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10339 }
10340 }
10341 return procs;
10342 }
10343
10344 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10345 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010346 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010347 if (procs == null) {
10348 return;
10349 }
10350
10351 long uptime = SystemClock.uptimeMillis();
10352 long realtime = SystemClock.elapsedRealtime();
10353 pw.println("Applications Graphics Acceleration Info:");
10354 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10355
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010356 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10357 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010358 if (r.thread != null) {
10359 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10360 pw.flush();
10361 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010362 TransferPipe tp = new TransferPipe();
10363 try {
10364 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10365 tp.go(fd);
10366 } finally {
10367 tp.kill();
10368 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010369 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010370 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010371 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010372 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010373 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010374 pw.flush();
10375 }
10376 }
10377 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010378 }
10379
Jeff Brown6754ba22011-12-14 20:20:01 -080010380 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10381 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10382 if (procs == null) {
10383 return;
10384 }
10385
10386 pw.println("Applications Database Info:");
10387
10388 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10389 ProcessRecord r = procs.get(i);
10390 if (r.thread != null) {
10391 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10392 pw.flush();
10393 try {
10394 TransferPipe tp = new TransferPipe();
10395 try {
10396 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10397 tp.go(fd);
10398 } finally {
10399 tp.kill();
10400 }
10401 } catch (IOException e) {
10402 pw.println("Failure while dumping the app: " + r);
10403 pw.flush();
10404 } catch (RemoteException e) {
10405 pw.println("Got a RemoteException while dumping the app " + r);
10406 pw.flush();
10407 }
10408 }
10409 }
10410 }
10411
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010412 final static class MemItem {
10413 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010414 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010415 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010416 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010417 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010418
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010419 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010420 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010421 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010422 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010423 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010424 }
10425 }
10426
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010427 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010428 boolean sort) {
10429 if (sort) {
10430 Collections.sort(items, new Comparator<MemItem>() {
10431 @Override
10432 public int compare(MemItem lhs, MemItem rhs) {
10433 if (lhs.pss < rhs.pss) {
10434 return 1;
10435 } else if (lhs.pss > rhs.pss) {
10436 return -1;
10437 }
10438 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010439 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010440 });
10441 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010442
10443 for (int i=0; i<items.size(); i++) {
10444 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010445 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010446 if (mi.subitems != null) {
10447 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10448 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010449 }
10450 }
10451
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010452 // These are in KB.
10453 static final long[] DUMP_MEM_BUCKETS = new long[] {
10454 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10455 120*1024, 160*1024, 200*1024,
10456 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10457 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10458 };
10459
Dianne Hackborn672342c2011-11-29 11:29:02 -080010460 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10461 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010462 int start = label.lastIndexOf('.');
10463 if (start >= 0) start++;
10464 else start = 0;
10465 int end = label.length();
10466 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10467 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10468 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10469 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010470 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010471 out.append(label, start, end);
10472 return;
10473 }
10474 }
10475 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010476 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010477 out.append(label, start, end);
10478 }
10479
10480 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10481 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10482 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10483 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10484 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10485 };
10486 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10487 "System", "Persistent", "Foreground",
10488 "Visible", "Perceptible", "Heavy Weight",
10489 "Backup", "A Services", "Home", "Previous",
10490 "B Services", "Background"
10491 };
10492
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010493 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010494 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010495 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010496 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010497 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010498
10499 int opti = 0;
10500 while (opti < args.length) {
10501 String opt = args[opti];
10502 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10503 break;
10504 }
10505 opti++;
10506 if ("-a".equals(opt)) {
10507 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010508 } else if ("--oom".equals(opt)) {
10509 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010510 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010511 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010512 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010513 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010514 pw.println("If [process] is specified it can be the name or ");
10515 pw.println("pid of a specific process to dump.");
10516 return;
10517 } else {
10518 pw.println("Unknown argument: " + opt + "; use -h for help");
10519 }
10520 }
10521
10522 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010523 if (procs == null) {
10524 return;
10525 }
10526
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010527 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010528 long uptime = SystemClock.uptimeMillis();
10529 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010530
10531 if (procs.size() == 1 || isCheckinRequest) {
10532 dumpAll = true;
10533 }
10534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010535 if (isCheckinRequest) {
10536 // short checkin version
10537 pw.println(uptime + "," + realtime);
10538 pw.flush();
10539 } else {
10540 pw.println("Applications Memory Usage (kB):");
10541 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10542 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010543
Dianne Hackbornb437e092011-08-05 17:50:29 -070010544 String[] innerArgs = new String[args.length-opti];
10545 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10546
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010547 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10548 long nativePss=0, dalvikPss=0, otherPss=0;
10549 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10550
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010551 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10552 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10553 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010554
10555 long totalPss = 0;
10556
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010557 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10558 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010560 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10562 pw.flush();
10563 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010564 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010565 if (dumpAll) {
10566 try {
10567 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10568 } catch (RemoteException e) {
10569 if (!isCheckinRequest) {
10570 pw.println("Got RemoteException!");
10571 pw.flush();
10572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010573 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010574 } else {
10575 mi = new Debug.MemoryInfo();
10576 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010578
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010579 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010580 long myTotalPss = mi.getTotalPss();
10581 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010582 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010583 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010584 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010585
10586 nativePss += mi.nativePss;
10587 dalvikPss += mi.dalvikPss;
10588 otherPss += mi.otherPss;
10589 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10590 long mem = mi.getOtherPss(j);
10591 miscPss[j] += mem;
10592 otherPss -= mem;
10593 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010594
10595 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010596 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10597 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010598 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010599 if (oomProcs[oomIndex] == null) {
10600 oomProcs[oomIndex] = new ArrayList<MemItem>();
10601 }
10602 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010603 break;
10604 }
10605 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 }
10608 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010609
10610 if (!isCheckinRequest && procs.size() > 1) {
10611 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10612
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010613 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10614 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10615 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010616 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010617 String label = Debug.MemoryInfo.getOtherLabel(j);
10618 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010619 }
10620
Dianne Hackbornb437e092011-08-05 17:50:29 -070010621 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10622 for (int j=0; j<oomPss.length; j++) {
10623 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010624 String label = DUMP_MEM_OOM_LABEL[j];
10625 MemItem item = new MemItem(label, label, oomPss[j],
10626 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010627 item.subitems = oomProcs[j];
10628 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010629 }
10630 }
10631
Dianne Hackborn672342c2011-11-29 11:29:02 -080010632 if (outTag != null || outStack != null) {
10633 if (outTag != null) {
10634 appendMemBucket(outTag, totalPss, "total", false);
10635 }
10636 if (outStack != null) {
10637 appendMemBucket(outStack, totalPss, "total", true);
10638 }
10639 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010640 for (int i=0; i<oomMems.size(); i++) {
10641 MemItem miCat = oomMems.get(i);
10642 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10643 continue;
10644 }
10645 if (miCat.id < ProcessList.SERVICE_ADJ
10646 || miCat.id == ProcessList.HOME_APP_ADJ
10647 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010648 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10649 outTag.append(" / ");
10650 }
10651 if (outStack != null) {
10652 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10653 if (firstLine) {
10654 outStack.append(":");
10655 firstLine = false;
10656 }
10657 outStack.append("\n\t at ");
10658 } else {
10659 outStack.append("$");
10660 }
10661 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010662 for (int j=0; j<miCat.subitems.size(); j++) {
10663 MemItem mi = miCat.subitems.get(j);
10664 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010665 if (outTag != null) {
10666 outTag.append(" ");
10667 }
10668 if (outStack != null) {
10669 outStack.append("$");
10670 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010671 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010672 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10673 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10674 }
10675 if (outStack != null) {
10676 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10677 }
10678 }
10679 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10680 outStack.append("(");
10681 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10682 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10683 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10684 outStack.append(":");
10685 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10686 }
10687 }
10688 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010689 }
10690 }
10691 }
10692 }
10693
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010694 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010695 pw.println();
10696 pw.println("Total PSS by process:");
10697 dumpMemItems(pw, " ", procMems, true);
10698 pw.println();
10699 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010700 pw.println("Total PSS by OOM adjustment:");
10701 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010702 if (!oomOnly) {
10703 PrintWriter out = categoryPw != null ? categoryPw : pw;
10704 out.println();
10705 out.println("Total PSS by category:");
10706 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010707 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010708 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010709 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010710 final int[] SINGLE_LONG_FORMAT = new int[] {
10711 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10712 };
10713 long[] longOut = new long[1];
10714 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10715 SINGLE_LONG_FORMAT, null, longOut, null);
10716 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10717 longOut[0] = 0;
10718 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10719 SINGLE_LONG_FORMAT, null, longOut, null);
10720 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10721 longOut[0] = 0;
10722 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10723 SINGLE_LONG_FORMAT, null, longOut, null);
10724 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10725 longOut[0] = 0;
10726 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10727 SINGLE_LONG_FORMAT, null, longOut, null);
10728 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10729 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10730 pw.print(shared); pw.println(" kB");
10731 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10732 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 }
10735
10736 /**
10737 * Searches array of arguments for the specified string
10738 * @param args array of argument strings
10739 * @param value value to search for
10740 * @return true if the value is contained in the array
10741 */
10742 private static boolean scanArgs(String[] args, String value) {
10743 if (args != null) {
10744 for (String arg : args) {
10745 if (value.equals(arg)) {
10746 return true;
10747 }
10748 }
10749 }
10750 return false;
10751 }
10752
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010753 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10754 ContentProviderRecord cpr, boolean always) {
10755 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10756
10757 if (!inLaunching || always) {
10758 synchronized (cpr) {
10759 cpr.launchingApp = null;
10760 cpr.notifyAll();
10761 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010762 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010763 String names[] = cpr.info.authority.split(";");
10764 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010765 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 }
10767 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010768
10769 for (int i=0; i<cpr.connections.size(); i++) {
10770 ContentProviderConnection conn = cpr.connections.get(i);
10771 if (conn.waiting) {
10772 // If this connection is waiting for the provider, then we don't
10773 // need to mess with its process unless we are always removing
10774 // or for some reason the provider is not currently launching.
10775 if (inLaunching && !always) {
10776 continue;
10777 }
10778 }
10779 ProcessRecord capp = conn.client;
10780 conn.dead = true;
10781 if (conn.stableCount > 0) {
10782 if (!capp.persistent && capp.thread != null
10783 && capp.pid != 0
10784 && capp.pid != MY_PID) {
10785 Slog.i(TAG, "Kill " + capp.processName
10786 + " (pid " + capp.pid + "): provider " + cpr.info.name
10787 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010788 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010789 capp.processName, capp.setAdj, "dying provider "
10790 + cpr.name.toShortString());
10791 Process.killProcessQuiet(capp.pid);
10792 }
10793 } else if (capp.thread != null && conn.provider.provider != null) {
10794 try {
10795 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10796 } catch (RemoteException e) {
10797 }
10798 // In the protocol here, we don't expect the client to correctly
10799 // clean up this connection, we'll just remove it.
10800 cpr.connections.remove(i);
10801 conn.client.conProviders.remove(conn);
10802 }
10803 }
10804
10805 if (inLaunching && always) {
10806 mLaunchingProviders.remove(cpr);
10807 }
10808 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 }
10810
10811 /**
10812 * Main code for cleaning up a process when it has gone away. This is
10813 * called both as a result of the process dying, or directly when stopping
10814 * a process when running in single process mode.
10815 */
10816 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010817 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010819 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 }
10821
Dianne Hackborn36124872009-10-08 16:22:03 -070010822 mProcessesToGc.remove(app);
10823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 // Dismiss any open dialogs.
10825 if (app.crashDialog != null) {
10826 app.crashDialog.dismiss();
10827 app.crashDialog = null;
10828 }
10829 if (app.anrDialog != null) {
10830 app.anrDialog.dismiss();
10831 app.anrDialog = null;
10832 }
10833 if (app.waitDialog != null) {
10834 app.waitDialog.dismiss();
10835 app.waitDialog = null;
10836 }
10837
10838 app.crashing = false;
10839 app.notResponding = false;
10840
10841 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010842 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010843 app.thread = null;
10844 app.forcingToForeground = null;
10845 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010846 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010847 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010848 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010849
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010850 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851
10852 boolean restart = false;
10853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 // Remove published content providers.
10855 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010856 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010858 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010859
10860 final boolean always = app.bad || !allowRestart;
10861 if (removeDyingProviderLocked(app, cpr, always) || always) {
10862 // We left the provider in the launching list, need to
10863 // restart it.
10864 restart = true;
10865 }
10866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010868 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 }
10870 app.pubProviders.clear();
10871 }
10872
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010873 // Take care of any launching providers waiting for this process.
10874 if (checkAppInLaunchingProvidersLocked(app, false)) {
10875 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 // Unregister from connected content providers.
10879 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010880 for (int i=0; i<app.conProviders.size(); i++) {
10881 ContentProviderConnection conn = app.conProviders.get(i);
10882 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 }
10884 app.conProviders.clear();
10885 }
10886
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010887 // At this point there may be remaining entries in mLaunchingProviders
10888 // where we were the only one waiting, so they are no longer of use.
10889 // Look for these and clean up if found.
10890 // XXX Commented out for now. Trying to figure out a way to reproduce
10891 // the actual situation to identify what is actually going on.
10892 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010893 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010894 ContentProviderRecord cpr = (ContentProviderRecord)
10895 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010896 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010897 synchronized (cpr) {
10898 cpr.launchingApp = null;
10899 cpr.notifyAll();
10900 }
10901 }
10902 }
10903 }
10904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010905 skipCurrentReceiverLocked(app);
10906
10907 // Unregister any receivers.
10908 if (app.receivers.size() > 0) {
10909 Iterator<ReceiverList> it = app.receivers.iterator();
10910 while (it.hasNext()) {
10911 removeReceiverLocked(it.next());
10912 }
10913 app.receivers.clear();
10914 }
10915
Christopher Tate181fafa2009-05-14 11:12:14 -070010916 // If the app is undergoing backup, tell the backup manager about it
10917 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010918 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10919 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010920 try {
10921 IBackupManager bm = IBackupManager.Stub.asInterface(
10922 ServiceManager.getService(Context.BACKUP_SERVICE));
10923 bm.agentDisconnected(app.info.packageName);
10924 } catch (RemoteException e) {
10925 // can't happen; backup manager is local
10926 }
10927 }
10928
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010929 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10930 ProcessChangeItem item = mPendingProcessChanges.get(i);
10931 if (item.pid == app.pid) {
10932 mPendingProcessChanges.remove(i);
10933 mAvailProcessChanges.add(item);
10934 }
10935 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010936 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 // If the caller is restarting this app, then leave it in its
10939 // current lists and let the caller take care of it.
10940 if (restarting) {
10941 return;
10942 }
10943
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010944 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010945 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010946 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010947 mProcessNames.remove(app.processName, app.uid);
10948 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010949 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010950 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10951 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010952 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010954 } else if (!app.removed) {
10955 // This app is persistent, so we need to keep its record around.
10956 // If it is not already on the pending app list, add it there
10957 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10959 mPersistentStartingProcesses.add(app);
10960 restart = true;
10961 }
10962 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010963 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010964 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 mProcessesOnHold.remove(app);
10966
The Android Open Source Project4df24232009-03-05 14:34:35 -080010967 if (app == mHomeProcess) {
10968 mHomeProcess = null;
10969 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010970 if (app == mPreviousProcess) {
10971 mPreviousProcess = null;
10972 }
10973
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010974 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010975 // We have components that still need to be running in the
10976 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010977 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010978 startProcessLocked(app, "restart", app.processName);
10979 } else if (app.pid > 0 && app.pid != MY_PID) {
10980 // Goodbye!
10981 synchronized (mPidsSelfLocked) {
10982 mPidsSelfLocked.remove(app.pid);
10983 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10984 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010985 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 }
10987 }
10988
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010989 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10990 // Look through the content providers we are waiting to have launched,
10991 // and if any run in this process then either schedule a restart of
10992 // the process or kill the client waiting for it if this process has
10993 // gone bad.
10994 int NL = mLaunchingProviders.size();
10995 boolean restart = false;
10996 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010997 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010998 if (cpr.launchingApp == app) {
10999 if (!alwaysBad && !app.bad) {
11000 restart = true;
11001 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011002 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011003 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011004 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011005 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011006 }
11007 }
11008 }
11009 return restart;
11010 }
11011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011012 // =========================================================
11013 // SERVICES
11014 // =========================================================
11015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11017 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011018 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011020 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 }
11022 }
11023
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011024 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011025 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011026 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011027 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011028 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011029 }
11030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011031 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011032 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011033 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 // Refuse possible leaked file descriptors
11035 if (service != null && service.hasFileDescriptors() == true) {
11036 throw new IllegalArgumentException("File descriptors passed in Intent");
11037 }
11038
Amith Yamasani742a6712011-05-04 14:49:28 -070011039 if (DEBUG_SERVICE)
11040 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 synchronized(this) {
11042 final int callingPid = Binder.getCallingPid();
11043 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011044 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011046 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011047 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048 Binder.restoreCallingIdentity(origId);
11049 return res;
11050 }
11051 }
11052
11053 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070011054 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011056 if (DEBUG_SERVICE)
11057 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011058 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011059 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070011060 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 Binder.restoreCallingIdentity(origId);
11062 return res;
11063 }
11064 }
11065
11066 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011067 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011068 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 // Refuse possible leaked file descriptors
11070 if (service != null && service.hasFileDescriptors() == true) {
11071 throw new IllegalArgumentException("File descriptors passed in Intent");
11072 }
11073
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011074 checkValidCaller(Binder.getCallingUid(), userId);
11075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011077 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 }
11080
11081 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011082 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 // Refuse possible leaked file descriptors
11084 if (service != null && service.hasFileDescriptors() == true) {
11085 throw new IllegalArgumentException("File descriptors passed in Intent");
11086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011088 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011090 }
11091
11092 public boolean stopServiceToken(ComponentName className, IBinder token,
11093 int startId) {
11094 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011095 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 }
11098
11099 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011100 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011102 mServices.setServiceForegroundLocked(className, token, id, notification,
11103 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 }
11105 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011106
Dianne Hackborn41203752012-08-31 14:05:51 -070011107 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11108 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011109 final int callingUserId = UserHandle.getUserId(callingUid);
11110 if (callingUserId != userId) {
11111 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11112 if ((requireFull || checkComponentPermission(
11113 android.Manifest.permission.INTERACT_ACROSS_USERS,
11114 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11115 && checkComponentPermission(
11116 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11117 callingPid, callingUid, -1, true)
11118 != PackageManager.PERMISSION_GRANTED) {
11119 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11120 // In this case, they would like to just execute as their
11121 // owner user instead of failing.
11122 userId = callingUserId;
11123 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011124 StringBuilder builder = new StringBuilder(128);
11125 builder.append("Permission Denial: ");
11126 builder.append(name);
11127 if (callerPackage != null) {
11128 builder.append(" from ");
11129 builder.append(callerPackage);
11130 }
11131 builder.append(" asks to run as user ");
11132 builder.append(userId);
11133 builder.append(" but is calling from user ");
11134 builder.append(UserHandle.getUserId(callingUid));
11135 builder.append("; this requires ");
11136 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11137 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011138 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011139 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11140 }
11141 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011142 Slog.w(TAG, msg);
11143 throw new SecurityException(msg);
11144 }
11145 }
11146 }
11147 if (userId == UserHandle.USER_CURRENT
11148 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011149 // Note that we may be accessing this outside of a lock...
11150 // shouldn't be a big deal, if this is being called outside
11151 // of a locked context there is intrinsically a race with
11152 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011153 userId = mCurrentUserId;
11154 }
11155 if (!allowAll && userId < 0) {
11156 throw new IllegalArgumentException(
11157 "Call does not support special user #" + userId);
11158 }
11159 }
11160 return userId;
11161 }
11162
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011163 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11164 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011165 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011166 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011167 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11168 if (ActivityManager.checkUidPermission(
11169 android.Manifest.permission.INTERACT_ACROSS_USERS,
11170 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11171 ComponentName comp = new ComponentName(aInfo.packageName, className);
11172 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11173 + " requests FLAG_SINGLE_USER, but app does not hold "
11174 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11175 Slog.w(TAG, msg);
11176 throw new SecurityException(msg);
11177 }
11178 result = true;
11179 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011180 } else if (componentProcessName == aInfo.packageName) {
11181 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11182 } else if ("system".equals(componentProcessName)) {
11183 result = true;
11184 }
11185 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011186 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11187 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011188 }
11189 return result;
11190 }
11191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 public int bindService(IApplicationThread caller, IBinder token,
11193 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011194 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011195 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 // Refuse possible leaked file descriptors
11197 if (service != null && service.hasFileDescriptors() == true) {
11198 throw new IllegalArgumentException("File descriptors passed in Intent");
11199 }
11200
11201 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011202 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11203 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 }
11205 }
11206
11207 public boolean unbindService(IServiceConnection connection) {
11208 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011209 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 }
11212
11213 public void publishService(IBinder token, Intent intent, IBinder service) {
11214 // Refuse possible leaked file descriptors
11215 if (intent != null && intent.hasFileDescriptors() == true) {
11216 throw new IllegalArgumentException("File descriptors passed in Intent");
11217 }
11218
11219 synchronized(this) {
11220 if (!(token instanceof ServiceRecord)) {
11221 throw new IllegalArgumentException("Invalid service token");
11222 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011223 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 }
11225 }
11226
11227 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11228 // Refuse possible leaked file descriptors
11229 if (intent != null && intent.hasFileDescriptors() == true) {
11230 throw new IllegalArgumentException("File descriptors passed in Intent");
11231 }
11232
11233 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011234 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 }
11236 }
11237
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011238 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 synchronized(this) {
11240 if (!(token instanceof ServiceRecord)) {
11241 throw new IllegalArgumentException("Invalid service token");
11242 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011243 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 }
11246
11247 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011248 // BACKUP AND RESTORE
11249 // =========================================================
11250
11251 // Cause the target app to be launched if necessary and its backup agent
11252 // instantiated. The backup agent will invoke backupAgentCreated() on the
11253 // activity manager to announce its creation.
11254 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011255 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11256 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011257
11258 synchronized(this) {
11259 // !!! TODO: currently no check here that we're already bound
11260 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11261 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11262 synchronized (stats) {
11263 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11264 }
11265
Dianne Hackborne7f97212011-02-24 14:40:20 -080011266 // Backup agent is now in use, its package can't be stopped.
11267 try {
11268 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011269 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011270 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011271 } catch (IllegalArgumentException e) {
11272 Slog.w(TAG, "Failed trying to unstop package "
11273 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011274 }
11275
Christopher Tate181fafa2009-05-14 11:12:14 -070011276 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011277 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11278 ? new ComponentName(app.packageName, app.backupAgentName)
11279 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011280 // startProcessLocked() returns existing proc's record if it's already running
11281 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011282 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011283 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011284 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011285 return false;
11286 }
11287
11288 r.app = proc;
11289 mBackupTarget = r;
11290 mBackupAppName = app.packageName;
11291
Christopher Tate6fa95972009-06-05 18:43:55 -070011292 // Try not to kill the process during backup
11293 updateOomAdjLocked(proc);
11294
Christopher Tate181fafa2009-05-14 11:12:14 -070011295 // If the process is already attached, schedule the creation of the backup agent now.
11296 // If it is not yet live, this will be done when it attaches to the framework.
11297 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011298 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011299 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011300 proc.thread.scheduleCreateBackupAgent(app,
11301 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011302 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011303 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011304 }
11305 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011306 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011307 }
11308 // Invariants: at this point, the target app process exists and the application
11309 // is either already running or in the process of coming up. mBackupTarget and
11310 // mBackupAppName describe the app, so that when it binds back to the AM we
11311 // know that it's scheduled for a backup-agent operation.
11312 }
11313
11314 return true;
11315 }
11316
Christopher Tate346acb12012-10-15 19:20:25 -070011317 @Override
11318 public void clearPendingBackup() {
11319 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11320 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11321
11322 synchronized (this) {
11323 mBackupTarget = null;
11324 mBackupAppName = null;
11325 }
11326 }
11327
Christopher Tate181fafa2009-05-14 11:12:14 -070011328 // A backup agent has just come up
11329 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011330 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011331 + " = " + agent);
11332
11333 synchronized(this) {
11334 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011335 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011336 return;
11337 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011338 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011339
Dianne Hackborn06740692010-09-22 22:46:21 -070011340 long oldIdent = Binder.clearCallingIdentity();
11341 try {
11342 IBackupManager bm = IBackupManager.Stub.asInterface(
11343 ServiceManager.getService(Context.BACKUP_SERVICE));
11344 bm.agentConnected(agentPackageName, agent);
11345 } catch (RemoteException e) {
11346 // can't happen; the backup manager service is local
11347 } catch (Exception e) {
11348 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11349 e.printStackTrace();
11350 } finally {
11351 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011352 }
11353 }
11354
11355 // done with this agent
11356 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011357 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011358 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011359 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011360 return;
11361 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011362
11363 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011364 try {
11365 if (mBackupAppName == null) {
11366 Slog.w(TAG, "Unbinding backup agent with no active backup");
11367 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011368 }
Christopher Tate346acb12012-10-15 19:20:25 -070011369
11370 if (!mBackupAppName.equals(appInfo.packageName)) {
11371 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11372 return;
11373 }
11374
11375 // Not backing this app up any more; reset its OOM adjustment
11376 final ProcessRecord proc = mBackupTarget.app;
11377 updateOomAdjLocked(proc);
11378
11379 // If the app crashed during backup, 'thread' will be null here
11380 if (proc.thread != null) {
11381 try {
11382 proc.thread.scheduleDestroyBackupAgent(appInfo,
11383 compatibilityInfoForPackageLocked(appInfo));
11384 } catch (Exception e) {
11385 Slog.e(TAG, "Exception when unbinding backup agent:");
11386 e.printStackTrace();
11387 }
11388 }
11389 } finally {
11390 mBackupTarget = null;
11391 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011392 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011393 }
11394 }
11395 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 // BROADCASTS
11397 // =========================================================
11398
Josh Bartel7f208742010-02-25 11:01:44 -060011399 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011400 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011402 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11403 if (stickies == null) {
11404 return cur;
11405 }
11406 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 if (list == null) {
11408 return cur;
11409 }
11410 int N = list.size();
11411 for (int i=0; i<N; i++) {
11412 Intent intent = list.get(i);
11413 if (filter.match(resolver, intent, true, TAG) >= 0) {
11414 if (cur == null) {
11415 cur = new ArrayList<Intent>();
11416 }
11417 cur.add(intent);
11418 }
11419 }
11420 return cur;
11421 }
11422
Christopher Tatef46723b2012-01-26 14:19:24 -080011423 boolean isPendingBroadcastProcessLocked(int pid) {
11424 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11425 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427
Christopher Tatef46723b2012-01-26 14:19:24 -080011428 void skipPendingBroadcastLocked(int pid) {
11429 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11430 for (BroadcastQueue queue : mBroadcastQueues) {
11431 queue.skipPendingBroadcastLocked(pid);
11432 }
11433 }
11434
11435 // The app just attached; send any pending broadcasts that it should receive
11436 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11437 boolean didSomething = false;
11438 for (BroadcastQueue queue : mBroadcastQueues) {
11439 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011441 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 }
11443
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011444 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011445 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011446 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011447 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011448 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 synchronized(this) {
11450 ProcessRecord callerApp = null;
11451 if (caller != null) {
11452 callerApp = getRecordForAppLocked(caller);
11453 if (callerApp == null) {
11454 throw new SecurityException(
11455 "Unable to find app for caller " + caller
11456 + " (pid=" + Binder.getCallingPid()
11457 + ") when registering receiver " + receiver);
11458 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011459 if (callerApp.info.uid != Process.SYSTEM_UID &&
11460 !callerApp.pkgList.contains(callerPackage)) {
11461 throw new SecurityException("Given caller package " + callerPackage
11462 + " is not running in process " + callerApp);
11463 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011464 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011465 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011466 } else {
11467 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011468 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011469 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 }
11471
Dianne Hackborn139748f2012-09-24 11:36:57 -070011472 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011473 true, true, "registerReceiver", callerPackage);
11474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 List allSticky = null;
11476
11477 // Look for any matching sticky broadcasts...
11478 Iterator actions = filter.actionsIterator();
11479 if (actions != null) {
11480 while (actions.hasNext()) {
11481 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011482 allSticky = getStickiesLocked(action, filter, allSticky,
11483 UserHandle.USER_ALL);
11484 allSticky = getStickiesLocked(action, filter, allSticky,
11485 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 }
11487 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011488 allSticky = getStickiesLocked(null, filter, allSticky,
11489 UserHandle.USER_ALL);
11490 allSticky = getStickiesLocked(null, filter, allSticky,
11491 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 }
11493
11494 // The first sticky in the list is returned directly back to
11495 // the client.
11496 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11497
Joe Onorato8a9b2202010-02-26 18:56:32 -080011498 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 + ": " + sticky);
11500
11501 if (receiver == null) {
11502 return sticky;
11503 }
11504
11505 ReceiverList rl
11506 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11507 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011508 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11509 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011510 if (rl.app != null) {
11511 rl.app.receivers.add(rl);
11512 } else {
11513 try {
11514 receiver.asBinder().linkToDeath(rl, 0);
11515 } catch (RemoteException e) {
11516 return sticky;
11517 }
11518 rl.linkedToDeath = true;
11519 }
11520 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011521 } else if (rl.uid != callingUid) {
11522 throw new IllegalArgumentException(
11523 "Receiver requested to register for uid " + callingUid
11524 + " was previously registered for uid " + rl.uid);
11525 } else if (rl.pid != callingPid) {
11526 throw new IllegalArgumentException(
11527 "Receiver requested to register for pid " + callingPid
11528 + " was previously registered for pid " + rl.pid);
11529 } else if (rl.userId != userId) {
11530 throw new IllegalArgumentException(
11531 "Receiver requested to register for user " + userId
11532 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011534 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011535 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 rl.add(bf);
11537 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011538 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 }
11540 mReceiverResolver.addFilter(bf);
11541
11542 // Enqueue broadcasts for all existing stickies that match
11543 // this filter.
11544 if (allSticky != null) {
11545 ArrayList receivers = new ArrayList();
11546 receivers.add(bf);
11547
11548 int N = allSticky.size();
11549 for (int i=0; i<N; i++) {
11550 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011551 BroadcastQueue queue = broadcastQueueForIntent(intent);
11552 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011554 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011555 queue.enqueueParallelBroadcastLocked(r);
11556 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 }
11558 }
11559
11560 return sticky;
11561 }
11562 }
11563
11564 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011565 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566
Christopher Tatef46723b2012-01-26 14:19:24 -080011567 final long origId = Binder.clearCallingIdentity();
11568 try {
11569 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570
Christopher Tatef46723b2012-01-26 14:19:24 -080011571 synchronized(this) {
11572 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011573 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011574 if (rl != null) {
11575 if (rl.curBroadcast != null) {
11576 BroadcastRecord r = rl.curBroadcast;
11577 final boolean doNext = finishReceiverLocked(
11578 receiver.asBinder(), r.resultCode, r.resultData,
11579 r.resultExtras, r.resultAbort, true);
11580 if (doNext) {
11581 doTrim = true;
11582 r.queue.processNextBroadcast(false);
11583 }
11584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585
Christopher Tatef46723b2012-01-26 14:19:24 -080011586 if (rl.app != null) {
11587 rl.app.receivers.remove(rl);
11588 }
11589 removeReceiverLocked(rl);
11590 if (rl.linkedToDeath) {
11591 rl.linkedToDeath = false;
11592 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 }
11595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596
Christopher Tatef46723b2012-01-26 14:19:24 -080011597 // If we actually concluded any broadcasts, we might now be able
11598 // to trim the recipients' apps from our working set
11599 if (doTrim) {
11600 trimApplications();
11601 return;
11602 }
11603
11604 } finally {
11605 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011607 }
11608
11609 void removeReceiverLocked(ReceiverList rl) {
11610 mRegisteredReceivers.remove(rl.receiver.asBinder());
11611 int N = rl.size();
11612 for (int i=0; i<N; i++) {
11613 mReceiverResolver.removeFilter(rl.get(i));
11614 }
11615 }
11616
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011617 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011618 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11619 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011620 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011621 try {
11622 r.thread.dispatchPackageBroadcast(cmd, packages);
11623 } catch (RemoteException ex) {
11624 }
11625 }
11626 }
11627 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011628
11629 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11630 int[] users) {
11631 List<ResolveInfo> receivers = null;
11632 try {
11633 HashSet<ComponentName> singleUserReceivers = null;
11634 boolean scannedFirstReceivers = false;
11635 for (int user : users) {
11636 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11637 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011638 if (user != 0 && newReceivers != null) {
11639 // If this is not the primary user, we need to check for
11640 // any receivers that should be filtered out.
11641 for (int i=0; i<newReceivers.size(); i++) {
11642 ResolveInfo ri = newReceivers.get(i);
11643 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11644 newReceivers.remove(i);
11645 i--;
11646 }
11647 }
11648 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011649 if (newReceivers != null && newReceivers.size() == 0) {
11650 newReceivers = null;
11651 }
11652 if (receivers == null) {
11653 receivers = newReceivers;
11654 } else if (newReceivers != null) {
11655 // We need to concatenate the additional receivers
11656 // found with what we have do far. This would be easy,
11657 // but we also need to de-dup any receivers that are
11658 // singleUser.
11659 if (!scannedFirstReceivers) {
11660 // Collect any single user receivers we had already retrieved.
11661 scannedFirstReceivers = true;
11662 for (int i=0; i<receivers.size(); i++) {
11663 ResolveInfo ri = receivers.get(i);
11664 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11665 ComponentName cn = new ComponentName(
11666 ri.activityInfo.packageName, ri.activityInfo.name);
11667 if (singleUserReceivers == null) {
11668 singleUserReceivers = new HashSet<ComponentName>();
11669 }
11670 singleUserReceivers.add(cn);
11671 }
11672 }
11673 }
11674 // Add the new results to the existing results, tracking
11675 // and de-dupping single user receivers.
11676 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011677 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011678 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11679 ComponentName cn = new ComponentName(
11680 ri.activityInfo.packageName, ri.activityInfo.name);
11681 if (singleUserReceivers == null) {
11682 singleUserReceivers = new HashSet<ComponentName>();
11683 }
11684 if (!singleUserReceivers.contains(cn)) {
11685 singleUserReceivers.add(cn);
11686 receivers.add(ri);
11687 }
11688 } else {
11689 receivers.add(ri);
11690 }
11691 }
11692 }
11693 }
11694 } catch (RemoteException ex) {
11695 // pm is in same process, this will never happen.
11696 }
11697 return receivers;
11698 }
11699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011700 private final int broadcastIntentLocked(ProcessRecord callerApp,
11701 String callerPackage, Intent intent, String resolvedType,
11702 IIntentReceiver resultTo, int resultCode, String resultData,
11703 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011704 boolean ordered, boolean sticky, int callingPid, int callingUid,
11705 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 intent = new Intent(intent);
11707
Dianne Hackborne7f97212011-02-24 14:40:20 -080011708 // By default broadcasts do not go to stopped apps.
11709 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11710
Joe Onorato8a9b2202010-02-26 18:56:32 -080011711 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011713 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011715 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011717
Dianne Hackborn139748f2012-09-24 11:36:57 -070011718 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011719 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011720
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011721 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011722 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011723 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011724 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11725 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11726 Slog.w(TAG, "Skipping broadcast of " + intent
11727 + ": user " + userId + " is stopped");
11728 return ActivityManager.BROADCAST_SUCCESS;
11729 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011730 }
11731
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011732 /*
11733 * Prevent non-system code (defined here to be non-persistent
11734 * processes) from sending protected broadcasts.
11735 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011736 int callingAppId = UserHandle.getAppId(callingUid);
11737 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11738 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011739 callingUid == 0) {
11740 // Always okay.
11741 } else if (callerApp == null || !callerApp.persistent) {
11742 try {
11743 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11744 intent.getAction())) {
11745 String msg = "Permission Denial: not allowed to send broadcast "
11746 + intent.getAction() + " from pid="
11747 + callingPid + ", uid=" + callingUid;
11748 Slog.w(TAG, msg);
11749 throw new SecurityException(msg);
11750 }
11751 } catch (RemoteException e) {
11752 Slog.w(TAG, "Remote exception", e);
11753 return ActivityManager.BROADCAST_SUCCESS;
11754 }
11755 }
11756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 // Handle special intents: if this broadcast is from the package
11758 // manager about a package being removed, we need to remove all of
11759 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011760 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011762 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11763 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011764 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 || uidRemoved) {
11766 if (checkComponentPermission(
11767 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011768 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 == PackageManager.PERMISSION_GRANTED) {
11770 if (uidRemoved) {
11771 final Bundle intentExtras = intent.getExtras();
11772 final int uid = intentExtras != null
11773 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11774 if (uid >= 0) {
11775 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11776 synchronized (bs) {
11777 bs.removeUidStatsLocked(uid);
11778 }
11779 }
11780 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011781 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011782 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011783 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011784 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11785 if (list != null && (list.length > 0)) {
11786 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011787 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011788 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011789 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011790 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011791 }
11792 } else {
11793 Uri data = intent.getData();
11794 String ssp;
11795 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11796 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11797 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011798 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11799 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011800 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011801 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011802 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011803 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 }
11806 }
11807 }
11808 } else {
11809 String msg = "Permission Denial: " + intent.getAction()
11810 + " broadcast from " + callerPackage + " (pid=" + callingPid
11811 + ", uid=" + callingUid + ")"
11812 + " requires "
11813 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011814 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 throw new SecurityException(msg);
11816 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011817
11818 // Special case for adding a package: by default turn on compatibility
11819 // mode.
11820 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011821 Uri data = intent.getData();
11822 String ssp;
11823 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11824 mCompatModePackages.handlePackageAddedLocked(ssp,
11825 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 }
11828
11829 /*
11830 * If this is the time zone changed action, queue up a message that will reset the timezone
11831 * of all currently running processes. This message will get queued up before the broadcast
11832 * happens.
11833 */
11834 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11835 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11836 }
11837
Robert Greenwalt03595d02010-11-02 14:08:23 -070011838 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11839 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11840 }
11841
Robert Greenwalt434203a2010-10-11 16:00:27 -070011842 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11843 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11844 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11845 }
11846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 // Add to the sticky list if requested.
11848 if (sticky) {
11849 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11850 callingPid, callingUid)
11851 != PackageManager.PERMISSION_GRANTED) {
11852 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11853 + callingPid + ", uid=" + callingUid
11854 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011855 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 throw new SecurityException(msg);
11857 }
11858 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011859 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011860 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011861 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 }
11863 if (intent.getComponent() != null) {
11864 throw new SecurityException(
11865 "Sticky broadcasts can't target a specific component");
11866 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011867 // We use userId directly here, since the "all" target is maintained
11868 // as a separate set of sticky broadcasts.
11869 if (userId != UserHandle.USER_ALL) {
11870 // But first, if this is not a broadcast to all users, then
11871 // make sure it doesn't conflict with an existing broadcast to
11872 // all users.
11873 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11874 UserHandle.USER_ALL);
11875 if (stickies != null) {
11876 ArrayList<Intent> list = stickies.get(intent.getAction());
11877 if (list != null) {
11878 int N = list.size();
11879 int i;
11880 for (i=0; i<N; i++) {
11881 if (intent.filterEquals(list.get(i))) {
11882 throw new IllegalArgumentException(
11883 "Sticky broadcast " + intent + " for user "
11884 + userId + " conflicts with existing global broadcast");
11885 }
11886 }
11887 }
11888 }
11889 }
11890 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11891 if (stickies == null) {
11892 stickies = new HashMap<String, ArrayList<Intent>>();
11893 mStickyBroadcasts.put(userId, stickies);
11894 }
11895 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 if (list == null) {
11897 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011898 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 }
11900 int N = list.size();
11901 int i;
11902 for (i=0; i<N; i++) {
11903 if (intent.filterEquals(list.get(i))) {
11904 // This sticky already exists, replace it.
11905 list.set(i, new Intent(intent));
11906 break;
11907 }
11908 }
11909 if (i >= N) {
11910 list.add(new Intent(intent));
11911 }
11912 }
11913
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011914 int[] users;
11915 if (userId == UserHandle.USER_ALL) {
11916 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011917 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011918 } else {
11919 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011920 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011921 }
11922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 // Figure out who all will receive this broadcast.
11924 List receivers = null;
11925 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011926 // Need to resolve the intent to interested receivers...
11927 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11928 == 0) {
11929 receivers = collectReceiverComponents(intent, resolvedType, users);
11930 }
11931 if (intent.getComponent() == null) {
11932 registeredReceivers = mReceiverResolver.queryIntent(intent,
11933 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011934 }
11935
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011936 final boolean replacePending =
11937 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11938
Joe Onorato8a9b2202010-02-26 18:56:32 -080011939 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011940 + " replacePending=" + replacePending);
11941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011942 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11943 if (!ordered && NR > 0) {
11944 // If we are not serializing this broadcast, then send the
11945 // registered receivers separately so they don't wait for the
11946 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011947 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11948 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 callerPackage, callingPid, callingUid, requiredPermission,
11950 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011951 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011952 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011953 TAG, "Enqueueing parallel broadcast " + r);
11954 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011955 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011956 queue.enqueueParallelBroadcastLocked(r);
11957 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011959 registeredReceivers = null;
11960 NR = 0;
11961 }
11962
11963 // Merge into one list.
11964 int ir = 0;
11965 if (receivers != null) {
11966 // A special case for PACKAGE_ADDED: do not allow the package
11967 // being added to see this broadcast. This prevents them from
11968 // using this as a back door to get run as soon as they are
11969 // installed. Maybe in the future we want to have a special install
11970 // broadcast or such for apps, but we'd like to deliberately make
11971 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011972 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011973 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11974 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11975 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011976 Uri data = intent.getData();
11977 if (data != null) {
11978 String pkgName = data.getSchemeSpecificPart();
11979 if (pkgName != null) {
11980 skipPackages = new String[] { pkgName };
11981 }
11982 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011983 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011984 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011985 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011986 if (skipPackages != null && (skipPackages.length > 0)) {
11987 for (String skipPackage : skipPackages) {
11988 if (skipPackage != null) {
11989 int NT = receivers.size();
11990 for (int it=0; it<NT; it++) {
11991 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11992 if (curt.activityInfo.packageName.equals(skipPackage)) {
11993 receivers.remove(it);
11994 it--;
11995 NT--;
11996 }
11997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 }
11999 }
12000 }
12001
12002 int NT = receivers != null ? receivers.size() : 0;
12003 int it = 0;
12004 ResolveInfo curt = null;
12005 BroadcastFilter curr = null;
12006 while (it < NT && ir < NR) {
12007 if (curt == null) {
12008 curt = (ResolveInfo)receivers.get(it);
12009 }
12010 if (curr == null) {
12011 curr = registeredReceivers.get(ir);
12012 }
12013 if (curr.getPriority() >= curt.priority) {
12014 // Insert this broadcast record into the final list.
12015 receivers.add(it, curr);
12016 ir++;
12017 curr = null;
12018 it++;
12019 NT++;
12020 } else {
12021 // Skip to the next ResolveInfo in the final list.
12022 it++;
12023 curt = null;
12024 }
12025 }
12026 }
12027 while (ir < NR) {
12028 if (receivers == null) {
12029 receivers = new ArrayList();
12030 }
12031 receivers.add(registeredReceivers.get(ir));
12032 ir++;
12033 }
12034
12035 if ((receivers != null && receivers.size() > 0)
12036 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012037 BroadcastQueue queue = broadcastQueueForIntent(intent);
12038 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012040 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012041 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012042 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012043 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012044 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 if (DEBUG_BROADCAST) {
12046 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012049 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012050 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012051 queue.enqueueOrderedBroadcastLocked(r);
12052 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 }
12055
Dianne Hackborna4972e92012-03-14 10:38:05 -070012056 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012057 }
12058
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012059 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012060 // Refuse possible leaked file descriptors
12061 if (intent != null && intent.hasFileDescriptors() == true) {
12062 throw new IllegalArgumentException("File descriptors passed in Intent");
12063 }
12064
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012065 int flags = intent.getFlags();
12066
12067 if (!mProcessesReady) {
12068 // if the caller really truly claims to know what they're doing, go
12069 // ahead and allow the broadcast without launching any receivers
12070 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12071 intent = new Intent(intent);
12072 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12073 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12074 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12075 + " before boot completion");
12076 throw new IllegalStateException("Cannot broadcast before boot completed");
12077 }
12078 }
12079
12080 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12081 throw new IllegalArgumentException(
12082 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12083 }
12084
12085 return intent;
12086 }
12087
12088 public final int broadcastIntent(IApplicationThread caller,
12089 Intent intent, String resolvedType, IIntentReceiver resultTo,
12090 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012091 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012092 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012093 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012094 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12097 final int callingPid = Binder.getCallingPid();
12098 final int callingUid = Binder.getCallingUid();
12099 final long origId = Binder.clearCallingIdentity();
12100 int res = broadcastIntentLocked(callerApp,
12101 callerApp != null ? callerApp.info.packageName : null,
12102 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012103 resultCode, resultData, map, requiredPermission, serialized, sticky,
12104 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 Binder.restoreCallingIdentity(origId);
12106 return res;
12107 }
12108 }
12109
12110 int broadcastIntentInPackage(String packageName, int uid,
12111 Intent intent, String resolvedType, IIntentReceiver resultTo,
12112 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012113 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012114 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012115 intent = verifyBroadcastLocked(intent);
12116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 final long origId = Binder.clearCallingIdentity();
12118 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12119 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012120 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012121 Binder.restoreCallingIdentity(origId);
12122 return res;
12123 }
12124 }
12125
Amith Yamasani742a6712011-05-04 14:49:28 -070012126 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 // Refuse possible leaked file descriptors
12128 if (intent != null && intent.hasFileDescriptors() == true) {
12129 throw new IllegalArgumentException("File descriptors passed in Intent");
12130 }
12131
Dianne Hackborn139748f2012-09-24 11:36:57 -070012132 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012133 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012135 synchronized(this) {
12136 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12137 != PackageManager.PERMISSION_GRANTED) {
12138 String msg = "Permission Denial: unbroadcastIntent() from pid="
12139 + Binder.getCallingPid()
12140 + ", uid=" + Binder.getCallingUid()
12141 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012142 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012143 throw new SecurityException(msg);
12144 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012145 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12146 if (stickies != null) {
12147 ArrayList<Intent> list = stickies.get(intent.getAction());
12148 if (list != null) {
12149 int N = list.size();
12150 int i;
12151 for (i=0; i<N; i++) {
12152 if (intent.filterEquals(list.get(i))) {
12153 list.remove(i);
12154 break;
12155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012157 if (list.size() <= 0) {
12158 stickies.remove(intent.getAction());
12159 }
12160 }
12161 if (stickies.size() <= 0) {
12162 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012163 }
12164 }
12165 }
12166 }
12167
12168 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12169 String resultData, Bundle resultExtras, boolean resultAbort,
12170 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012171 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12172 if (r == null) {
12173 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012174 return false;
12175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176
Christopher Tatef46723b2012-01-26 14:19:24 -080012177 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12178 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012179 }
12180
12181 public void finishReceiver(IBinder who, int resultCode, String resultData,
12182 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012183 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184
12185 // Refuse possible leaked file descriptors
12186 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12187 throw new IllegalArgumentException("File descriptors passed in Bundle");
12188 }
12189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012190 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012191 try {
12192 boolean doNext = false;
12193 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194
Christopher Tatef46723b2012-01-26 14:19:24 -080012195 synchronized(this) {
12196 r = broadcastRecordForReceiverLocked(who);
12197 if (r != null) {
12198 doNext = r.queue.finishReceiverLocked(r, resultCode,
12199 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012201 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012202
Christopher Tatef46723b2012-01-26 14:19:24 -080012203 if (doNext) {
12204 r.queue.processNextBroadcast(false);
12205 }
12206 trimApplications();
12207 } finally {
12208 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212 // =========================================================
12213 // INSTRUMENTATION
12214 // =========================================================
12215
12216 public boolean startInstrumentation(ComponentName className,
12217 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012218 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
12219 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012220 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012221 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012222 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 // Refuse possible leaked file descriptors
12224 if (arguments != null && arguments.hasFileDescriptors()) {
12225 throw new IllegalArgumentException("File descriptors passed in Bundle");
12226 }
12227
12228 synchronized(this) {
12229 InstrumentationInfo ii = null;
12230 ApplicationInfo ai = null;
12231 try {
12232 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012233 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012234 ai = AppGlobals.getPackageManager().getApplicationInfo(
12235 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012237 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238 }
12239 if (ii == null) {
12240 reportStartInstrumentationFailure(watcher, className,
12241 "Unable to find instrumentation info for: " + className);
12242 return false;
12243 }
12244 if (ai == null) {
12245 reportStartInstrumentationFailure(watcher, className,
12246 "Unable to find instrumentation target package: " + ii.targetPackage);
12247 return false;
12248 }
12249
12250 int match = mContext.getPackageManager().checkSignatures(
12251 ii.targetPackage, ii.packageName);
12252 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12253 String msg = "Permission Denial: starting instrumentation "
12254 + className + " from pid="
12255 + Binder.getCallingPid()
12256 + ", uid=" + Binder.getCallingPid()
12257 + " not allowed because package " + ii.packageName
12258 + " does not have a signature matching the target "
12259 + ii.targetPackage;
12260 reportStartInstrumentationFailure(watcher, className, msg);
12261 throw new SecurityException(msg);
12262 }
12263
12264 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012265 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012266 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012267 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012268 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012269 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012270 app.instrumentationProfileFile = profileFile;
12271 app.instrumentationArguments = arguments;
12272 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012273 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012274 app.instrumentationResultClass = className;
12275 Binder.restoreCallingIdentity(origId);
12276 }
12277
12278 return true;
12279 }
12280
12281 /**
12282 * Report errors that occur while attempting to start Instrumentation. Always writes the
12283 * error to the logs, but if somebody is watching, send the report there too. This enables
12284 * the "am" command to report errors with more information.
12285 *
12286 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12287 * @param cn The component name of the instrumentation.
12288 * @param report The error report.
12289 */
12290 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12291 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012292 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012293 try {
12294 if (watcher != null) {
12295 Bundle results = new Bundle();
12296 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12297 results.putString("Error", report);
12298 watcher.instrumentationStatus(cn, -1, results);
12299 }
12300 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012301 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 }
12303 }
12304
12305 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12306 if (app.instrumentationWatcher != null) {
12307 try {
12308 // NOTE: IInstrumentationWatcher *must* be oneway here
12309 app.instrumentationWatcher.instrumentationFinished(
12310 app.instrumentationClass,
12311 resultCode,
12312 results);
12313 } catch (RemoteException e) {
12314 }
12315 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012316 if (app.instrumentationUiAutomationConnection != null) {
12317 try {
12318 app.instrumentationUiAutomationConnection.shutdown();
12319 } catch (RemoteException re) {
12320 /* ignore */
12321 }
12322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012324 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012325 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012326 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012327 app.instrumentationProfileFile = null;
12328 app.instrumentationArguments = null;
12329
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012330 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012331 }
12332
12333 public void finishInstrumentation(IApplicationThread target,
12334 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012335 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 // Refuse possible leaked file descriptors
12337 if (results != null && results.hasFileDescriptors()) {
12338 throw new IllegalArgumentException("File descriptors passed in Intent");
12339 }
12340
12341 synchronized(this) {
12342 ProcessRecord app = getRecordForAppLocked(target);
12343 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012344 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 return;
12346 }
12347 final long origId = Binder.clearCallingIdentity();
12348 finishInstrumentationLocked(app, resultCode, results);
12349 Binder.restoreCallingIdentity(origId);
12350 }
12351 }
12352
12353 // =========================================================
12354 // CONFIGURATION
12355 // =========================================================
12356
12357 public ConfigurationInfo getDeviceConfigurationInfo() {
12358 ConfigurationInfo config = new ConfigurationInfo();
12359 synchronized (this) {
12360 config.reqTouchScreen = mConfiguration.touchscreen;
12361 config.reqKeyboardType = mConfiguration.keyboard;
12362 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012363 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12364 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012365 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12366 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012367 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12368 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012369 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12370 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012371 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012372 }
12373 return config;
12374 }
12375
12376 public Configuration getConfiguration() {
12377 Configuration ci;
12378 synchronized(this) {
12379 ci = new Configuration(mConfiguration);
12380 }
12381 return ci;
12382 }
12383
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012384 public void updatePersistentConfiguration(Configuration values) {
12385 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12386 "updateConfiguration()");
12387 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12388 "updateConfiguration()");
12389 if (values == null) {
12390 throw new NullPointerException("Configuration must not be null");
12391 }
12392
12393 synchronized(this) {
12394 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012395 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012396 Binder.restoreCallingIdentity(origId);
12397 }
12398 }
12399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 public void updateConfiguration(Configuration values) {
12401 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12402 "updateConfiguration()");
12403
12404 synchronized(this) {
12405 if (values == null && mWindowManager != null) {
12406 // sentinel: fetch the current configuration from the window manager
12407 values = mWindowManager.computeNewConfiguration();
12408 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012409
12410 if (mWindowManager != null) {
12411 mProcessList.applyDisplaySize(mWindowManager);
12412 }
12413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012415 if (values != null) {
12416 Settings.System.clearConfiguration(values);
12417 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012418 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 Binder.restoreCallingIdentity(origId);
12420 }
12421 }
12422
12423 /**
12424 * Do either or both things: (1) change the current configuration, and (2)
12425 * make sure the given activity is running with the (now) current
12426 * configuration. Returns true if the activity has been left running, or
12427 * false if <var>starting</var> is being destroyed to match the new
12428 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012429 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012430 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012431 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012432 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012433 // do nothing if we are headless
12434 if (mHeadless) return true;
12435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012436 int changes = 0;
12437
12438 boolean kept = true;
12439
12440 if (values != null) {
12441 Configuration newConfig = new Configuration(mConfiguration);
12442 changes = newConfig.updateFrom(values);
12443 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012444 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012445 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 }
12447
Doug Zongker2bec3d42009-12-04 12:52:44 -080012448 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449
Dianne Hackborn813075a62011-11-14 17:45:19 -080012450 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 saveLocaleLocked(values.locale,
12452 !values.locale.equals(mConfiguration.locale),
12453 values.userSetLocale);
12454 }
12455
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012456 mConfigurationSeq++;
12457 if (mConfigurationSeq <= 0) {
12458 mConfigurationSeq = 1;
12459 }
12460 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012462 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012463
12464 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012465
12466 // TODO: If our config changes, should we auto dismiss any currently
12467 // showing dialogs?
12468 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012469
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012470 AttributeCache ac = AttributeCache.instance();
12471 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012472 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012475 // Make sure all resources in our process are updated
12476 // right now, so that anyone who is going to retrieve
12477 // resource values after we return will be sure to get
12478 // the new ones. This is especially important during
12479 // boot, where the first config change needs to guarantee
12480 // all resources have that config before following boot
12481 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012482 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012483
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012484 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012485 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012486 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012487 mHandler.sendMessage(msg);
12488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012490 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12491 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 try {
12493 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012494 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012495 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012496 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012497 }
12498 } catch (Exception e) {
12499 }
12500 }
12501 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012502 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012503 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12504 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012506 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012507 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012508 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12509 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12510 broadcastIntentLocked(null, null, intent,
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012511 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012512 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 }
12515 }
12516
12517 if (changes != 0 && starting == null) {
12518 // If the configuration changed, and the caller is not already
12519 // in the process of starting an activity, then find the top
12520 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012521 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012522 }
12523
12524 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012525 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012526 // And we need to make sure at this point that all other activities
12527 // are made visible with the correct configuration.
12528 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012529 }
12530
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012531 if (values != null && mWindowManager != null) {
12532 mWindowManager.setNewConfiguration(mConfiguration);
12533 }
12534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 return kept;
12536 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012537
12538 /**
12539 * Decide based on the configuration whether we should shouw the ANR,
12540 * crash, etc dialogs. The idea is that if there is no affordnace to
12541 * press the on-screen buttons, we shouldn't show the dialog.
12542 *
12543 * A thought: SystemUI might also want to get told about this, the Power
12544 * dialog / global actions also might want different behaviors.
12545 */
12546 private static final boolean shouldShowDialogs(Configuration config) {
12547 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12548 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012550
12551 /**
12552 * Save the locale. You must be inside a synchronized (this) block.
12553 */
12554 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12555 if(isDiff) {
12556 SystemProperties.set("user.language", l.getLanguage());
12557 SystemProperties.set("user.region", l.getCountry());
12558 }
12559
12560 if(isPersist) {
12561 SystemProperties.set("persist.sys.language", l.getLanguage());
12562 SystemProperties.set("persist.sys.country", l.getCountry());
12563 SystemProperties.set("persist.sys.localevar", l.getVariant());
12564 }
12565 }
12566
Adam Powelldd8fab22012-03-22 17:47:27 -070012567 @Override
12568 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12569 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012570 return srec != null && srec.task.affinity != null &&
12571 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012572 }
12573
12574 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12575 Intent resultData) {
12576 ComponentName dest = destIntent.getComponent();
12577
12578 synchronized (this) {
12579 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012580 if (srec == null) {
12581 return false;
12582 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012583 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12584 final int start = history.indexOf(srec);
12585 if (start < 0) {
12586 // Current activity is not in history stack; do nothing.
12587 return false;
12588 }
12589 int finishTo = start - 1;
12590 ActivityRecord parent = null;
12591 boolean foundParentInTask = false;
12592 if (dest != null) {
12593 TaskRecord tr = srec.task;
12594 for (int i = start - 1; i >= 0; i--) {
12595 ActivityRecord r = history.get(i);
12596 if (tr != r.task) {
12597 // Couldn't find parent in the same task; stop at the one above this.
12598 // (Root of current task; in-app "home" behavior)
12599 // Always at least finish the current activity.
12600 finishTo = Math.min(start - 1, i + 1);
12601 parent = history.get(finishTo);
12602 break;
12603 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12604 r.info.name.equals(dest.getClassName())) {
12605 finishTo = i;
12606 parent = r;
12607 foundParentInTask = true;
12608 break;
12609 }
12610 }
12611 }
12612
12613 if (mController != null) {
12614 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12615 if (next != null) {
12616 // ask watcher if this is allowed
12617 boolean resumeOK = true;
12618 try {
12619 resumeOK = mController.activityResuming(next.packageName);
12620 } catch (RemoteException e) {
12621 mController = null;
12622 }
12623
12624 if (!resumeOK) {
12625 return false;
12626 }
12627 }
12628 }
12629 final long origId = Binder.clearCallingIdentity();
12630 for (int i = start; i > finishTo; i--) {
12631 ActivityRecord r = history.get(i);
12632 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012633 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012634 // Only return the supplied result for the first activity finished
12635 resultCode = Activity.RESULT_CANCELED;
12636 resultData = null;
12637 }
12638
12639 if (parent != null && foundParentInTask) {
12640 final int parentLaunchMode = parent.info.launchMode;
12641 final int destIntentFlags = destIntent.getFlags();
12642 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12643 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12644 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12645 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012646 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012647 } else {
12648 try {
12649 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012650 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012651 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12652 null, aInfo, parent.appToken, null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012653 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
12654 0, null, true, null);
Adam Powelldd8fab22012-03-22 17:47:27 -070012655 foundParentInTask = res == ActivityManager.START_SUCCESS;
12656 } catch (RemoteException e) {
12657 foundParentInTask = false;
12658 }
12659 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012660 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012661 }
12662 }
12663 Binder.restoreCallingIdentity(origId);
12664 return foundParentInTask;
12665 }
12666 }
12667
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012668 public int getLaunchedFromUid(IBinder activityToken) {
12669 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12670 if (srec == null) {
12671 return -1;
12672 }
12673 return srec.launchedFromUid;
12674 }
12675
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012676 public String getLaunchedFromPackage(IBinder activityToken) {
12677 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12678 if (srec == null) {
12679 return null;
12680 }
12681 return srec.launchedFromPackage;
12682 }
12683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 // =========================================================
12685 // LIFETIME MANAGEMENT
12686 // =========================================================
12687
Christopher Tatef46723b2012-01-26 14:19:24 -080012688 // Returns which broadcast queue the app is the current [or imminent] receiver
12689 // on, or 'null' if the app is not an active broadcast recipient.
12690 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12691 BroadcastRecord r = app.curReceiver;
12692 if (r != null) {
12693 return r.queue;
12694 }
12695
12696 // It's not the current receiver, but it might be starting up to become one
12697 synchronized (this) {
12698 for (BroadcastQueue queue : mBroadcastQueues) {
12699 r = queue.mPendingBroadcast;
12700 if (r != null && r.curApp == app) {
12701 // found it; report which queue it's in
12702 return queue;
12703 }
12704 }
12705 }
12706
12707 return null;
12708 }
12709
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012710 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012711 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012712 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012713 // This adjustment has already been computed. If we are calling
12714 // from the top, we may have already computed our adjustment with
12715 // an earlier hidden adjustment that isn't really for us... if
12716 // so, use the new hidden adjustment.
12717 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012718 if (app.hasActivities) {
12719 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12720 } else if (app.hasClientActivities) {
12721 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12722 } else {
12723 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12724 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012725 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012726 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012727 }
12728
12729 if (app.thread == null) {
12730 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012731 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012732 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 }
12734
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012735 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12736 app.adjSource = null;
12737 app.adjTarget = null;
12738 app.empty = false;
12739 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012740 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012741
12742 final int activitiesSize = app.activities.size();
12743
Dianne Hackborn7d608422011-08-07 16:24:18 -070012744 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012745 // The max adjustment doesn't allow this app to be anything
12746 // below foreground, so it is not worth doing work for it.
12747 app.adjType = "fixed";
12748 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012749 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012750 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012751 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012752 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012753 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012754 // System process can do UI, and when they do we want to have
12755 // them trim their memory after the user leaves the UI. To
12756 // facilitate this, here we need to determine whether or not it
12757 // is currently showing UI.
12758 app.systemNoUi = true;
12759 if (app == TOP_APP) {
12760 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012761 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012762 } else if (activitiesSize > 0) {
12763 for (int j = 0; j < activitiesSize; j++) {
12764 final ActivityRecord r = app.activities.get(j);
12765 if (r.visible) {
12766 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012767 }
12768 if (r.app == app) {
12769 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012770 }
12771 }
12772 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012773 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012774 }
12775
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012776 app.keeping = false;
12777 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012778 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779
The Android Open Source Project4df24232009-03-05 14:34:35 -080012780 // Determine the importance of the process, starting with most
12781 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012783 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012784 boolean foregroundActivities = false;
12785 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012786 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012787 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012788 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012789 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012790 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012791 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012792 foregroundActivities = true;
12793 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012794 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012795 } else if (app.instrumentationClass != null) {
12796 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012797 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012798 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012799 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012800 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012801 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012802 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012803 // counts as being in the foreground for OOM killer purposes.
12804 // It's placed in a sched group based on the nature of the
12805 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012806 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012807 schedGroup = (queue == mFgBroadcastQueue)
12808 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012809 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 } else if (app.executingServices.size() > 0) {
12811 // An app that is currently executing a service callback also
12812 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012813 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012814 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012815 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012816 } else {
12817 // Assume process is hidden (has activities); we will correct
12818 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012820 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012821 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012822 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012823 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012824
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012825 boolean hasStoppingActivities = false;
12826
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012827 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012828 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012829 for (int j = 0; j < activitiesSize; j++) {
12830 final ActivityRecord r = app.activities.get(j);
12831 if (r.visible) {
12832 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012833 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12834 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012835 app.adjType = "visible";
12836 }
12837 schedGroup = Process.THREAD_GROUP_DEFAULT;
12838 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012839 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012840 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012841 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012842 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012843 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12844 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012845 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012846 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012847 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012848 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012849 } else if (r.state == ActivityState.STOPPING) {
12850 // We will apply the actual adjustment later, because
12851 // we want to allow this process to immediately go through
12852 // any memory trimming that is in effect.
12853 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012854 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012855 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012856 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012857 if (r.app == app) {
12858 app.hasActivities = true;
12859 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012860 }
12861 }
12862
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012863 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012864 if (app.hasClientActivities) {
12865 adj = clientHiddenAdj;
12866 app.adjType = "bg-client-act";
12867 } else {
12868 // Whoops, this process is completely empty as far as we know
12869 // at this point.
12870 adj = emptyAdj;
12871 app.empty = true;
12872 app.adjType = "bg-empty";
12873 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012874 }
12875
Dianne Hackborn7d608422011-08-07 16:24:18 -070012876 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012877 if (app.foregroundServices) {
12878 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012879 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012880 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012881 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012882 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012883 } else if (app.forcingToForeground != null) {
12884 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012885 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012886 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012887 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012888 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012889 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012890 }
12891 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012892
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012893 if (app.foregroundServices) {
12894 interesting = true;
12895 }
12896
Dianne Hackborn7d608422011-08-07 16:24:18 -070012897 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012898 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012899 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012900 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012901 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012902 app.adjType = "heavy";
12903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904
Dianne Hackborn7d608422011-08-07 16:24:18 -070012905 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012906 // This process is hosting what we currently consider to be the
12907 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012908 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012909 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012910 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012911 app.adjType = "home";
12912 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012913
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012914 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12915 && app.activities.size() > 0) {
12916 // This was the previous process that showed UI to the user.
12917 // We want to try to keep it around more aggressively, to give
12918 // a good experience around switching between two apps.
12919 adj = ProcessList.PREVIOUS_APP_ADJ;
12920 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12921 app.hidden = false;
12922 app.adjType = "previous";
12923 }
12924
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012925 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12926 + " reason=" + app.adjType);
12927
The Android Open Source Project4df24232009-03-05 14:34:35 -080012928 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 // there are applications dependent on our services or providers, but
12930 // this gives us a baseline and makes sure we don't get into an
12931 // infinite recursion.
12932 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012933 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934
Christopher Tate6fa95972009-06-05 18:43:55 -070012935 if (mBackupTarget != null && app == mBackupTarget.app) {
12936 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012937 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012938 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012939 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012940 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012941 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012942 }
12943 }
12944
Dianne Hackborn7d608422011-08-07 16:24:18 -070012945 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012946 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 final long now = SystemClock.uptimeMillis();
12948 // This process is more important if the top activity is
12949 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012950 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012951 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012952 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012954 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012955 // If this process has shown some UI, let it immediately
12956 // go to the LRU list because it may be pretty heavy with
12957 // UI stuff. We'll tag it with a label just to help
12958 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012959 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012960 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012962 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012963 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012964 // This service has seen some activity within
12965 // recent memory, so we will keep its process ahead
12966 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012967 if (adj > ProcessList.SERVICE_ADJ) {
12968 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012969 app.adjType = "started-services";
12970 app.hidden = false;
12971 }
12972 }
12973 // If we have let the service slide into the background
12974 // state, still have some text describing what it is doing
12975 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012976 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012977 app.adjType = "started-bg-services";
12978 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012979 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012980 // Don't kill this process because it is doing work; it
12981 // has said it is doing work.
12982 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012983 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012984 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012985 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012986 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012988 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012989 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012990 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012991 // XXX should compute this based on the max of
12992 // all connected clients.
12993 ConnectionRecord cr = clist.get(i);
12994 if (cr.binding.client == app) {
12995 // Binding to ourself is not interesting.
12996 continue;
12997 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012998 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012999 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013000 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013001 int myHiddenAdj = hiddenAdj;
13002 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013003 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013004 myHiddenAdj = client.hiddenAdj;
13005 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013006 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013007 }
13008 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013009 int myClientHiddenAdj = clientHiddenAdj;
13010 if (myClientHiddenAdj > client.clientHiddenAdj) {
13011 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
13012 myClientHiddenAdj = client.clientHiddenAdj;
13013 } else {
13014 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
13015 }
13016 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013017 int myEmptyAdj = emptyAdj;
13018 if (myEmptyAdj > client.emptyAdj) {
13019 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
13020 myEmptyAdj = client.emptyAdj;
13021 } else {
13022 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
13023 }
13024 }
13025 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013026 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013027 String adjType = null;
13028 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13029 // Not doing bind OOM management, so treat
13030 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013031 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013032 // If this process has shown some UI, let it immediately
13033 // go to the LRU list because it may be pretty heavy with
13034 // UI stuff. We'll tag it with a label just to help
13035 // debug and understand what is going on.
13036 if (adj > clientAdj) {
13037 adjType = "bound-bg-ui-services";
13038 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013039 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013040 clientAdj = adj;
13041 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013042 if (now >= (s.lastActivity
13043 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013044 // This service has not seen activity within
13045 // recent memory, so allow it to drop to the
13046 // LRU list if there is no other reason to keep
13047 // it around. We'll also tag it with a label just
13048 // to help debug and undertand what is going on.
13049 if (adj > clientAdj) {
13050 adjType = "bound-bg-services";
13051 }
13052 clientAdj = adj;
13053 }
13054 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013055 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13056 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
13057 // If this connection is keeping the service
13058 // created, then we want to try to better follow
13059 // its memory management semantics for activities.
13060 // That is, if it is sitting in the background
13061 // LRU list as a hidden process (with activities),
13062 // we don't want the service it is connected to
13063 // to go into the empty LRU and quickly get killed,
13064 // because I'll we'll do is just end up restarting
13065 // the service.
13066 app.hasClientActivities |= client.hasActivities;
13067 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013068 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013069 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013070 // If this process has recently shown UI, and
13071 // the process that is binding to it is less
13072 // important than being visible, then we don't
13073 // care about the binding as much as we care
13074 // about letting this process get into the LRU
13075 // list to be killed and restarted if needed for
13076 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013077 if (app.hasShownUi && app != mHomeProcess
13078 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013079 adjType = "bound-bg-ui-services";
13080 } else {
13081 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13082 |Context.BIND_IMPORTANT)) != 0) {
13083 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013084 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13085 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13086 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13087 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13088 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013089 adj = clientAdj;
13090 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013091 app.pendingUiClean = true;
13092 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13093 adj = ProcessList.VISIBLE_APP_ADJ;
13094 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013095 }
13096 if (!client.hidden) {
13097 app.hidden = false;
13098 }
13099 if (client.keeping) {
13100 app.keeping = true;
13101 }
13102 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013103 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013104 }
13105 if (adjType != null) {
13106 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013107 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13108 .REASON_SERVICE_IN_USE;
13109 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013110 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013111 app.adjTarget = s.name;
13112 }
13113 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13114 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13115 schedGroup = Process.THREAD_GROUP_DEFAULT;
13116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013117 }
13118 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013119 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013120 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013121 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013122 (a.visible || a.state == ActivityState.RESUMED
13123 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013124 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013125 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13126 schedGroup = Process.THREAD_GROUP_DEFAULT;
13127 }
13128 app.hidden = false;
13129 app.adjType = "service";
13130 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13131 .REASON_SERVICE_IN_USE;
13132 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013133 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013134 app.adjTarget = s.name;
13135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 }
13138 }
13139 }
13140 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013141
Dianne Hackborn287952c2010-09-22 22:34:31 -070013142 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013143 // would like to avoid killing it unless it would prevent the current
13144 // application from running. By default we put the process in
13145 // with the rest of the background processes; as we scan through
13146 // its services we may bump it up from there.
13147 if (adj > hiddenAdj) {
13148 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013149 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013150 app.adjType = "bg-services";
13151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 }
13153
Dianne Hackborn7d608422011-08-07 16:24:18 -070013154 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013155 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013156 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013157 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013158 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013159 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013160 for (int i = cpr.connections.size()-1;
13161 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13162 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13163 i--) {
13164 ContentProviderConnection conn = cpr.connections.get(i);
13165 ProcessRecord client = conn.client;
13166 if (client == app) {
13167 // Being our own client is not interesting.
13168 continue;
13169 }
13170 int myHiddenAdj = hiddenAdj;
13171 if (myHiddenAdj > client.hiddenAdj) {
13172 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13173 myHiddenAdj = client.hiddenAdj;
13174 } else {
13175 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013176 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013177 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013178 int myClientHiddenAdj = clientHiddenAdj;
13179 if (myClientHiddenAdj > client.clientHiddenAdj) {
13180 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13181 myClientHiddenAdj = client.clientHiddenAdj;
13182 } else {
13183 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13184 }
13185 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013186 int myEmptyAdj = emptyAdj;
13187 if (myEmptyAdj > client.emptyAdj) {
13188 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13189 myEmptyAdj = client.emptyAdj;
13190 } else {
13191 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13192 }
13193 }
13194 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013195 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013196 if (adj > clientAdj) {
13197 if (app.hasShownUi && app != mHomeProcess
13198 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13199 app.adjType = "bg-ui-provider";
13200 } else {
13201 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13202 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13203 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013204 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013205 if (!client.hidden) {
13206 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013208 if (client.keeping) {
13209 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013210 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013211 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13212 .REASON_PROVIDER_IN_USE;
13213 app.adjSource = client;
13214 app.adjSourceOom = clientAdj;
13215 app.adjTarget = cpr.name;
13216 }
13217 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13218 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 }
13220 }
13221 // If the provider has external (non-framework) process
13222 // dependencies, ensure that its adjustment is at least
13223 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013224 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013225 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13226 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013227 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013228 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013229 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013230 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013231 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 }
13233 }
13234 }
13235 }
13236
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013237 if (adj == ProcessList.SERVICE_ADJ) {
13238 if (doingAll) {
13239 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13240 mNewNumServiceProcs++;
13241 }
13242 if (app.serviceb) {
13243 adj = ProcessList.SERVICE_B_ADJ;
13244 }
13245 } else {
13246 app.serviceb = false;
13247 }
13248
13249 app.nonStoppingAdj = adj;
13250
13251 if (hasStoppingActivities) {
13252 // Only upgrade adjustment.
13253 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13254 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13255 app.adjType = "stopping";
13256 }
13257 }
13258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013259 app.curRawAdj = adj;
13260
Joe Onorato8a9b2202010-02-26 18:56:32 -080013261 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13263 if (adj > app.maxAdj) {
13264 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013265 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013266 schedGroup = Process.THREAD_GROUP_DEFAULT;
13267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013268 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013269 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013270 app.keeping = true;
13271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013272
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013273 if (app.hasAboveClient) {
13274 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13275 // then we need to drop its adjustment to be lower than the service's
13276 // in order to honor the request. We want to drop it by one adjustment
13277 // level... but there is special meaning applied to various levels so
13278 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013279 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013280 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013281 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13282 adj = ProcessList.VISIBLE_APP_ADJ;
13283 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13284 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13285 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13286 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013287 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013288 adj++;
13289 }
13290 }
13291
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013292 int importance = app.memImportance;
13293 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13294 app.curAdj = adj;
13295 app.curSchedGroup = schedGroup;
13296 if (!interesting) {
13297 // For this reporting, if there is not something explicitly
13298 // interesting in this process then we will push it to the
13299 // background importance.
13300 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13301 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13302 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13303 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13304 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13305 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13306 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13307 } else if (adj >= ProcessList.SERVICE_ADJ) {
13308 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13309 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13310 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13311 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13312 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13313 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13314 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13315 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13316 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13317 } else {
13318 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13319 }
13320 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013321
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013322 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13323 if (foregroundActivities != app.foregroundActivities) {
13324 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13325 }
13326 if (changes != 0) {
13327 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13328 app.memImportance = importance;
13329 app.foregroundActivities = foregroundActivities;
13330 int i = mPendingProcessChanges.size()-1;
13331 ProcessChangeItem item = null;
13332 while (i >= 0) {
13333 item = mPendingProcessChanges.get(i);
13334 if (item.pid == app.pid) {
13335 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13336 break;
13337 }
13338 i--;
13339 }
13340 if (i < 0) {
13341 // No existing item in pending changes; need a new one.
13342 final int NA = mAvailProcessChanges.size();
13343 if (NA > 0) {
13344 item = mAvailProcessChanges.remove(NA-1);
13345 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13346 } else {
13347 item = new ProcessChangeItem();
13348 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13349 }
13350 item.changes = 0;
13351 item.pid = app.pid;
13352 item.uid = app.info.uid;
13353 if (mPendingProcessChanges.size() == 0) {
13354 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13355 "*** Enqueueing dispatch processes changed!");
13356 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13357 }
13358 mPendingProcessChanges.add(item);
13359 }
13360 item.changes |= changes;
13361 item.importance = importance;
13362 item.foregroundActivities = foregroundActivities;
13363 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13364 + Integer.toHexString(System.identityHashCode(item))
13365 + " " + app.toShortString() + ": changes=" + item.changes
13366 + " importance=" + item.importance
13367 + " foreground=" + item.foregroundActivities
13368 + " type=" + app.adjType + " source=" + app.adjSource
13369 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013370 }
13371
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013372 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 }
13374
13375 /**
13376 * Ask a given process to GC right now.
13377 */
13378 final void performAppGcLocked(ProcessRecord app) {
13379 try {
13380 app.lastRequestedGc = SystemClock.uptimeMillis();
13381 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013382 if (app.reportLowMemory) {
13383 app.reportLowMemory = false;
13384 app.thread.scheduleLowMemory();
13385 } else {
13386 app.thread.processInBackground();
13387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013388 }
13389 } catch (Exception e) {
13390 // whatever.
13391 }
13392 }
13393
13394 /**
13395 * Returns true if things are idle enough to perform GCs.
13396 */
Josh Bartel7f208742010-02-25 11:01:44 -060013397 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013398 boolean processingBroadcasts = false;
13399 for (BroadcastQueue q : mBroadcastQueues) {
13400 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13401 processingBroadcasts = true;
13402 }
13403 }
13404 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013405 && (mSleeping || (mMainStack.mResumedActivity != null &&
13406 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 }
13408
13409 /**
13410 * Perform GCs on all processes that are waiting for it, but only
13411 * if things are idle.
13412 */
13413 final void performAppGcsLocked() {
13414 final int N = mProcessesToGc.size();
13415 if (N <= 0) {
13416 return;
13417 }
Josh Bartel7f208742010-02-25 11:01:44 -060013418 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013419 while (mProcessesToGc.size() > 0) {
13420 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013421 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013422 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13423 <= SystemClock.uptimeMillis()) {
13424 // To avoid spamming the system, we will GC processes one
13425 // at a time, waiting a few seconds between each.
13426 performAppGcLocked(proc);
13427 scheduleAppGcsLocked();
13428 return;
13429 } else {
13430 // It hasn't been long enough since we last GCed this
13431 // process... put it in the list to wait for its time.
13432 addProcessToGcListLocked(proc);
13433 break;
13434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013435 }
13436 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013437
13438 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013439 }
13440 }
13441
13442 /**
13443 * If all looks good, perform GCs on all processes waiting for them.
13444 */
13445 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013446 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 performAppGcsLocked();
13448 return;
13449 }
13450 // Still not idle, wait some more.
13451 scheduleAppGcsLocked();
13452 }
13453
13454 /**
13455 * Schedule the execution of all pending app GCs.
13456 */
13457 final void scheduleAppGcsLocked() {
13458 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013459
13460 if (mProcessesToGc.size() > 0) {
13461 // Schedule a GC for the time to the next process.
13462 ProcessRecord proc = mProcessesToGc.get(0);
13463 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13464
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013465 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013466 long now = SystemClock.uptimeMillis();
13467 if (when < (now+GC_TIMEOUT)) {
13468 when = now + GC_TIMEOUT;
13469 }
13470 mHandler.sendMessageAtTime(msg, when);
13471 }
13472 }
13473
13474 /**
13475 * Add a process to the array of processes waiting to be GCed. Keeps the
13476 * list in sorted order by the last GC time. The process can't already be
13477 * on the list.
13478 */
13479 final void addProcessToGcListLocked(ProcessRecord proc) {
13480 boolean added = false;
13481 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13482 if (mProcessesToGc.get(i).lastRequestedGc <
13483 proc.lastRequestedGc) {
13484 added = true;
13485 mProcessesToGc.add(i+1, proc);
13486 break;
13487 }
13488 }
13489 if (!added) {
13490 mProcessesToGc.add(0, proc);
13491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492 }
13493
13494 /**
13495 * Set up to ask a process to GC itself. This will either do it
13496 * immediately, or put it on the list of processes to gc the next
13497 * time things are idle.
13498 */
13499 final void scheduleAppGcLocked(ProcessRecord app) {
13500 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013501 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502 return;
13503 }
13504 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013505 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 scheduleAppGcsLocked();
13507 }
13508 }
13509
Dianne Hackborn287952c2010-09-22 22:34:31 -070013510 final void checkExcessivePowerUsageLocked(boolean doKills) {
13511 updateCpuStatsNow();
13512
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013513 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013514 boolean doWakeKills = doKills;
13515 boolean doCpuKills = doKills;
13516 if (mLastPowerCheckRealtime == 0) {
13517 doWakeKills = false;
13518 }
13519 if (mLastPowerCheckUptime == 0) {
13520 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013521 }
13522 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013523 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013524 }
13525 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013526 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13527 final long curUptime = SystemClock.uptimeMillis();
13528 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13529 mLastPowerCheckRealtime = curRealtime;
13530 mLastPowerCheckUptime = curUptime;
13531 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13532 doWakeKills = false;
13533 }
13534 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13535 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013536 }
13537 int i = mLruProcesses.size();
13538 while (i > 0) {
13539 i--;
13540 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013541 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013542 long wtime;
13543 synchronized (stats) {
13544 wtime = stats.getProcessWakeTime(app.info.uid,
13545 app.pid, curRealtime);
13546 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013547 long wtimeUsed = wtime - app.lastWakeTime;
13548 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13549 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013550 StringBuilder sb = new StringBuilder(128);
13551 sb.append("Wake for ");
13552 app.toShortString(sb);
13553 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013554 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013555 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013556 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013557 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013558 sb.append((wtimeUsed*100)/realtimeSince);
13559 sb.append("%)");
13560 Slog.i(TAG, sb.toString());
13561 sb.setLength(0);
13562 sb.append("CPU for ");
13563 app.toShortString(sb);
13564 sb.append(": over ");
13565 TimeUtils.formatDuration(uptimeSince, sb);
13566 sb.append(" used ");
13567 TimeUtils.formatDuration(cputimeUsed, sb);
13568 sb.append(" (");
13569 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013570 sb.append("%)");
13571 Slog.i(TAG, sb.toString());
13572 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013573 // If a process has held a wake lock for more
13574 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013575 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013576 if (doWakeKills && realtimeSince > 0
13577 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13578 synchronized (stats) {
13579 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13580 realtimeSince, wtimeUsed);
13581 }
13582 Slog.w(TAG, "Excessive wake lock in " + app.processName
13583 + " (pid " + app.pid + "): held " + wtimeUsed
13584 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013585 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013586 app.processName, app.setAdj, "excessive wake lock");
13587 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013588 } else if (doCpuKills && uptimeSince > 0
13589 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13590 synchronized (stats) {
13591 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13592 uptimeSince, cputimeUsed);
13593 }
13594 Slog.w(TAG, "Excessive CPU in " + app.processName
13595 + " (pid " + app.pid + "): used " + cputimeUsed
13596 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013597 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013598 app.processName, app.setAdj, "excessive cpu");
13599 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013600 } else {
13601 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013602 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013603 }
13604 }
13605 }
13606 }
13607
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013608 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013609 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013610 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013611 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013612 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613
13614 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013615 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 }
13617
Dianne Hackborn287952c2010-09-22 22:34:31 -070013618 final boolean wasKeeping = app.keeping;
13619
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013620 boolean success = true;
13621
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013622 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623
Jeff Brown10e89712011-07-08 18:52:57 -070013624 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013625 if (wasKeeping && !app.keeping) {
13626 // This app is no longer something we want to keep. Note
13627 // its current wake lock time to later know to kill it if
13628 // it is not behaving well.
13629 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13630 synchronized (stats) {
13631 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13632 app.pid, SystemClock.elapsedRealtime());
13633 }
13634 app.lastCpuTime = app.curCpuTime;
13635 }
13636
13637 app.setRawAdj = app.curRawAdj;
13638 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013639
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013640 if (app.curAdj != app.setAdj) {
13641 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013642 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013643 TAG, "Set " + app.pid + " " + app.processName +
13644 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013645 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013646 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013647 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013648 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013649 }
13650 }
13651 if (app.setSchedGroup != app.curSchedGroup) {
13652 app.setSchedGroup = app.curSchedGroup;
13653 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13654 "Setting process group of " + app.processName
13655 + " to " + app.curSchedGroup);
13656 if (app.waitingToKill != null &&
13657 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13658 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013659 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013660 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013661 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013662 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013663 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013664 } else {
13665 if (true) {
13666 long oldId = Binder.clearCallingIdentity();
13667 try {
13668 Process.setProcessGroup(app.pid, app.curSchedGroup);
13669 } catch (Exception e) {
13670 Slog.w(TAG, "Failed setting process group of " + app.pid
13671 + " to " + app.curSchedGroup);
13672 e.printStackTrace();
13673 } finally {
13674 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013675 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013676 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013677 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013678 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013679 app.thread.setSchedulingGroup(app.curSchedGroup);
13680 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013681 }
13682 }
13683 }
13684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013685 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013686 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013687 }
13688
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013689 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013690 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013691 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013692 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013694 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 }
13696 }
13697 return resumedActivity;
13698 }
13699
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013700 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013701 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013702 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13703 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013704 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13705 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706
13707 mAdjSeq++;
13708
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013709 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13710 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013711 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13712 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013713 if (nowHidden != wasHidden) {
13714 // Changed to/from hidden state, so apps after it in the LRU
13715 // list may also be changed.
13716 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013717 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013718 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013719 }
13720
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013721 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013722 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013723 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013724 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725
13726 if (false) {
13727 RuntimeException e = new RuntimeException();
13728 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013729 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013730 }
13731
13732 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013733 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013735 final int emptyProcessLimit;
13736 final int hiddenProcessLimit;
13737 if (mProcessLimit <= 0) {
13738 emptyProcessLimit = hiddenProcessLimit = 0;
13739 } else if (mProcessLimit == 1) {
13740 emptyProcessLimit = 1;
13741 hiddenProcessLimit = 0;
13742 } else {
13743 emptyProcessLimit = (mProcessLimit*2)/3;
13744 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13745 }
13746
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013747 // Let's determine how many processes we have running vs.
13748 // how many slots we have for background processes; we may want
13749 // to put multiple processes in a slot of there are enough of
13750 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013751 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13752 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013753 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13754 if (numEmptyProcs > hiddenProcessLimit) {
13755 // If there are more empty processes than our limit on hidden
13756 // processes, then use the hidden process limit for the factor.
13757 // This ensures that the really old empty processes get pushed
13758 // down to the bottom, so if we are running low on memory we will
13759 // have a better chance at keeping around more hidden processes
13760 // instead of a gazillion empty processes.
13761 numEmptyProcs = hiddenProcessLimit;
13762 }
13763 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013764 if (emptyFactor < 1) emptyFactor = 1;
13765 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13766 if (hiddenFactor < 1) hiddenFactor = 1;
13767 int stepHidden = 0;
13768 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013769 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013770 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013771 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013772
13773 mNumNonHiddenProcs = 0;
13774 mNumHiddenProcs = 0;
13775
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013776 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013777 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013778 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013779 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013780 int nextHiddenAdj = curHiddenAdj+1;
13781 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13782 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013783 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013784 while (i > 0) {
13785 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013786 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013787 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013788 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013789 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013790 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13791 // This process was assigned as a hidden process... step the
13792 // hidden level.
13793 mNumHiddenProcs++;
13794 if (curHiddenAdj != nextHiddenAdj) {
13795 stepHidden++;
13796 if (stepHidden >= hiddenFactor) {
13797 stepHidden = 0;
13798 curHiddenAdj = nextHiddenAdj;
13799 nextHiddenAdj += 2;
13800 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13801 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13802 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013803 if (curClientHiddenAdj <= curHiddenAdj) {
13804 curClientHiddenAdj = curHiddenAdj + 1;
13805 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13806 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13807 }
13808 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013809 }
13810 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013811 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013812 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013813 Slog.i(TAG, "No longer want " + app.processName
13814 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013815 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013816 app.processName, app.setAdj, "too many background");
13817 app.killedBackground = true;
13818 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013819 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013820 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13821 // This process has a client that has activities. We will have
13822 // given it the current hidden adj; here we will just leave it
13823 // without stepping the hidden adj.
13824 curClientHiddenAdj++;
13825 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13826 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13827 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013828 } else {
13829 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13830 // This process was assigned as an empty process... step the
13831 // empty level.
13832 if (curEmptyAdj != nextEmptyAdj) {
13833 stepEmpty++;
13834 if (stepEmpty >= emptyFactor) {
13835 stepEmpty = 0;
13836 curEmptyAdj = nextEmptyAdj;
13837 nextEmptyAdj += 2;
13838 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13839 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13840 }
13841 }
13842 }
13843 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13844 mNumNonHiddenProcs++;
13845 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013846 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13847 && !app.hasClientActivities) {
13848 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13849 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013850 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013851 + " (pid " + app.pid + "): empty for "
13852 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13853 / 1000) + "s");
13854 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13855 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013856 app.killedBackground = true;
13857 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013858 } else {
13859 numEmpty++;
13860 if (numEmpty > emptyProcessLimit) {
13861 Slog.i(TAG, "No longer want " + app.processName
13862 + " (pid " + app.pid + "): empty #" + numEmpty);
13863 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13864 app.processName, app.setAdj, "too many background");
13865 app.killedBackground = true;
13866 Process.killProcessQuiet(app.pid);
13867 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013868 }
13869 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013870 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013871 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013872 // If this is an isolated process, and there are no
13873 // services running in it, then the process is no longer
13874 // needed. We agressively kill these because we can by
13875 // definition not re-use the same process again, and it is
13876 // good to avoid having whatever code was running in them
13877 // left sitting around after no longer needed.
13878 Slog.i(TAG, "Isolated process " + app.processName
13879 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013880 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013881 app.processName, app.setAdj, "isolated not needed");
13882 app.killedBackground = true;
13883 Process.killProcessQuiet(app.pid);
13884 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013885 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13886 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13887 && !app.killedBackground) {
13888 numTrimming++;
13889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013890 }
13891 }
13892
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013893 mNumServiceProcs = mNewNumServiceProcs;
13894
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013895 // Now determine the memory trimming level of background processes.
13896 // Unfortunately we need to start at the back of the list to do this
13897 // properly. We only do this if the number of background apps we
13898 // are managing to keep around is less than half the maximum we desire;
13899 // if we are keeping a good number around, we'll let them use whatever
13900 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013901 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13902 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013903 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013904 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013905 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013906 int minFactor = 2;
13907 if (mHomeProcess != null) minFactor++;
13908 if (mPreviousProcess != null) minFactor++;
13909 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013910 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013911 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013912 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013913 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013914 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013915 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13916 } else {
13917 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13918 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013919 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013920 for (i=0; i<N; i++) {
13921 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013922 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13923 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013924 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013925 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13926 try {
13927 app.thread.scheduleTrimMemory(curLevel);
13928 } catch (RemoteException e) {
13929 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013930 if (false) {
13931 // For now we won't do this; our memory trimming seems
13932 // to be good enough at this point that destroying
13933 // activities causes more harm than good.
13934 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13935 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013936 // Need to do this on its own message because the stack may not
13937 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013938 // For these apps we will also finish their activities
13939 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013940 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013941 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013942 }
13943 }
13944 app.trimMemoryLevel = curLevel;
13945 step++;
13946 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013947 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013948 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013949 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13950 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013951 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013952 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13953 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013954 break;
13955 }
13956 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013957 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013958 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013959 && app.thread != null) {
13960 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013961 app.thread.scheduleTrimMemory(
13962 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013963 } catch (RemoteException e) {
13964 }
13965 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013966 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013967 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013968 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013969 && app.pendingUiClean) {
13970 // If this application is now in the background and it
13971 // had done UI, then give it the special trim level to
13972 // have it free UI resources.
13973 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13974 if (app.trimMemoryLevel < level && app.thread != null) {
13975 try {
13976 app.thread.scheduleTrimMemory(level);
13977 } catch (RemoteException e) {
13978 }
13979 }
13980 app.pendingUiClean = false;
13981 }
13982 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013983 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013984 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013985 } catch (RemoteException e) {
13986 }
13987 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013988 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013989 }
13990 }
13991 } else {
13992 final int N = mLruProcesses.size();
13993 for (i=0; i<N; i++) {
13994 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013995 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013996 && app.pendingUiClean) {
13997 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13998 && app.thread != null) {
13999 try {
14000 app.thread.scheduleTrimMemory(
14001 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14002 } catch (RemoteException e) {
14003 }
14004 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014005 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014006 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014007 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014008 }
14009 }
14010
14011 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014012 // Need to do this on its own message because the stack may not
14013 // be in a consistent state at this point.
14014 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014016 }
14017
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014018 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014019 synchronized (this) {
14020 int i;
14021
14022 // First remove any unused application processes whose package
14023 // has been removed.
14024 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14025 final ProcessRecord app = mRemovedProcesses.get(i);
14026 if (app.activities.size() == 0
14027 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014028 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014029 TAG, "Exiting empty application process "
14030 + app.processName + " ("
14031 + (app.thread != null ? app.thread.asBinder() : null)
14032 + ")\n");
14033 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014034 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014035 app.processName, app.setAdj, "empty");
14036 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014037 } else {
14038 try {
14039 app.thread.scheduleExit();
14040 } catch (Exception e) {
14041 // Ignore exceptions.
14042 }
14043 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014044 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014045 mRemovedProcesses.remove(i);
14046
14047 if (app.persistent) {
14048 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014049 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014050 }
14051 }
14052 }
14053 }
14054
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014055 // Now update the oom adj for all processes.
14056 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014057 }
14058 }
14059
14060 /** This method sends the specified signal to each of the persistent apps */
14061 public void signalPersistentProcesses(int sig) throws RemoteException {
14062 if (sig != Process.SIGNAL_USR1) {
14063 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14064 }
14065
14066 synchronized (this) {
14067 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14068 != PackageManager.PERMISSION_GRANTED) {
14069 throw new SecurityException("Requires permission "
14070 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14071 }
14072
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014073 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14074 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014075 if (r.thread != null && r.persistent) {
14076 Process.sendSignal(r.pid, sig);
14077 }
14078 }
14079 }
14080 }
14081
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014082 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14083 if (proc == null || proc == mProfileProc) {
14084 proc = mProfileProc;
14085 path = mProfileFile;
14086 profileType = mProfileType;
14087 clearProfilerLocked();
14088 }
14089 if (proc == null) {
14090 return;
14091 }
14092 try {
14093 proc.thread.profilerControl(false, path, null, profileType);
14094 } catch (RemoteException e) {
14095 throw new IllegalStateException("Process disappeared");
14096 }
14097 }
14098
14099 private void clearProfilerLocked() {
14100 if (mProfileFd != null) {
14101 try {
14102 mProfileFd.close();
14103 } catch (IOException e) {
14104 }
14105 }
14106 mProfileApp = null;
14107 mProfileProc = null;
14108 mProfileFile = null;
14109 mProfileType = 0;
14110 mAutoStopProfiler = false;
14111 }
14112
Dianne Hackborn1676c852012-09-10 14:52:30 -070014113 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014114 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014115
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014116 try {
14117 synchronized (this) {
14118 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14119 // its own permission.
14120 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14121 != PackageManager.PERMISSION_GRANTED) {
14122 throw new SecurityException("Requires permission "
14123 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014124 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014125
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014126 if (start && fd == null) {
14127 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014128 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014129
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014130 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014131 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014132 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014133 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014134
14135 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014136 throw new IllegalArgumentException("Unknown process: " + process);
14137 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014138
14139 if (start) {
14140 stopProfilerLocked(null, null, 0);
14141 setProfileApp(proc.info, proc.processName, path, fd, false);
14142 mProfileProc = proc;
14143 mProfileType = profileType;
14144 try {
14145 fd = fd.dup();
14146 } catch (IOException e) {
14147 fd = null;
14148 }
14149 proc.thread.profilerControl(start, path, fd, profileType);
14150 fd = null;
14151 mProfileFd = null;
14152 } else {
14153 stopProfilerLocked(proc, path, profileType);
14154 if (fd != null) {
14155 try {
14156 fd.close();
14157 } catch (IOException e) {
14158 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014159 }
14160 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014161
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014162 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014163 }
14164 } catch (RemoteException e) {
14165 throw new IllegalStateException("Process disappeared");
14166 } finally {
14167 if (fd != null) {
14168 try {
14169 fd.close();
14170 } catch (IOException e) {
14171 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014172 }
14173 }
14174 }
Andy McFadden824c5102010-07-09 16:26:57 -070014175
Dianne Hackborn1676c852012-09-10 14:52:30 -070014176 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014177 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014178 userId, true, true, callName, null);
14179 ProcessRecord proc = null;
14180 try {
14181 int pid = Integer.parseInt(process);
14182 synchronized (mPidsSelfLocked) {
14183 proc = mPidsSelfLocked.get(pid);
14184 }
14185 } catch (NumberFormatException e) {
14186 }
14187
14188 if (proc == null) {
14189 HashMap<String, SparseArray<ProcessRecord>> all
14190 = mProcessNames.getMap();
14191 SparseArray<ProcessRecord> procs = all.get(process);
14192 if (procs != null && procs.size() > 0) {
14193 proc = procs.valueAt(0);
14194 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14195 for (int i=1; i<procs.size(); i++) {
14196 ProcessRecord thisProc = procs.valueAt(i);
14197 if (thisProc.userId == userId) {
14198 proc = thisProc;
14199 break;
14200 }
14201 }
14202 }
14203 }
14204 }
14205
14206 return proc;
14207 }
14208
14209 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014210 String path, ParcelFileDescriptor fd) throws RemoteException {
14211
14212 try {
14213 synchronized (this) {
14214 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14215 // its own permission (same as profileControl).
14216 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14217 != PackageManager.PERMISSION_GRANTED) {
14218 throw new SecurityException("Requires permission "
14219 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14220 }
14221
14222 if (fd == null) {
14223 throw new IllegalArgumentException("null fd");
14224 }
14225
Dianne Hackborn1676c852012-09-10 14:52:30 -070014226 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014227 if (proc == null || proc.thread == null) {
14228 throw new IllegalArgumentException("Unknown process: " + process);
14229 }
14230
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014231 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14232 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014233 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14234 throw new SecurityException("Process not debuggable: " + proc);
14235 }
14236 }
14237
14238 proc.thread.dumpHeap(managed, path, fd);
14239 fd = null;
14240 return true;
14241 }
14242 } catch (RemoteException e) {
14243 throw new IllegalStateException("Process disappeared");
14244 } finally {
14245 if (fd != null) {
14246 try {
14247 fd.close();
14248 } catch (IOException e) {
14249 }
14250 }
14251 }
14252 }
14253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014254 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14255 public void monitor() {
14256 synchronized (this) { }
14257 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014258
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014259 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014260 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14261 ProcessRecord processRecord = mLruProcesses.get(i);
14262 try {
14263 if (processRecord.thread != null) {
14264 processRecord.thread.setCoreSettings(settings);
14265 }
14266 } catch (RemoteException re) {
14267 /* ignore */
14268 }
14269 }
14270 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014271
14272 // Multi-user methods
14273
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014274 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014275 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014276 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14277 != PackageManager.PERMISSION_GRANTED) {
14278 String msg = "Permission Denial: switchUser() from pid="
14279 + Binder.getCallingPid()
14280 + ", uid=" + Binder.getCallingUid()
14281 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14282 Slog.w(TAG, msg);
14283 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014284 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014285
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014286 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014287 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014288 synchronized (this) {
14289 final int oldUserId = mCurrentUserId;
14290 if (oldUserId == userId) {
14291 return true;
14292 }
14293
14294 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14295 if (userInfo == null) {
14296 Slog.w(TAG, "No user info for user #" + userId);
14297 return false;
14298 }
14299
14300 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14301 R.anim.screen_user_enter);
14302
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014303 boolean needStart = false;
14304
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014305 // If the user we are switching to is not currently started, then
14306 // we need to start it now.
14307 if (mStartedUsers.get(userId) == null) {
14308 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014309 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014310 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014311 }
14312
14313 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014314 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014315 final Integer userIdInt = Integer.valueOf(userId);
14316 mUserLru.remove(userIdInt);
14317 mUserLru.add(userIdInt);
14318
Craig Mautnerf1b67412012-09-19 13:18:29 -070014319 mWindowManager.setCurrentUser(userId);
14320
Adam Cohenf7522022012-10-03 20:03:18 -070014321 // Once the internal notion of the active user has switched, we lock the device
14322 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014323 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014324
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014325 final UserStartedState uss = mStartedUsers.get(userId);
14326
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014327 // Make sure user is in the started state. If it is currently
14328 // stopping, we need to knock that off.
14329 if (uss.mState == UserStartedState.STATE_STOPPING) {
14330 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14331 // so we can just fairly silently bring the user back from
14332 // the almost-dead.
14333 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014334 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014335 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014336 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14337 // This means ACTION_SHUTDOWN has been sent, so we will
14338 // need to treat this as a new boot of the user.
14339 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014340 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014341 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014342 }
14343
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014344 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14345 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14346 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14347 oldUserId, userId, uss));
14348 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14349 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014350 if (needStart) {
14351 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14352 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14353 | Intent.FLAG_RECEIVER_FOREGROUND);
14354 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14355 broadcastIntentLocked(null, null, intent,
14356 null, null, 0, null, null, null,
14357 false, false, MY_PID, Process.SYSTEM_UID, userId);
14358 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014359
14360 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14361 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014362 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014363 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014364 broadcastIntentLocked(null, null, intent, null,
14365 new IIntentReceiver.Stub() {
14366 public void performReceive(Intent intent, int resultCode,
14367 String data, Bundle extras, boolean ordered,
14368 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014369 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014370 }
14371 }, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
14372 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014373 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014374 } else {
14375 getUserManagerLocked().makeInitialized(userInfo.id);
14376 }
14377 }
14378
14379 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14380 if (!haveActivities) {
14381 startHomeActivityLocked(userId);
14382 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014383
Jeff Sharkey86597df2012-11-09 15:00:31 -080014384 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014385 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014386 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014387 if (needStart) {
14388 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14389 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14390 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14391 broadcastIntentLocked(null, null, intent,
14392 null, new IIntentReceiver.Stub() {
14393 @Override
14394 public void performReceive(Intent intent, int resultCode, String data,
14395 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14396 throws RemoteException {
14397 }
14398 }, 0, null, null,
14399 android.Manifest.permission.INTERACT_ACROSS_USERS,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014400 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014401 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014402 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014403 } finally {
14404 Binder.restoreCallingIdentity(ident);
14405 }
Amith Yamasani13593602012-03-22 16:16:17 -070014406
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014407 return true;
14408 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014409
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014410 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14411 long ident = Binder.clearCallingIdentity();
14412 try {
14413 Intent intent;
14414 if (oldUserId >= 0) {
14415 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014416 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14417 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014418 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14419 broadcastIntentLocked(null, null, intent,
14420 null, null, 0, null, null, null,
14421 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14422 }
14423 if (newUserId >= 0) {
14424 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014425 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14426 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014427 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14428 broadcastIntentLocked(null, null, intent,
14429 null, null, 0, null, null, null,
14430 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14431 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014432 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14433 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014434 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14435 broadcastIntentLocked(null, null, intent,
14436 null, null, 0, null, null,
14437 android.Manifest.permission.MANAGE_USERS,
14438 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14439 }
14440 } finally {
14441 Binder.restoreCallingIdentity(ident);
14442 }
14443 }
14444
14445 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14446 final int newUserId) {
14447 final int N = mUserSwitchObservers.beginBroadcast();
14448 if (N > 0) {
14449 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14450 int mCount = 0;
14451 @Override
14452 public void sendResult(Bundle data) throws RemoteException {
14453 synchronized (ActivityManagerService.this) {
14454 if (mCurUserSwitchCallback == this) {
14455 mCount++;
14456 if (mCount == N) {
14457 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14458 }
14459 }
14460 }
14461 }
14462 };
14463 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014464 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014465 mCurUserSwitchCallback = callback;
14466 }
14467 for (int i=0; i<N; i++) {
14468 try {
14469 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14470 newUserId, callback);
14471 } catch (RemoteException e) {
14472 }
14473 }
14474 } else {
14475 synchronized (this) {
14476 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14477 }
14478 }
14479 mUserSwitchObservers.finishBroadcast();
14480 }
14481
14482 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14483 synchronized (this) {
14484 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14485 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14486 }
14487 }
14488
14489 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14490 mCurUserSwitchCallback = null;
14491 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14492 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14493 oldUserId, newUserId, uss));
14494 }
14495
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014496 void userInitialized(UserStartedState uss, int newUserId) {
14497 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014498 }
14499
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014500 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014501 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014502 }
14503
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014504 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14505 boolean clearInitializing, boolean clearSwitching) {
14506 boolean unfrozen = false;
14507 synchronized (this) {
14508 if (clearInitializing) {
14509 uss.initializing = false;
14510 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14511 }
14512 if (clearSwitching) {
14513 uss.switching = false;
14514 }
14515 if (!uss.switching && !uss.initializing) {
14516 mWindowManager.stopFreezingScreen();
14517 unfrozen = true;
14518 }
14519 }
14520 if (unfrozen) {
14521 final int N = mUserSwitchObservers.beginBroadcast();
14522 for (int i=0; i<N; i++) {
14523 try {
14524 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14525 } catch (RemoteException e) {
14526 }
14527 }
14528 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014529 }
14530 }
14531
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014532 void finishUserSwitch(UserStartedState uss) {
14533 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014534 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014535 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14536 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014537 final int userId = uss.mHandle.getIdentifier();
14538 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14539 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14540 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014541 null, null, 0, null, null,
14542 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070014543 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014544 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014545 int num = mUserLru.size();
14546 int i = 0;
14547 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14548 Integer oldUserId = mUserLru.get(i);
14549 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14550 if (oldUss == null) {
14551 // Shouldn't happen, but be sane if it does.
14552 mUserLru.remove(i);
14553 num--;
14554 continue;
14555 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014556 if (oldUss.mState == UserStartedState.STATE_STOPPING
14557 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014558 // This user is already stopping, doesn't count.
14559 num--;
14560 i++;
14561 continue;
14562 }
14563 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14564 // Owner and current can't be stopped, but count as running.
14565 i++;
14566 continue;
14567 }
14568 // This is a user to be stopped.
14569 stopUserLocked(oldUserId, null);
14570 num--;
14571 i++;
14572 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014573 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014574 }
14575
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014576 @Override
14577 public int stopUser(final int userId, final IStopUserCallback callback) {
14578 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14579 != PackageManager.PERMISSION_GRANTED) {
14580 String msg = "Permission Denial: switchUser() from pid="
14581 + Binder.getCallingPid()
14582 + ", uid=" + Binder.getCallingUid()
14583 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14584 Slog.w(TAG, msg);
14585 throw new SecurityException(msg);
14586 }
14587 if (userId <= 0) {
14588 throw new IllegalArgumentException("Can't stop primary user " + userId);
14589 }
Amith Yamasani13593602012-03-22 16:16:17 -070014590 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014591 return stopUserLocked(userId, callback);
14592 }
14593 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014594
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014595 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14596 if (mCurrentUserId == userId) {
14597 return ActivityManager.USER_OP_IS_CURRENT;
14598 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014599
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014600 final UserStartedState uss = mStartedUsers.get(userId);
14601 if (uss == null) {
14602 // User is not started, nothing to do... but we do need to
14603 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014604 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014605 mHandler.post(new Runnable() {
14606 @Override
14607 public void run() {
14608 try {
14609 callback.userStopped(userId);
14610 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014611 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014612 }
14613 });
14614 }
14615 return ActivityManager.USER_OP_SUCCESS;
14616 }
14617
14618 if (callback != null) {
14619 uss.mStopCallbacks.add(callback);
14620 }
14621
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014622 if (uss.mState != UserStartedState.STATE_STOPPING
14623 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014624 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014625 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014626
14627 long ident = Binder.clearCallingIdentity();
14628 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014629 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014630 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014631 // stop the user.
14632 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14633 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14634 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14635 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14636 // This is the result receiver for the final shutdown broadcast.
14637 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014638 @Override
14639 public void performReceive(Intent intent, int resultCode, String data,
14640 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14641 finishUserStop(uss);
14642 }
14643 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014644 // This is the result receiver for the initial stopping broadcast.
14645 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14646 @Override
14647 public void performReceive(Intent intent, int resultCode, String data,
14648 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14649 // On to the next.
14650 synchronized (ActivityManagerService.this) {
14651 if (uss.mState != UserStartedState.STATE_STOPPING) {
14652 // Whoops, we are being started back up. Abort, abort!
14653 return;
14654 }
14655 uss.mState = UserStartedState.STATE_SHUTDOWN;
14656 }
14657 broadcastIntentLocked(null, null, shutdownIntent,
14658 null, shutdownReceiver, 0, null, null, null,
14659 true, false, MY_PID, Process.SYSTEM_UID, userId);
14660 }
14661 };
14662 // Kick things off.
14663 broadcastIntentLocked(null, null, stoppingIntent,
14664 null, stoppingReceiver, 0, null, null,
14665 android.Manifest.permission.INTERACT_ACROSS_USERS,
14666 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014667 } finally {
14668 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014669 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014670 }
Amith Yamasani13593602012-03-22 16:16:17 -070014671
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014672 return ActivityManager.USER_OP_SUCCESS;
14673 }
14674
14675 void finishUserStop(UserStartedState uss) {
14676 final int userId = uss.mHandle.getIdentifier();
14677 boolean stopped;
14678 ArrayList<IStopUserCallback> callbacks;
14679 synchronized (this) {
14680 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014681 if (mStartedUsers.get(userId) != uss) {
14682 stopped = false;
14683 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014684 stopped = false;
14685 } else {
14686 stopped = true;
14687 // User can no longer run.
14688 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014689 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014690 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014691
14692 // Clean up all state and processes associated with the user.
14693 // Kill all the processes for the user.
14694 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014695 }
14696 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014697
14698 for (int i=0; i<callbacks.size(); i++) {
14699 try {
14700 if (stopped) callbacks.get(i).userStopped(userId);
14701 else callbacks.get(i).userStopAborted(userId);
14702 } catch (RemoteException e) {
14703 }
14704 }
14705 }
14706
14707 @Override
14708 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014709 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14710 != PackageManager.PERMISSION_GRANTED) && (
14711 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14712 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014713 String msg = "Permission Denial: getCurrentUser() from pid="
14714 + Binder.getCallingPid()
14715 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014716 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014717 Slog.w(TAG, msg);
14718 throw new SecurityException(msg);
14719 }
14720 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014721 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014722 }
Amith Yamasani13593602012-03-22 16:16:17 -070014723 }
14724
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014725 int getCurrentUserIdLocked() {
14726 return mCurrentUserId;
14727 }
14728
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014729 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014730 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014731 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14732 != PackageManager.PERMISSION_GRANTED) {
14733 String msg = "Permission Denial: isUserRunning() from pid="
14734 + Binder.getCallingPid()
14735 + ", uid=" + Binder.getCallingUid()
14736 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14737 Slog.w(TAG, msg);
14738 throw new SecurityException(msg);
14739 }
14740 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014741 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014742 }
14743 }
14744
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014745 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014746 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014747 if (state == null) {
14748 return false;
14749 }
14750 if (orStopped) {
14751 return true;
14752 }
14753 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014754 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014755 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014756
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014757 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014758 public int[] getRunningUserIds() {
14759 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14760 != PackageManager.PERMISSION_GRANTED) {
14761 String msg = "Permission Denial: isUserRunning() from pid="
14762 + Binder.getCallingPid()
14763 + ", uid=" + Binder.getCallingUid()
14764 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14765 Slog.w(TAG, msg);
14766 throw new SecurityException(msg);
14767 }
14768 synchronized (this) {
14769 return mStartedUserArray;
14770 }
14771 }
14772
14773 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014774 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014775 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014776 UserStartedState uss = mStartedUsers.valueAt(i);
14777 // This list does not include stopping users.
14778 if (uss.mState != UserStartedState.STATE_STOPPING
14779 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14780 num++;
14781 }
14782 }
14783 mStartedUserArray = new int[num];
14784 num = 0;
14785 for (int i=0; i<mStartedUsers.size(); i++) {
14786 UserStartedState uss = mStartedUsers.valueAt(i);
14787 if (uss.mState != UserStartedState.STATE_STOPPING
14788 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14789 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14790 num++;
14791 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014792 }
14793 }
14794
14795 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014796 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14797 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14798 != PackageManager.PERMISSION_GRANTED) {
14799 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14800 + Binder.getCallingPid()
14801 + ", uid=" + Binder.getCallingUid()
14802 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14803 Slog.w(TAG, msg);
14804 throw new SecurityException(msg);
14805 }
14806
14807 mUserSwitchObservers.register(observer);
14808 }
14809
14810 @Override
14811 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14812 mUserSwitchObservers.unregister(observer);
14813 }
14814
Dianne Hackborn1676c852012-09-10 14:52:30 -070014815 private boolean userExists(int userId) {
14816 if (userId == 0) {
14817 return true;
14818 }
14819 UserManagerService ums = getUserManagerLocked();
14820 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14821 }
14822
14823 int[] getUsersLocked() {
14824 UserManagerService ums = getUserManagerLocked();
14825 return ums != null ? ums.getUserIds() : new int[] { 0 };
14826 }
14827
14828 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014829 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014830 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14831 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014832 }
14833 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014834 }
14835
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014836 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014837 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014838
14839 throw new SecurityException("Caller uid=" + uid
14840 + " is not privileged to communicate with user=" + userId);
14841 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014842
14843 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014844 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014845 }
14846
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014847 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014848 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014849 ApplicationInfo newInfo = new ApplicationInfo(info);
14850 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014851 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14852 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014853 return newInfo;
14854 }
14855
14856 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014857 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014858 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014859 return aInfo;
14860 }
14861
14862 ActivityInfo info = new ActivityInfo(aInfo);
14863 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14864 return info;
14865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014866}