blob: 44f2d1279418a58cafe7a2156b0d9f1147c17058 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackbornf51f6122013-02-04 18:23:34 -080021import android.app.AppOpsManager;
Dianne Hackborn860755f2010-06-03 18:47:52 -070022import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070024import com.android.internal.os.ProcessStats;
Dianne Hackborna06de0f2012-12-11 16:34:47 -080025import com.android.server.AppOpsService;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070026import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.IntentResolver;
28import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import com.android.server.SystemServer;
30import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070031import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070032import com.android.server.pm.UserManagerService;
Craig Mautner4b71aa12012-12-27 17:20:01 -080033import com.android.server.wm.AppTransition;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080034import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035
Dianne Hackborndd71fc82009-12-16 19:24:32 -080036import dalvik.system.Zygote;
37
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.Activity;
39import android.app.ActivityManager;
40import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070041import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.ActivityThread;
43import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070044import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020045import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070047import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IApplicationThread;
49import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070050import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070051import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070053import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.IThumbnailReceiver;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080055import android.app.IUiAutomationConnection;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070056import android.app.IUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070058import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070059import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080061import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020062import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080063import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080064import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070065import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070067import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.content.ContentResolver;
69import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020070import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070071import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070072import android.content.IIntentReceiver;
73import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070074import android.content.Intent;
75import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070076import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.ActivityInfo;
78import android.content.pm.ApplicationInfo;
79import android.content.pm.ConfigurationInfo;
80import android.content.pm.IPackageDataObserver;
81import android.content.pm.IPackageManager;
82import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080083import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070085import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070086import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070087import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.content.pm.ProviderInfo;
89import android.content.pm.ResolveInfo;
90import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040091import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.content.res.Configuration;
93import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070094import android.net.Proxy;
95import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.net.Uri;
97import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080098import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080099import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -0700100import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -0800101import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -0800103import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.FileUtils;
105import android.os.Handler;
106import android.os.IBinder;
107import android.os.IPermissionController;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700108import android.os.IRemoteCallback;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700109import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.Looper;
111import android.os.Message;
112import android.os.Parcel;
113import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700115import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400117import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700119import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.os.SystemClock;
121import android.os.SystemProperties;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700122import android.os.UpdateLock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700123import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700125import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800127import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700128import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700130import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700132import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import android.view.Gravity;
134import android.view.LayoutInflater;
135import android.view.View;
136import android.view.WindowManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.BufferedInputStream;
139import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700140import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.DataInputStream;
142import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.File;
144import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700145import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700147import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200148import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800149import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700151import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152import java.lang.ref.WeakReference;
153import java.util.ArrayList;
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700154import java.util.Arrays;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700155import java.util.Collections;
156import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.util.HashMap;
158import java.util.HashSet;
159import java.util.Iterator;
160import java.util.List;
161import java.util.Locale;
162import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700163import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700164import java.util.concurrent.atomic.AtomicBoolean;
165import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Svetoslav Ganov80943d82013-01-02 10:25:37 -0800167public final class ActivityManagerService extends ActivityManagerNative
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700168 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700169 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700171 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400173 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SWITCH = localLOGV || false;
175 static final boolean DEBUG_TASKS = localLOGV || false;
Dianne Hackborn15491c62012-09-19 10:59:14 -0700176 static final boolean DEBUG_THUMBNAILS = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_PAUSE = localLOGV || false;
178 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
179 static final boolean DEBUG_TRANSITION = localLOGV || false;
180 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800181 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700182 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 static final boolean DEBUG_VISBILITY = localLOGV || false;
186 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700187 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -0700188 static final boolean DEBUG_CLEANUP = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700189 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800190 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700192 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700193 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700194 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700195 static final boolean DEBUG_POWER = localLOGV || false;
196 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700197 static final boolean DEBUG_MU = localLOGV || false;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700198 static final boolean DEBUG_IMMERSIVE = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 static final boolean VALIDATE_TOKENS = false;
200 static final boolean SHOW_ACTIVITY_START_TIME = true;
201
202 // Control over CPU and battery monitoring.
203 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
204 static final boolean MONITOR_CPU_USAGE = true;
205 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
206 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
207 static final boolean MONITOR_THREAD_CPU_USAGE = false;
208
Dianne Hackborn1655be42009-05-08 14:29:01 -0700209 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700210 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700211
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800212 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700214 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 // Maximum number of recent tasks that we can remember.
217 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700218
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700219 // Amount of time after a call to stopAppSwitches() during which we will
220 // prevent further untrusted switches from happening.
221 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
223 // How long we wait for a launched process to attach to the activity manager
224 // before we decide it's never going to come up for real.
225 static final int PROC_START_TIMEOUT = 10*1000;
226
Jeff Brown3f9dd282011-07-08 20:02:19 -0700227 // How long we wait for a launched process to attach to the activity manager
228 // before we decide it's never going to come up for real, when the process was
229 // started with a wrapper for instrumentation (such as Valgrind) because it
230 // could take much longer than usual.
231 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 // How long to wait after going idle before forcing apps to GC.
234 static final int GC_TIMEOUT = 5*1000;
235
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700236 // The minimum amount of time between successive GC requests for a process.
237 static final int GC_MIN_INTERVAL = 60*1000;
238
Dianne Hackborn287952c2010-09-22 22:34:31 -0700239 // The rate at which we check for apps using excessive power -- 15 mins.
240 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
241
242 // The minimum sample duration we will allow before deciding we have
243 // enough data on wake locks to start killing things.
244 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
245
246 // The minimum sample duration we will allow before deciding we have
247 // enough data on CPU usage to start killing things.
248 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800251 static final int BROADCAST_FG_TIMEOUT = 10*1000;
252 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // How long we wait until we timeout on key dispatching.
255 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 // How long we wait until we timeout on key dispatching during instrumentation.
258 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
259
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700260 // Amount of time we wait for observers to handle a user switch before
261 // giving up on them and unfreezing the screen.
262 static final int USER_SWITCH_TIMEOUT = 2*1000;
263
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -0700264 // Maximum number of users we allow to be running at a time.
265 static final int MAX_RUNNING_USERS = 3;
266
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800267 // How long to wait in getTopActivityExtras for the activity to respond with the result.
268 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000;
269
Dan Egnor42471dd2010-01-07 17:25:22 -0800270 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271
272 static final String[] EMPTY_STRING_ARRAY = new String[0];
273
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700274 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700275
276 private final boolean mHeadless;
277
Joe Onorato54a4a412011-11-02 20:50:08 -0700278 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
279 // default actuion automatically. Important for devices without direct input
280 // devices.
281 private boolean mShowDialogs = true;
282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800283 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700284 * Description of a request to start a new activity, which has been held
285 * due to app switches being disabled.
286 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700287 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700288 ActivityRecord r;
289 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700290 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700291 }
292
293 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
294 = new ArrayList<PendingActivityLaunch>();
295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800297 BroadcastQueue mFgBroadcastQueue;
298 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800299 // Convenient for easy iteration over the queues. Foreground is first
300 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800301 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800302
303 BroadcastQueue broadcastQueueForIntent(Intent intent) {
304 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
305 if (DEBUG_BACKGROUND_BROADCAST) {
306 Slog.i(TAG, "Broadcast intent " + intent + " on "
307 + (isFg ? "foreground" : "background")
308 + " queue");
309 }
310 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
311 }
312
313 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
314 for (BroadcastQueue queue : mBroadcastQueues) {
315 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
316 if (r != null) {
317 return r;
318 }
319 }
320 return null;
321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800322
323 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 * Activity we have told the window manager to have key focus.
325 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700326 ActivityRecord mFocusedActivity = null;
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800327
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * List of intents that were used to start the most recent tasks.
330 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700331 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -0800333 public class PendingActivityExtras extends Binder implements Runnable {
334 public final ActivityRecord activity;
335 public boolean haveResult = false;
336 public Bundle result = null;
337 public PendingActivityExtras(ActivityRecord _activity) {
338 activity = _activity;
339 }
340 @Override
341 public void run() {
342 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity);
343 synchronized (this) {
344 haveResult = true;
345 notifyAll();
346 }
347 }
348 }
349
350 final ArrayList<PendingActivityExtras> mPendingActivityExtras
351 = new ArrayList<PendingActivityExtras>();
352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700354 * Process management.
355 */
356 final ProcessList mProcessList = new ProcessList();
357
358 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 * All of the applications we currently have running organized by name.
360 * The keys are strings of the application package name (as
361 * returned by the package manager), and the keys are ApplicationRecord
362 * objects.
363 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700364 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365
366 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800367 * The currently running isolated processes.
368 */
369 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
370
371 /**
372 * Counter for assigning isolated process uids, to avoid frequently reusing the
373 * same ones.
374 */
375 int mNextIsolatedProcessUid = 0;
376
377 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700378 * The currently running heavy-weight process, if any.
379 */
380 ProcessRecord mHeavyWeightProcess = null;
381
382 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 * The last time that various processes have crashed.
384 */
385 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
386
387 /**
388 * Set of applications that we consider to be bad, and will reject
389 * incoming broadcasts from (which the user has no control over).
390 * Processes are added to this set when they have crashed twice within
391 * a minimum amount of time; they are removed from it when they are
392 * later restarted (hopefully due to some user action). The value is the
393 * time it was added to the list.
394 */
395 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
396
397 /**
398 * All of the processes we currently have running organized by pid.
399 * The keys are the pid running the application.
400 *
401 * <p>NOTE: This object is protected by its own lock, NOT the global
402 * activity manager lock!
403 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700404 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405
406 /**
407 * All of the processes that have been forced to be foreground. The key
408 * is the pid of the caller who requested it (we hold a death
409 * link on it).
410 */
411 abstract class ForegroundToken implements IBinder.DeathRecipient {
412 int pid;
413 IBinder token;
414 }
415 final SparseArray<ForegroundToken> mForegroundProcesses
416 = new SparseArray<ForegroundToken>();
417
418 /**
419 * List of records for processes that someone had tried to start before the
420 * system was ready. We don't start them at that point, but ensure they
421 * are started by the time booting is complete.
422 */
423 final ArrayList<ProcessRecord> mProcessesOnHold
424 = new ArrayList<ProcessRecord>();
425
426 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 * List of persistent applications that are in the process
428 * of being started.
429 */
430 final ArrayList<ProcessRecord> mPersistentStartingProcesses
431 = new ArrayList<ProcessRecord>();
432
433 /**
434 * Processes that are being forcibly torn down.
435 */
436 final ArrayList<ProcessRecord> mRemovedProcesses
437 = new ArrayList<ProcessRecord>();
438
439 /**
440 * List of running applications, sorted by recent usage.
441 * The first entry in the list is the least recently used.
442 * It contains ApplicationRecord objects. This list does NOT include
443 * any persistent application records (since we never want to exit them).
444 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800445 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 = new ArrayList<ProcessRecord>();
447
448 /**
449 * List of processes that should gc as soon as things are idle.
450 */
451 final ArrayList<ProcessRecord> mProcessesToGc
452 = new ArrayList<ProcessRecord>();
453
454 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800455 * This is the process holding what we currently consider to be
456 * the "home" activity.
457 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700458 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800459
460 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700461 * This is the process holding the activity the user last visited that
462 * is in a different process from the one they are currently in.
463 */
464 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800465
466 /**
467 * The time at which the previous process was last visible.
468 */
469 long mPreviousProcessVisibleTime;
470
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700471 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700472 * Which uses have been started, so are allowed to run code.
473 */
474 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
475
476 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700477 * LRU list of history of current users. Most recently current is at the end.
478 */
479 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
480
481 /**
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700482 * Constant array of the users that are currently started.
483 */
484 int[] mStartedUserArray = new int[] { 0 };
485
486 /**
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700487 * Registered observers of the user switching mechanics.
488 */
489 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
490 = new RemoteCallbackList<IUserSwitchObserver>();
491
492 /**
493 * Currently active user switch.
494 */
495 Object mCurUserSwitchCallback;
496
497 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400498 * Packages that the user has asked to have run in screen size
499 * compatibility mode instead of filling the screen.
500 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700501 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400502
503 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 * Set of PendingResultRecord objects that are currently active.
505 */
506 final HashSet mPendingResultRecords = new HashSet();
507
508 /**
509 * Set of IntentSenderRecord objects that are currently active.
510 */
511 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
512 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
513
514 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800515 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700516 * already logged DropBox entries for. Guarded by itself. If
517 * something (rogue user app) forces this over
518 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
519 */
520 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
521 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
522
523 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700524 * Strict Mode background batched logging state.
525 *
526 * The string buffer is guarded by itself, and its lock is also
527 * used to determine if another batched write is already
528 * in-flight.
529 */
530 private final StringBuilder mStrictModeBuffer = new StringBuilder();
531
532 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 * Keeps track of all IIntentReceivers that have been registered for
534 * broadcasts. Hash keys are the receiver IBinder, hash value is
535 * a ReceiverList.
536 */
537 final HashMap mRegisteredReceivers = new HashMap();
538
539 /**
540 * Resolver for broadcast intents to registered receivers.
541 * Holds BroadcastFilter (subclass of IntentFilter).
542 */
543 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
544 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
545 @Override
546 protected boolean allowFilterResult(
547 BroadcastFilter filter, List<BroadcastFilter> dest) {
548 IBinder target = filter.receiverList.receiver.asBinder();
549 for (int i=dest.size()-1; i>=0; i--) {
550 if (dest.get(i).receiverList.receiver.asBinder() == target) {
551 return false;
552 }
553 }
554 return true;
555 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700556
557 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700558 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700559 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
560 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700561 return super.newResult(filter, match, userId);
562 }
563 return null;
564 }
565
566 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700567 protected BroadcastFilter[] newArray(int size) {
568 return new BroadcastFilter[size];
569 }
570
571 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700572 protected String packageForFilter(BroadcastFilter filter) {
573 return filter.packageName;
574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 };
576
577 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700578 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700580 * that action (which should usually be one). The SparseArray is keyed
581 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
582 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700584 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
585 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700587 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588
589 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700590 * Backup/restore process management
591 */
592 String mBackupAppName = null;
593 BackupRecord mBackupTarget = null;
594
595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * List of PendingThumbnailsRecord objects of clients who are still
597 * waiting to receive all of the thumbnails for a task.
598 */
599 final ArrayList mPendingThumbnails = new ArrayList();
600
601 /**
602 * List of HistoryRecord objects that have been finished and must
603 * still report back to a pending thumbnail receiver.
604 */
605 final ArrayList mCancelledThumbnails = new ArrayList();
606
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700607 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 /**
610 * List of content providers who have clients waiting for them. The
611 * application is currently being launched and the provider will be
612 * removed from this list once it is published.
613 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700614 final ArrayList<ContentProviderRecord> mLaunchingProviders
615 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616
617 /**
618 * Global set of specific Uri permissions that have been granted.
619 */
620 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
621 = new SparseArray<HashMap<Uri, UriPermission>>();
622
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800623 CoreSettingsObserver mCoreSettingsObserver;
624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 /**
626 * Thread-local storage used to carry caller permissions over through
627 * indirect content-provider access.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 */
629 private class Identity {
630 public int pid;
631 public int uid;
632
633 Identity(int _pid, int _uid) {
634 pid = _pid;
635 uid = _uid;
636 }
637 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
640
641 /**
642 * All information we have collected about the runtime performance of
643 * any user id that can impact battery performance.
644 */
645 final BatteryStatsService mBatteryStatsService;
646
647 /**
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800648 * Information about component usage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649 */
650 final UsageStatsService mUsageStatsService;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800651
652 /**
653 * Information about and control over application operations
654 */
655 final AppOpsService mAppOpsService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656
657 /**
658 * Current configuration information. HistoryRecord objects are given
659 * a reference to this object to indicate which configuration they are
660 * currently running in, so this object must be kept immutable.
661 */
662 Configuration mConfiguration = new Configuration();
663
664 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800665 * Current sequencing integer of the configuration, for skipping old
666 * configurations.
667 */
668 int mConfigurationSeq = 0;
669
670 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700671 * Hardware-reported OpenGLES version.
672 */
673 final int GL_ES_VERSION;
674
675 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 * List of initialization arguments to pass to all processes when binding applications to them.
677 * For example, references to the commonly used services.
678 */
679 HashMap<String, IBinder> mAppBindArgs;
680
681 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700682 * Temporary to avoid allocations. Protected by main lock.
683 */
684 final StringBuilder mStringBuilder = new StringBuilder(256);
685
686 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687 * Used to control how we initialize the service.
688 */
689 boolean mStartRunning = false;
690 ComponentName mTopComponent;
691 String mTopAction;
692 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700693 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 boolean mSystemReady = false;
695 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700696 boolean mWaitingUpdate = false;
697 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700698 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700699 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700
701 Context mContext;
702
703 int mFactoryTest;
704
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700705 boolean mCheckedForSetup;
706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700708 * The time at which we will allow normal application switches again,
709 * after a call to {@link #stopAppSwitches()}.
710 */
711 long mAppSwitchesAllowedTime;
712
713 /**
714 * This is set to true after the first switch after mAppSwitchesAllowedTime
715 * is set; any switches after that will clear the time.
716 */
717 boolean mDidAppSwitch;
718
719 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700720 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700721 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700722 long mLastPowerCheckRealtime;
723
724 /**
725 * Last time (in uptime) at which we checked for power usage.
726 */
727 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700728
729 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 * Set while we are wanting to sleep, to prevent any
731 * activities from being started/resumed.
732 */
733 boolean mSleeping = false;
734
735 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700736 * State of external calls telling us if the device is asleep.
737 */
738 boolean mWentToSleep = false;
739
740 /**
741 * State of external call telling us if the lock screen is shown.
742 */
743 boolean mLockScreenShown = false;
744
745 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700746 * Set if we are shutting down the system, similar to sleeping.
747 */
748 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749
750 /**
751 * Task identifier that activities are currently being started
752 * in. Incremented each time a new task is created.
753 * todo: Replace this with a TokenSpace class that generates non-repeating
754 * integers that won't wrap.
755 */
756 int mCurTask = 1;
757
758 /**
759 * Current sequence id for oom_adj computation traversal.
760 */
761 int mAdjSeq = 0;
762
763 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700764 * Current sequence id for process LRU updating.
765 */
766 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
768 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700769 * Keep track of the non-hidden/empty process we last found, to help
770 * determine how to distribute hidden/empty processes next time.
771 */
772 int mNumNonHiddenProcs = 0;
773
774 /**
775 * Keep track of the number of hidden procs, to balance oom adj
776 * distribution between those and empty procs.
777 */
778 int mNumHiddenProcs = 0;
779
780 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700781 * Keep track of the number of service processes we last found, to
782 * determine on the next iteration which should be B services.
783 */
784 int mNumServiceProcs = 0;
785 int mNewNumServiceProcs = 0;
786
787 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 * System monitoring: number of processes that died since the last
789 * N procs were started.
790 */
791 int[] mProcDeaths = new int[20];
792
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700793 /**
794 * This is set if we had to do a delayed dexopt of an app before launching
795 * it, to increasing the ANR timeouts in that case.
796 */
797 boolean mDidDexOpt;
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 String mDebugApp = null;
800 boolean mWaitForDebugger = false;
801 boolean mDebugTransient = false;
802 String mOrigDebugApp = null;
803 boolean mOrigWaitForDebugger = false;
804 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700805 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700806 String mProfileApp = null;
807 ProcessRecord mProfileProc = null;
808 String mProfileFile;
809 ParcelFileDescriptor mProfileFd;
810 int mProfileType = 0;
811 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800812 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700814 static class ProcessChangeItem {
815 static final int CHANGE_ACTIVITIES = 1<<0;
816 static final int CHANGE_IMPORTANCE= 1<<1;
817 int changes;
818 int uid;
819 int pid;
820 int importance;
821 boolean foregroundActivities;
822 }
823
Jeff Sharkeya4620792011-05-20 15:29:23 -0700824 final RemoteCallbackList<IProcessObserver> mProcessObservers
825 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700826 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
827
828 final ArrayList<ProcessChangeItem> mPendingProcessChanges
829 = new ArrayList<ProcessChangeItem>();
830 final ArrayList<ProcessChangeItem> mAvailProcessChanges
831 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 * Runtime statistics collection thread. This object's lock is used to
835 * protect all related state.
836 */
837 final Thread mProcessStatsThread;
838
839 /**
840 * Used to collect process stats when showing not responding dialog.
841 * Protected by mProcessStatsThread.
842 */
843 final ProcessStats mProcessStats = new ProcessStats(
844 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700845 final AtomicLong mLastCpuTime = new AtomicLong(0);
846 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 long mLastWriteTime = 0;
849
850 /**
Christopher Tate73c2aee2012-03-15 16:27:14 -0700851 * Used to retain an update lock when the foreground activity is in
852 * immersive mode.
853 */
854 final UpdateLock mUpdateLock = new UpdateLock("immersive");
855
856 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 * Set to true after the system has finished booting.
858 */
859 boolean mBooted = false;
860
Dianne Hackborn7d608422011-08-07 16:24:18 -0700861 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700862 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863
864 WindowManagerService mWindowManager;
865
866 static ActivityManagerService mSelf;
867 static ActivityThread mSystemThread;
868
Dianne Hackbornc72fc672012-09-20 13:12:03 -0700869 private int mCurrentUserId = 0;
870 private int[] mCurrentUserArray = new int[] { 0 };
Dianne Hackborn1676c852012-09-10 14:52:30 -0700871 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 private final class AppDeathRecipient implements IBinder.DeathRecipient {
874 final ProcessRecord mApp;
875 final int mPid;
876 final IApplicationThread mAppThread;
877
878 AppDeathRecipient(ProcessRecord app, int pid,
879 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800880 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800881 TAG, "New death recipient " + this
882 + " for thread " + thread.asBinder());
883 mApp = app;
884 mPid = pid;
885 mAppThread = thread;
886 }
887
888 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 TAG, "Death received in " + this
891 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 synchronized(ActivityManagerService.this) {
893 appDiedLocked(mApp, mPid, mAppThread);
894 }
895 }
896 }
897
898 static final int SHOW_ERROR_MSG = 1;
899 static final int SHOW_NOT_RESPONDING_MSG = 2;
900 static final int SHOW_FACTORY_ERROR_MSG = 3;
901 static final int UPDATE_CONFIGURATION_MSG = 4;
902 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
903 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 static final int SERVICE_TIMEOUT_MSG = 12;
905 static final int UPDATE_TIME_ZONE = 13;
906 static final int SHOW_UID_ERROR_MSG = 14;
907 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700909 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700910 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800911 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700912 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
913 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700914 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700915 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700916 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700917 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700918 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700919 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700920 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700921 static final int REPORT_MEM_USAGE = 33;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700922 static final int REPORT_USER_SWITCH_MSG = 34;
923 static final int CONTINUE_USER_SWITCH_MSG = 35;
924 static final int USER_SWITCH_TIMEOUT_MSG = 36;
Christopher Tate73c2aee2012-03-15 16:27:14 -0700925 static final int IMMERSIVE_MODE_LOCK_MSG = 37;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800927 static final int FIRST_ACTIVITY_STACK_MSG = 100;
928 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
929 static final int FIRST_COMPAT_MODE_MSG = 300;
930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700932 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700933 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934
935 final Handler mHandler = new Handler() {
936 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800937 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 //}
939
940 public void handleMessage(Message msg) {
941 switch (msg.what) {
942 case SHOW_ERROR_MSG: {
943 HashMap data = (HashMap) msg.obj;
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700944 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
945 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 synchronized (ActivityManagerService.this) {
947 ProcessRecord proc = (ProcessRecord)data.get("app");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700948 AppErrorResult res = (AppErrorResult) data.get("result");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800950 Slog.e(TAG, "App already has crash dialog: " + proc);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700951 if (res != null) {
952 res.set(0);
953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 return;
955 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700956 if (!showBackground && UserHandle.getAppId(proc.uid)
957 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId
958 && proc.pid != MY_PID) {
959 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
960 if (res != null) {
961 res.set(0);
962 }
963 return;
964 }
Joe Onorato54a4a412011-11-02 20:50:08 -0700965 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700966 Dialog d = new AppErrorDialog(mContext,
967 ActivityManagerService.this, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 d.show();
969 proc.crashDialog = d;
970 } else {
971 // The device is asleep, so just pretend that the user
972 // saw a crash dialog and hit "force quit".
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -0700973 if (res != null) {
974 res.set(0);
975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 }
977 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700978
979 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 } break;
981 case SHOW_NOT_RESPONDING_MSG: {
982 synchronized (ActivityManagerService.this) {
983 HashMap data = (HashMap) msg.obj;
984 ProcessRecord proc = (ProcessRecord)data.get("app");
985 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800986 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 return;
988 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800989
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700990 Intent intent = new Intent("android.intent.action.ANR");
991 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800992 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
993 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700994 }
995 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -0800996 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -0700997 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800998
Justin Kohbc52ca22012-03-29 15:11:44 -0700999 if (mShowDialogs) {
1000 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07001001 mContext, proc, (ActivityRecord)data.get("activity"),
1002 msg.arg1 != 0);
Justin Kohbc52ca22012-03-29 15:11:44 -07001003 d.show();
1004 proc.anrDialog = d;
1005 } else {
1006 // Just kill the app if there is no dialog to be shown.
1007 killAppAtUsersRequest(proc, null);
1008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001010
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001011 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001013 case SHOW_STRICT_MODE_VIOLATION_MSG: {
1014 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1015 synchronized (ActivityManagerService.this) {
1016 ProcessRecord proc = (ProcessRecord) data.get("app");
1017 if (proc == null) {
1018 Slog.e(TAG, "App not found when showing strict mode dialog.");
1019 break;
1020 }
1021 if (proc.crashDialog != null) {
1022 Slog.e(TAG, "App already has strict mode dialog: " + proc);
1023 return;
1024 }
1025 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -07001026 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07001027 Dialog d = new StrictModeViolationDialog(mContext,
1028 ActivityManagerService.this, res, proc);
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07001029 d.show();
1030 proc.crashDialog = d;
1031 } else {
1032 // The device is asleep, so just pretend that the user
1033 // saw a crash dialog and hit "force quit".
1034 res.set(0);
1035 }
1036 }
1037 ensureBootCompleted();
1038 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 case SHOW_FACTORY_ERROR_MSG: {
1040 Dialog d = new FactoryErrorDialog(
1041 mContext, msg.getData().getCharSequence("msg"));
1042 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001043 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 } break;
1045 case UPDATE_CONFIGURATION_MSG: {
1046 final ContentResolver resolver = mContext.getContentResolver();
1047 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
1048 } break;
1049 case GC_BACKGROUND_PROCESSES_MSG: {
1050 synchronized (ActivityManagerService.this) {
1051 performAppGcsIfAppropriateLocked();
1052 }
1053 } break;
1054 case WAIT_FOR_DEBUGGER_MSG: {
1055 synchronized (ActivityManagerService.this) {
1056 ProcessRecord app = (ProcessRecord)msg.obj;
1057 if (msg.arg1 != 0) {
1058 if (!app.waitedForDebugger) {
1059 Dialog d = new AppWaitingForDebuggerDialog(
1060 ActivityManagerService.this,
1061 mContext, app);
1062 app.waitDialog = d;
1063 app.waitedForDebugger = true;
1064 d.show();
1065 }
1066 } else {
1067 if (app.waitDialog != null) {
1068 app.waitDialog.dismiss();
1069 app.waitDialog = null;
1070 }
1071 }
1072 }
1073 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001075 if (mDidDexOpt) {
1076 mDidDexOpt = false;
1077 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1078 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001079 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001080 return;
1081 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001082 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 } break;
1084 case UPDATE_TIME_ZONE: {
1085 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001086 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1087 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 if (r.thread != null) {
1089 try {
1090 r.thread.updateTimeZone();
1091 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001092 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
1094 }
1095 }
1096 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001097 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001098 case CLEAR_DNS_CACHE: {
1099 synchronized (ActivityManagerService.this) {
1100 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1101 ProcessRecord r = mLruProcesses.get(i);
1102 if (r.thread != null) {
1103 try {
1104 r.thread.clearDnsCache();
1105 } catch (RemoteException ex) {
1106 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1107 }
1108 }
1109 }
1110 }
1111 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001112 case UPDATE_HTTP_PROXY: {
1113 ProxyProperties proxy = (ProxyProperties)msg.obj;
1114 String host = "";
1115 String port = "";
1116 String exclList = "";
1117 if (proxy != null) {
1118 host = proxy.getHost();
1119 port = Integer.toString(proxy.getPort());
1120 exclList = proxy.getExclusionList();
1121 }
1122 synchronized (ActivityManagerService.this) {
1123 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1124 ProcessRecord r = mLruProcesses.get(i);
1125 if (r.thread != null) {
1126 try {
1127 r.thread.setHttpProxy(host, port, exclList);
1128 } catch (RemoteException ex) {
1129 Slog.w(TAG, "Failed to update http proxy for: " +
1130 r.info.processName);
1131 }
1132 }
1133 }
1134 }
1135 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001137 String title = "System UIDs Inconsistent";
1138 String text = "UIDs on the system are inconsistent, you need to wipe your"
1139 + " data partition or your device will be unstable.";
1140 Log.e(TAG, title + ": " + text);
1141 if (mShowDialogs) {
1142 // XXX This is a temporary dialog, no need to localize.
1143 AlertDialog d = new BaseErrorDialog(mContext);
1144 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1145 d.setCancelable(false);
1146 d.setTitle(title);
1147 d.setMessage(text);
1148 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1149 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1150 mUidAlert = d;
1151 d.show();
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } break;
1154 case IM_FEELING_LUCKY_MSG: {
1155 if (mUidAlert != null) {
1156 mUidAlert.dismiss();
1157 mUidAlert = null;
1158 }
1159 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001161 if (mDidDexOpt) {
1162 mDidDexOpt = false;
1163 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1164 nmsg.obj = msg.obj;
1165 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1166 return;
1167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 ProcessRecord app = (ProcessRecord)msg.obj;
1169 synchronized (ActivityManagerService.this) {
1170 processStartTimedOutLocked(app);
1171 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001172 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001173 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1174 synchronized (ActivityManagerService.this) {
1175 doPendingActivityLaunchesLocked(true);
1176 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001177 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001178 case KILL_APPLICATION_MSG: {
1179 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001180 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001181 boolean restart = (msg.arg2 == 1);
1182 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001183 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1184 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001185 }
1186 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001187 case FINALIZE_PENDING_INTENT_MSG: {
1188 ((PendingIntentRecord)msg.obj).completeFinalize();
1189 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001190 case POST_HEAVY_NOTIFICATION_MSG: {
1191 INotificationManager inm = NotificationManager.getService();
1192 if (inm == null) {
1193 return;
1194 }
1195
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001196 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001197 ProcessRecord process = root.app;
1198 if (process == null) {
1199 return;
1200 }
1201
1202 try {
1203 Context context = mContext.createPackageContext(process.info.packageName, 0);
1204 String text = mContext.getString(R.string.heavy_weight_notification,
1205 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1206 Notification notification = new Notification();
1207 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1208 notification.when = 0;
1209 notification.flags = Notification.FLAG_ONGOING_EVENT;
1210 notification.tickerText = text;
1211 notification.defaults = 0; // please be quiet
1212 notification.sound = null;
1213 notification.vibrate = null;
1214 notification.setLatestEventInfo(context, text,
1215 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001216 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1217 PendingIntent.FLAG_CANCEL_CURRENT, null,
1218 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001219
1220 try {
1221 int[] outId = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001222 inm.enqueueNotificationWithTag("android", "android", null,
Dianne Hackborn41203752012-08-31 14:05:51 -07001223 R.string.heavy_weight_notification,
1224 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001225 } catch (RuntimeException e) {
1226 Slog.w(ActivityManagerService.TAG,
1227 "Error showing notification for heavy-weight app", e);
1228 } catch (RemoteException e) {
1229 }
1230 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001231 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001232 }
1233 } break;
1234 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1235 INotificationManager inm = NotificationManager.getService();
1236 if (inm == null) {
1237 return;
1238 }
1239 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001240 inm.cancelNotificationWithTag("android", null,
1241 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001242 } catch (RuntimeException e) {
1243 Slog.w(ActivityManagerService.TAG,
1244 "Error canceling notification for service", e);
1245 } catch (RemoteException e) {
1246 }
1247 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001248 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1249 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001250 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001251 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001252 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1253 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001254 }
1255 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001256 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1257 synchronized (ActivityManagerService.this) {
1258 ActivityRecord ar = (ActivityRecord)msg.obj;
1259 if (mCompatModeDialog != null) {
1260 if (mCompatModeDialog.mAppInfo.packageName.equals(
1261 ar.info.applicationInfo.packageName)) {
1262 return;
1263 }
1264 mCompatModeDialog.dismiss();
1265 mCompatModeDialog = null;
1266 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001267 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001268 if (mCompatModePackages.getPackageAskCompatModeLocked(
1269 ar.packageName)) {
1270 int mode = mCompatModePackages.computeCompatModeLocked(
1271 ar.info.applicationInfo);
1272 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1273 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1274 mCompatModeDialog = new CompatModeDialog(
1275 ActivityManagerService.this, mContext,
1276 ar.info.applicationInfo);
1277 mCompatModeDialog.show();
1278 }
1279 }
1280 }
1281 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001282 break;
1283 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001284 case DISPATCH_PROCESSES_CHANGED: {
1285 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001286 break;
1287 }
1288 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001289 final int pid = msg.arg1;
1290 final int uid = msg.arg2;
1291 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001292 break;
1293 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001294 case REPORT_MEM_USAGE: {
1295 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1296 if (!isDebuggable) {
1297 return;
1298 }
1299 synchronized (ActivityManagerService.this) {
1300 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001301 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1302 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001303 // avoid spamming.
1304 return;
1305 }
1306 mLastMemUsageReportTime = now;
1307 }
1308 Thread thread = new Thread() {
1309 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001310 StringBuilder dropBuilder = new StringBuilder(1024);
1311 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001312 StringWriter oomSw = new StringWriter();
1313 PrintWriter oomPw = new PrintWriter(oomSw);
1314 StringWriter catSw = new StringWriter();
1315 PrintWriter catPw = new PrintWriter(catSw);
1316 String[] emptyArgs = new String[] { };
1317 StringBuilder tag = new StringBuilder(128);
1318 StringBuilder stack = new StringBuilder(128);
1319 tag.append("Low on memory -- ");
1320 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1321 tag, stack);
1322 dropBuilder.append(stack);
1323 dropBuilder.append('\n');
1324 dropBuilder.append('\n');
1325 String oomString = oomSw.toString();
1326 dropBuilder.append(oomString);
1327 dropBuilder.append('\n');
1328 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001329 try {
1330 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1331 "procrank", });
1332 final InputStreamReader converter = new InputStreamReader(
1333 proc.getInputStream());
1334 BufferedReader in = new BufferedReader(converter);
1335 String line;
1336 while (true) {
1337 line = in.readLine();
1338 if (line == null) {
1339 break;
1340 }
1341 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001342 logBuilder.append(line);
1343 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001344 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001345 dropBuilder.append(line);
1346 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001347 }
1348 converter.close();
1349 } catch (IOException e) {
1350 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001351 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001352 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001353 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001354 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001355 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1356 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001357 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001358 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001359 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001360 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001361 addErrorToDropBox("lowmem", null, "system_server", null,
1362 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001363 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001364 synchronized (ActivityManagerService.this) {
1365 long now = SystemClock.uptimeMillis();
1366 if (mLastMemUsageReportTime < now) {
1367 mLastMemUsageReportTime = now;
1368 }
1369 }
1370 }
1371 };
1372 thread.start();
1373 break;
1374 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001375 case REPORT_USER_SWITCH_MSG: {
1376 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1377 break;
1378 }
1379 case CONTINUE_USER_SWITCH_MSG: {
1380 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1381 break;
1382 }
1383 case USER_SWITCH_TIMEOUT_MSG: {
1384 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2);
1385 break;
1386 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001387 case IMMERSIVE_MODE_LOCK_MSG: {
1388 final boolean nextState = (msg.arg1 != 0);
1389 if (mUpdateLock.isHeld() != nextState) {
1390 if (DEBUG_IMMERSIVE) {
1391 final ActivityRecord r = (ActivityRecord) msg.obj;
1392 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r);
1393 }
1394 if (nextState) {
1395 mUpdateLock.acquire();
1396 } else {
1397 mUpdateLock.release();
1398 }
1399 }
1400 break;
1401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 }
1403 }
1404 };
1405
1406 public static void setSystemProcess() {
1407 try {
1408 ActivityManagerService m = mSelf;
1409
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001410 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001412 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001413 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 if (MONITOR_CPU_USAGE) {
1415 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 ServiceManager.addService("permission", new PermissionController(m));
1418
1419 ApplicationInfo info =
1420 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001421 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001422 mSystemThread.installSystemApplicationInfo(info);
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 synchronized (mSelf) {
1425 ProcessRecord app = mSelf.newProcessRecordLocked(
1426 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001427 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001429 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001430 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001431 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 synchronized (mSelf.mPidsSelfLocked) {
1433 mSelf.mPidsSelfLocked.put(app.pid, app);
1434 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001435 mSelf.updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 }
1437 } catch (PackageManager.NameNotFoundException e) {
1438 throw new RuntimeException(
1439 "Unable to find android system package", e);
1440 }
1441 }
1442
1443 public void setWindowManager(WindowManagerService wm) {
1444 mWindowManager = wm;
1445 }
1446
1447 public static final Context main(int factoryTest) {
1448 AThread thr = new AThread();
1449 thr.start();
1450
1451 synchronized (thr) {
1452 while (thr.mService == null) {
1453 try {
1454 thr.wait();
1455 } catch (InterruptedException e) {
1456 }
1457 }
1458 }
1459
1460 ActivityManagerService m = thr.mService;
1461 mSelf = m;
1462 ActivityThread at = ActivityThread.systemMain();
1463 mSystemThread = at;
1464 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001465 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 m.mContext = context;
1467 m.mFactoryTest = factoryTest;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001468 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469
1470 m.mBatteryStatsService.publish(context);
1471 m.mUsageStatsService.publish(context);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001472 m.mAppOpsService.publish(context);
1473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 synchronized (thr) {
1475 thr.mReady = true;
1476 thr.notifyAll();
1477 }
1478
1479 m.startRunning(null, null, null, null);
1480
1481 return context;
1482 }
1483
1484 public static ActivityManagerService self() {
1485 return mSelf;
1486 }
1487
1488 static class AThread extends Thread {
1489 ActivityManagerService mService;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001490 Looper mLooper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 boolean mReady = false;
1492
1493 public AThread() {
1494 super("ActivityManager");
1495 }
1496
1497 public void run() {
1498 Looper.prepare();
1499
1500 android.os.Process.setThreadPriority(
1501 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001502 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
1504 ActivityManagerService m = new ActivityManagerService();
1505
1506 synchronized (this) {
1507 mService = m;
Zoran Marcetaf958b322012-08-09 20:27:12 +09001508 mLooper = Looper.myLooper();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 notifyAll();
1510 }
1511
1512 synchronized (this) {
1513 while (!mReady) {
1514 try {
1515 wait();
1516 } catch (InterruptedException e) {
1517 }
1518 }
1519 }
1520
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001521 // For debug builds, log event loop stalls to dropbox for analysis.
1522 if (StrictMode.conditionallyEnableDebugLogging()) {
1523 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1524 }
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 Looper.loop();
1527 }
1528 }
1529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 static class MemBinder extends Binder {
1531 ActivityManagerService mActivityManagerService;
1532 MemBinder(ActivityManagerService activityManagerService) {
1533 mActivityManagerService = activityManagerService;
1534 }
1535
1536 @Override
1537 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001538 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1539 != PackageManager.PERMISSION_GRANTED) {
1540 pw.println("Permission Denial: can't dump meminfo from from pid="
1541 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1542 + " without permission " + android.Manifest.permission.DUMP);
1543 return;
1544 }
1545
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001546 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001547 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 }
1550
Chet Haase9c1e23b2011-03-24 10:51:31 -07001551 static class GraphicsBinder extends Binder {
1552 ActivityManagerService mActivityManagerService;
1553 GraphicsBinder(ActivityManagerService activityManagerService) {
1554 mActivityManagerService = activityManagerService;
1555 }
1556
1557 @Override
1558 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001559 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1560 != PackageManager.PERMISSION_GRANTED) {
1561 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1562 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1563 + " without permission " + android.Manifest.permission.DUMP);
1564 return;
1565 }
1566
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001567 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001568 }
1569 }
1570
Jeff Brown6754ba22011-12-14 20:20:01 -08001571 static class DbBinder extends Binder {
1572 ActivityManagerService mActivityManagerService;
1573 DbBinder(ActivityManagerService activityManagerService) {
1574 mActivityManagerService = activityManagerService;
1575 }
1576
1577 @Override
1578 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1579 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1580 != PackageManager.PERMISSION_GRANTED) {
1581 pw.println("Permission Denial: can't dump dbinfo from from pid="
1582 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1583 + " without permission " + android.Manifest.permission.DUMP);
1584 return;
1585 }
1586
1587 mActivityManagerService.dumpDbInfo(fd, pw, args);
1588 }
1589 }
1590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 static class CpuBinder extends Binder {
1592 ActivityManagerService mActivityManagerService;
1593 CpuBinder(ActivityManagerService activityManagerService) {
1594 mActivityManagerService = activityManagerService;
1595 }
1596
1597 @Override
1598 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001599 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1600 != PackageManager.PERMISSION_GRANTED) {
1601 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1602 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1603 + " without permission " + android.Manifest.permission.DUMP);
1604 return;
1605 }
1606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001608 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1609 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1610 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612 }
1613 }
1614
1615 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001617
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001618 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1619 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1620 mBroadcastQueues[0] = mFgBroadcastQueue;
1621 mBroadcastQueues[1] = mBgBroadcastQueue;
1622
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001623 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001624 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 File dataDir = Environment.getDataDirectory();
1627 File systemDir = new File(dataDir, "system");
1628 systemDir.mkdirs();
1629 mBatteryStatsService = new BatteryStatsService(new File(
1630 systemDir, "batterystats.bin").toString());
1631 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001632 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001633 mOnBattery = DEBUG_POWER ? true
1634 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001635 mBatteryStatsService.getActiveStatistics().setCallback(this);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001636
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001637 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001638 systemDir, "usagestats").toString());
Dianne Hackborn35654b62013-01-14 17:38:02 -08001639 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"));
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001640 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001642 // User 0 is the first and only user that runs at boot.
1643 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001644 mUserLru.add(Integer.valueOf(0));
Dianne Hackbornc72fc672012-09-20 13:12:03 -07001645 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001646
Jack Palevichb90d28c2009-07-22 15:35:24 -07001647 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1648 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1649
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001650 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001651 mConfiguration.setLocale(Locale.getDefault());
1652
Dianne Hackborn813075a62011-11-14 17:45:19 -08001653 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 mProcessStats.init();
1655
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001656 mCompatModePackages = new CompatModePackages(this, systemDir);
1657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 // Add ourself to the Watchdog monitors.
1659 Watchdog.getInstance().addMonitor(this);
1660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 mProcessStatsThread = new Thread("ProcessStats") {
1662 public void run() {
1663 while (true) {
1664 try {
1665 try {
1666 synchronized(this) {
1667 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001668 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001670 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 // + ", write delay=" + nextWriteDelay);
1672 if (nextWriteDelay < nextCpuDelay) {
1673 nextCpuDelay = nextWriteDelay;
1674 }
1675 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001676 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 this.wait(nextCpuDelay);
1678 }
1679 }
1680 } catch (InterruptedException e) {
1681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 updateCpuStatsNow();
1683 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001684 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686 }
1687 }
1688 };
1689 mProcessStatsThread.start();
1690 }
1691
1692 @Override
1693 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1694 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001695 if (code == SYSPROPS_TRANSACTION) {
1696 // We need to tell all apps about the system property change.
1697 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1698 synchronized(this) {
1699 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1700 final int NA = apps.size();
1701 for (int ia=0; ia<NA; ia++) {
1702 ProcessRecord app = apps.valueAt(ia);
1703 if (app.thread != null) {
1704 procs.add(app.thread.asBinder());
1705 }
1706 }
1707 }
1708 }
1709
1710 int N = procs.size();
1711 for (int i=0; i<N; i++) {
1712 Parcel data2 = Parcel.obtain();
1713 try {
1714 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1715 } catch (RemoteException e) {
1716 }
1717 data2.recycle();
1718 }
1719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 try {
1721 return super.onTransact(code, data, reply, flags);
1722 } catch (RuntimeException e) {
1723 // The activity manager only throws security exceptions, so let's
1724 // log all others.
1725 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001726 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 }
1728 throw e;
1729 }
1730 }
1731
1732 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001733 final long now = SystemClock.uptimeMillis();
1734 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1735 return;
1736 }
1737 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1738 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 mProcessStatsThread.notify();
1740 }
1741 }
1742 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 void updateCpuStatsNow() {
1745 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001746 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 final long now = SystemClock.uptimeMillis();
1748 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001751 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1752 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 haveNewCpuStats = true;
1754 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001755 //Slog.i(TAG, mProcessStats.printCurrentState());
1756 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 // + mProcessStats.getTotalCpuPercent() + "%");
1758
Joe Onorato8a9b2202010-02-26 18:56:32 -08001759 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 if ("true".equals(SystemProperties.get("events.cpu"))) {
1761 int user = mProcessStats.getLastUserTime();
1762 int system = mProcessStats.getLastSystemTime();
1763 int iowait = mProcessStats.getLastIoWaitTime();
1764 int irq = mProcessStats.getLastIrqTime();
1765 int softIrq = mProcessStats.getLastSoftIrqTime();
1766 int idle = mProcessStats.getLastIdleTime();
1767
1768 int total = user + system + iowait + irq + softIrq + idle;
1769 if (total == 0) total = 1;
1770
Doug Zongker2bec3d42009-12-04 12:52:44 -08001771 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 ((user+system+iowait+irq+softIrq) * 100) / total,
1773 (user * 100) / total,
1774 (system * 100) / total,
1775 (iowait * 100) / total,
1776 (irq * 100) / total,
1777 (softIrq * 100) / total);
1778 }
1779 }
1780
Amith Yamasanie43530a2009-08-21 13:11:37 -07001781 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001782 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001783 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 synchronized(mPidsSelfLocked) {
1785 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001786 if (mOnBattery) {
1787 int perc = bstats.startAddingCpuLocked();
1788 int totalUTime = 0;
1789 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001790 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001792 ProcessStats.Stats st = mProcessStats.getStats(i);
1793 if (!st.working) {
1794 continue;
1795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001797 int otherUTime = (st.rel_utime*perc)/100;
1798 int otherSTime = (st.rel_stime*perc)/100;
1799 totalUTime += otherUTime;
1800 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 if (pr != null) {
1802 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001803 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1804 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001805 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001806 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001807 } else {
1808 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001809 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001810 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001811 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1812 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001813 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001817 bstats.finishAddingCpuLocked(perc, totalUTime,
1818 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
1820 }
1821 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1824 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001825 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828 }
1829 }
1830
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001831 @Override
1832 public void batteryNeedsCpuUpdate() {
1833 updateCpuStatsNow();
1834 }
1835
1836 @Override
1837 public void batteryPowerChanged(boolean onBattery) {
1838 // When plugging in, update the CPU stats first before changing
1839 // the plug state.
1840 updateCpuStatsNow();
1841 synchronized (this) {
1842 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001843 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001844 }
1845 }
1846 }
1847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 /**
1849 * Initialize the application bind args. These are passed to each
1850 * process when the bindApplication() IPC is sent to the process. They're
1851 * lazily setup to make sure the services are running when they're asked for.
1852 */
1853 private HashMap<String, IBinder> getCommonServicesLocked() {
1854 if (mAppBindArgs == null) {
1855 mAppBindArgs = new HashMap<String, IBinder>();
1856
1857 // Setup the application init args
1858 mAppBindArgs.put("package", ServiceManager.getService("package"));
1859 mAppBindArgs.put("window", ServiceManager.getService("window"));
1860 mAppBindArgs.put(Context.ALARM_SERVICE,
1861 ServiceManager.getService(Context.ALARM_SERVICE));
1862 }
1863 return mAppBindArgs;
1864 }
1865
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001866 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 if (mFocusedActivity != r) {
1868 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001869 if (r != null) {
1870 mWindowManager.setFocusedApp(r.appToken, true);
1871 }
Christopher Tate73c2aee2012-03-15 16:27:14 -07001872 applyUpdateLockStateLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 }
1874 }
1875
Christopher Tate73c2aee2012-03-15 16:27:14 -07001876 final void applyUpdateLockStateLocked(ActivityRecord r) {
1877 // Modifications to the UpdateLock state are done on our handler, outside
1878 // the activity manager's locks. The new state is determined based on the
1879 // state *now* of the relevant activity record. The object is passed to
1880 // the handler solely for logging detail, not to be consulted/modified.
1881 final boolean nextState = r != null && r.immersive;
1882 mHandler.sendMessage(
1883 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r));
1884 }
1885
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001886 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001888 int lrui = mLruProcesses.indexOf(app);
1889 if (lrui >= 0) mLruProcesses.remove(lrui);
1890
1891 int i = mLruProcesses.size()-1;
1892 int skipTop = 0;
1893
Dianne Hackborn906497c2010-05-10 15:57:38 -07001894 app.lruSeq = mLruSeq;
1895
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001896 // compute the new weight for this process.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001897 app.lastActivityTime = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001898 if (app.activities.size() > 0) {
1899 // If this process has activities, we more strongly want to keep
1900 // it around.
1901 app.lruWeight = app.lastActivityTime;
1902 } else if (app.pubProviders.size() > 0) {
1903 // If this process contains content providers, we want to keep
1904 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001905 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001906 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001907 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001908 } else {
1909 // If this process doesn't have activities, we less strongly
1910 // want to keep it around, and generally want to avoid getting
1911 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001912 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001913 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001914 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001915 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001916
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001917 while (i >= 0) {
1918 ProcessRecord p = mLruProcesses.get(i);
1919 // If this app shouldn't be in front of the first N background
1920 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001921 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001922 skipTop--;
1923 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001924 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001925 mLruProcesses.add(i+1, app);
1926 break;
1927 }
1928 i--;
1929 }
1930 if (i < 0) {
1931 mLruProcesses.add(0, app);
1932 }
1933
Dianne Hackborn906497c2010-05-10 15:57:38 -07001934 // If the app is currently using a content provider or service,
1935 // bump those processes as well.
1936 if (app.connections.size() > 0) {
1937 for (ConnectionRecord cr : app.connections) {
1938 if (cr.binding != null && cr.binding.service != null
1939 && cr.binding.service.app != null
1940 && cr.binding.service.app.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001941 updateLruProcessInternalLocked(cr.binding.service.app, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001942 }
1943 }
1944 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001945 for (int j=app.conProviders.size()-1; j>=0; j--) {
1946 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1947 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001948 updateLruProcessInternalLocked(cpr.proc, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001949 }
1950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001953 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001954 boolean oomAdj) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07001955 mLruSeq++;
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001956 updateLruProcessInternalLocked(app, 0);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001957
1958 //Slog.i(TAG, "Putting proc to front: " + app.processName);
1959 if (oomAdj) {
1960 updateOomAdjLocked();
1961 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001962 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001963
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001964 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001966 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001967 // The system gets to run in any process. If there are multiple
1968 // processes with the same uid, just pick the first (this
1969 // should never happen).
1970 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1971 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001972 if (procs == null) return null;
1973 final int N = procs.size();
1974 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001975 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
1978 ProcessRecord proc = mProcessNames.get(processName, uid);
1979 return proc;
1980 }
1981
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001982 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001983 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001984 try {
1985 if (pm.performDexOpt(packageName)) {
1986 mDidDexOpt = true;
1987 }
1988 } catch (RemoteException e) {
1989 }
1990 }
1991
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001992 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 int transit = mWindowManager.getPendingAppTransition();
Craig Mautner4b71aa12012-12-27 17:20:01 -08001994 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN
1995 || transit == AppTransition.TRANSIT_TASK_OPEN
1996 || transit == AppTransition.TRANSIT_TASK_TO_FRONT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
1998
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001999 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002001 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
2002 boolean isolated) {
2003 ProcessRecord app;
2004 if (!isolated) {
2005 app = getProcessRecordLocked(processName, info.uid);
2006 } else {
2007 // If this is an isolated process, it can't re-use an existing process.
2008 app = null;
2009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 // We don't have to do anything more if:
2011 // (1) There is an existing application record; and
2012 // (2) The caller doesn't think it is dead, OR there is no thread
2013 // object attached to it so we know it couldn't have crashed; and
2014 // (3) There is a pid assigned to it, so it is either starting or
2015 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002016 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 + " app=" + app + " knownToBeDead=" + knownToBeDead
2018 + " thread=" + (app != null ? app.thread : null)
2019 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01002020 if (app != null && app.pid > 0) {
2021 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08002022 // We already have the app running, or are waiting for it to
2023 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002024 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002025 // If this is a new package in the process, add the package to the list
2026 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002027 return app;
2028 } else {
2029 // An application record is attached to a previous process,
2030 // clean it up now.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002031 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002032 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01002033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 String hostingNameStr = hostingName != null
2037 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002038
2039 if (!isolated) {
2040 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
2041 // If we are in the background, then check to see if this process
2042 // is bad. If so, we will just silently fail.
2043 if (mBadProcesses.get(info.processName, info.uid) != null) {
2044 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
2045 + "/" + info.processName);
2046 return null;
2047 }
2048 } else {
2049 // When the user is explicitly starting a process, then clear its
2050 // crash count so that we won't make it bad until they see at
2051 // least one crash dialog again, and make the process good again
2052 // if it had been bad.
2053 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002054 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002055 mProcessCrashTimes.remove(info.processName, info.uid);
2056 if (mBadProcesses.get(info.processName, info.uid) != null) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002057 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
2058 UserHandle.getUserId(info.uid), info.uid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002059 info.processName);
2060 mBadProcesses.remove(info.processName, info.uid);
2061 if (app != null) {
2062 app.bad = false;
2063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065 }
2066 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002069 app = newProcessRecordLocked(null, info, processName, isolated);
2070 if (app == null) {
2071 Slog.w(TAG, "Failed making new process record for "
2072 + processName + "/" + info.uid + " isolated=" + isolated);
2073 return null;
2074 }
2075 mProcessNames.put(processName, app.uid, app);
2076 if (isolated) {
2077 mIsolatedProcesses.put(app.uid, app);
2078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 } else {
2080 // If this is a new package in the process, add the package to the list
2081 app.addPackage(info.packageName);
2082 }
2083
2084 // If the system is not ready yet, then hold off on starting this
2085 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002086 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002087 && !isAllowedWhileBooting(info)
2088 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 if (!mProcessesOnHold.contains(app)) {
2090 mProcessesOnHold.add(app);
2091 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002092 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 return app;
2094 }
2095
2096 startProcessLocked(app, hostingType, hostingNameStr);
2097 return (app.pid != 0) ? app : null;
2098 }
2099
Dianne Hackborn9acc0302009-08-25 00:27:12 -07002100 boolean isAllowedWhileBooting(ApplicationInfo ai) {
2101 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
2102 }
2103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002104 private final void startProcessLocked(ProcessRecord app,
2105 String hostingType, String hostingNameStr) {
2106 if (app.pid > 0 && app.pid != MY_PID) {
2107 synchronized (mPidsSelfLocked) {
2108 mPidsSelfLocked.remove(app.pid);
2109 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
2110 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002111 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 }
2113
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002114 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2115 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 mProcessesOnHold.remove(app);
2117
2118 updateCpuStats();
2119
2120 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2121 mProcDeaths[0] = 0;
2122
2123 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002124 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002127 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002128 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002129 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002130 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002131 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002132 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002133
2134 if (Environment.isExternalStorageEmulated()) {
2135 if (pm.checkPermission(
2136 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2137 app.info.packageName) == PERMISSION_GRANTED) {
2138 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2139 } else {
2140 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2141 }
2142 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002143 } catch (PackageManager.NameNotFoundException e) {
2144 Slog.w(TAG, "Unable to retrieve gids", e);
2145 }
Kenny Roote091f222012-09-11 15:01:26 -07002146
2147 /*
2148 * Add shared application GID so applications can share some
2149 * resources like shared libraries
2150 */
2151 if (permGids == null) {
2152 gids = new int[1];
2153 } else {
2154 gids = new int[permGids.length + 1];
2155 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2156 }
2157 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 }
2159 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2160 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2161 && mTopComponent != null
2162 && app.processName.equals(mTopComponent.getPackageName())) {
2163 uid = 0;
2164 }
2165 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2166 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2167 uid = 0;
2168 }
2169 }
2170 int debugFlags = 0;
2171 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2172 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002173 // Also turn on CheckJNI for debuggable apps. It's quite
2174 // awkward to turn on otherwise.
2175 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002177 // Run the app in safe mode if its manifest requests so or the
2178 // system is booted in safe mode.
2179 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2180 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002181 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2184 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2185 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002186 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2187 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 if ("1".equals(SystemProperties.get("debug.assert"))) {
2190 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2191 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002192
2193 // Start the process. It will either succeed and return a result containing
2194 // the PID of the new process, or else throw a RuntimeException.
2195 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002196 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002197 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2200 synchronized (bs) {
2201 if (bs.isOnBattery()) {
2202 app.batteryStats.incStartsLocked();
2203 }
2204 }
2205
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002206 EventLog.writeEvent(EventLogTags.AM_PROC_START,
2207 UserHandle.getUserId(uid), startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 app.processName, hostingType,
2209 hostingNameStr != null ? hostingNameStr : "");
2210
2211 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002212 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002213 }
2214
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002215 StringBuilder buf = mStringBuilder;
2216 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 buf.append("Start proc ");
2218 buf.append(app.processName);
2219 buf.append(" for ");
2220 buf.append(hostingType);
2221 if (hostingNameStr != null) {
2222 buf.append(" ");
2223 buf.append(hostingNameStr);
2224 }
2225 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002226 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 buf.append(" uid=");
2228 buf.append(uid);
2229 buf.append(" gids={");
2230 if (gids != null) {
2231 for (int gi=0; gi<gids.length; gi++) {
2232 if (gi != 0) buf.append(", ");
2233 buf.append(gids[gi]);
2234
2235 }
2236 }
2237 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002238 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002239 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002240 app.usingWrapper = startResult.usingWrapper;
2241 app.removed = false;
2242 synchronized (mPidsSelfLocked) {
2243 this.mPidsSelfLocked.put(startResult.pid, app);
2244 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2245 msg.obj = app;
2246 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2247 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
2249 } catch (RuntimeException e) {
2250 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002251 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002252 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 }
2254 }
2255
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 if (resumed) {
2258 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2259 } else {
2260 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2261 }
2262 }
2263
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07002264 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002265 if (mHeadless) {
2266 // Added because none of the other calls to ensureBootCompleted seem to fire
2267 // when running headless.
2268 ensureBootCompleted();
2269 return false;
2270 }
2271
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002272 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2273 && mTopAction == null) {
2274 // We are running in factory test mode, but unable to find
2275 // the factory test app, so just sit around displaying the
2276 // error message and don't try to start anything.
2277 return false;
2278 }
2279 Intent intent = new Intent(
2280 mTopAction,
2281 mTopData != null ? Uri.parse(mTopData) : null);
2282 intent.setComponent(mTopComponent);
2283 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2284 intent.addCategory(Intent.CATEGORY_HOME);
2285 }
2286 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002287 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002288 if (aInfo != null) {
2289 intent.setComponent(new ComponentName(
2290 aInfo.applicationInfo.packageName, aInfo.name));
2291 // Don't do this if the home app is currently being
2292 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002293 aInfo = new ActivityInfo(aInfo);
2294 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002295 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2296 aInfo.applicationInfo.uid);
2297 if (app == null || app.instrumentationClass == null) {
2298 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002299 mMainStack.startActivityLocked(null, intent, null, aInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002300 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002301 }
2302 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002303
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002304 return true;
2305 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002306
Amith Yamasani259d5e52012-08-31 15:11:01 -07002307 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2308 ActivityInfo ai = null;
2309 ComponentName comp = intent.getComponent();
2310 try {
2311 if (comp != null) {
2312 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2313 } else {
2314 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2315 intent,
2316 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2317 flags, userId);
2318
2319 if (info != null) {
2320 ai = info.activityInfo;
2321 }
2322 }
2323 } catch (RemoteException e) {
2324 // ignore
2325 }
2326
2327 return ai;
2328 }
2329
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002330 /**
2331 * Starts the "new version setup screen" if appropriate.
2332 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002334 // Only do this once per boot.
2335 if (mCheckedForSetup) {
2336 return;
2337 }
2338
2339 // We will show this screen if the current one is a different
2340 // version than the last one shown, and we are not running in
2341 // low-level factory test mode.
2342 final ContentResolver resolver = mContext.getContentResolver();
2343 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002344 Settings.Global.getInt(resolver,
2345 Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002346 mCheckedForSetup = true;
2347
2348 // See if we should be showing the platform update setup UI.
2349 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2350 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2351 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2352
2353 // We don't allow third party apps to replace this.
2354 ResolveInfo ri = null;
2355 for (int i=0; ris != null && i<ris.size(); i++) {
2356 if ((ris.get(i).activityInfo.applicationInfo.flags
2357 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2358 ri = ris.get(i);
2359 break;
2360 }
2361 }
2362
2363 if (ri != null) {
2364 String vers = ri.activityInfo.metaData != null
2365 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2366 : null;
2367 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2368 vers = ri.activityInfo.applicationInfo.metaData.getString(
2369 Intent.METADATA_SETUP_VERSION);
2370 }
2371 String lastVers = Settings.Secure.getString(
2372 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2373 if (vers != null && !vers.equals(lastVers)) {
2374 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2375 intent.setComponent(new ComponentName(
2376 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002377 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002378 null, null, 0, 0, 0, null, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002379 }
2380 }
2381 }
2382 }
2383
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002384 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002385 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002386 }
2387
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002388 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002389 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002390 throw new SecurityException("Isolated process not allowed to call " + caller);
2391 }
2392 }
2393
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002394 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002395 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002396 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002397 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2398 }
2399 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002400
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002401 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002402 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2403 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002404 synchronized (this) {
2405 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2406 }
2407 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002408
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002409 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002410 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002411 synchronized (this) {
2412 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2413 }
2414 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002415
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002416 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002417 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2418 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002419 synchronized (this) {
2420 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002421 }
2422 }
2423
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002424 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002425 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002426 synchronized (this) {
2427 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2428 }
2429 }
2430
2431 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002432 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2433 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002434 synchronized (this) {
2435 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2436 }
2437 }
2438
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002439 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002440 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002441 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002444 private void dispatchProcessesChanged() {
2445 int N;
2446 synchronized (this) {
2447 N = mPendingProcessChanges.size();
2448 if (mActiveProcessChanges.length < N) {
2449 mActiveProcessChanges = new ProcessChangeItem[N];
2450 }
2451 mPendingProcessChanges.toArray(mActiveProcessChanges);
2452 mAvailProcessChanges.addAll(mPendingProcessChanges);
2453 mPendingProcessChanges.clear();
2454 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2455 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002456 int i = mProcessObservers.beginBroadcast();
2457 while (i > 0) {
2458 i--;
2459 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2460 if (observer != null) {
2461 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002462 for (int j=0; j<N; j++) {
2463 ProcessChangeItem item = mActiveProcessChanges[j];
2464 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2465 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2466 + item.pid + " uid=" + item.uid + ": "
2467 + item.foregroundActivities);
2468 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2469 item.foregroundActivities);
2470 }
2471 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2472 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2473 + item.pid + " uid=" + item.uid + ": " + item.importance);
2474 observer.onImportanceChanged(item.pid, item.uid,
2475 item.importance);
2476 }
2477 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002478 } catch (RemoteException e) {
2479 }
2480 }
2481 }
2482 mProcessObservers.finishBroadcast();
2483 }
2484
2485 private void dispatchProcessDied(int pid, int uid) {
2486 int i = mProcessObservers.beginBroadcast();
2487 while (i > 0) {
2488 i--;
2489 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2490 if (observer != null) {
2491 try {
2492 observer.onProcessDied(pid, uid);
2493 } catch (RemoteException e) {
2494 }
2495 }
2496 }
2497 mProcessObservers.finishBroadcast();
2498 }
2499
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002501 final int N = mPendingActivityLaunches.size();
2502 if (N <= 0) {
2503 return;
2504 }
2505 for (int i=0; i<N; i++) {
2506 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002507 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002508 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002509 }
2510 mPendingActivityLaunches.clear();
2511 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002512
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002513 public final int startActivity(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002514 Intent intent, String resolvedType, IBinder resultTo,
2515 String resultWho, int requestCode, int startFlags,
2516 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002517 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
2518 resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002519 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002520 }
2521
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002522 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Amith Yamasani82644082012-08-03 13:09:11 -07002523 Intent intent, String resolvedType, IBinder resultTo,
2524 String resultWho, int requestCode, int startFlags,
2525 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002526 enforceNotIsolatedCaller("startActivity");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002527 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackbornd8883992012-09-07 15:58:52 -07002528 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002529 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2531 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002532 }
2533
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002534 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002535 Intent intent, String resolvedType, IBinder resultTo,
2536 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002537 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002538 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002539 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002540 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002541 WaitResult res = new WaitResult();
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002542 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002543 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002544 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002545 return res;
2546 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002547
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002548 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 Intent intent, String resolvedType, IBinder resultTo,
2550 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002551 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002552 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn139748f2012-09-24 11:36:57 -07002553 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002554 false, true, "startActivityWithConfig", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002555 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002556 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002557 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002558 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002559 }
2560
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002561 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002562 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002563 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002565 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002566 // Refuse possible leaked file descriptors
2567 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2568 throw new IllegalArgumentException("File descriptors passed in Intent");
2569 }
2570
2571 IIntentSender sender = intent.getTarget();
2572 if (!(sender instanceof PendingIntentRecord)) {
2573 throw new IllegalArgumentException("Bad PendingIntent object");
2574 }
2575
2576 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002577
2578 synchronized (this) {
2579 // If this is coming from the currently resumed activity, it is
2580 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 if (mMainStack.mResumedActivity != null
2582 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002583 Binder.getCallingUid()) {
2584 mAppSwitchesAllowedTime = 0;
2585 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002586 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002587 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2588 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002589 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002590 }
2591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002593 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 // Refuse possible leaked file descriptors
2595 if (intent != null && intent.hasFileDescriptors() == true) {
2596 throw new IllegalArgumentException("File descriptors passed in Intent");
2597 }
2598
2599 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002600 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2601 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002602 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 return false;
2604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 if (r.app == null || r.app.thread == null) {
2606 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002607 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 return false;
2609 }
2610 intent = new Intent(intent);
2611 // The caller is not allowed to change the data.
2612 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2613 // And we are resetting to find the next component...
2614 intent.setComponent(null);
2615
2616 ActivityInfo aInfo = null;
2617 try {
2618 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002619 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002621 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002622 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623
2624 // Look for the original activity in the list...
2625 final int N = resolves != null ? resolves.size() : 0;
2626 for (int i=0; i<N; i++) {
2627 ResolveInfo rInfo = resolves.get(i);
2628 if (rInfo.activityInfo.packageName.equals(r.packageName)
2629 && rInfo.activityInfo.name.equals(r.info.name)) {
2630 // We found the current one... the next matching is
2631 // after it.
2632 i++;
2633 if (i<N) {
2634 aInfo = resolves.get(i).activityInfo;
2635 }
2636 break;
2637 }
2638 }
2639 } catch (RemoteException e) {
2640 }
2641
2642 if (aInfo == null) {
2643 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002644 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 return false;
2646 }
2647
2648 intent.setComponent(new ComponentName(
2649 aInfo.applicationInfo.packageName, aInfo.name));
2650 intent.setFlags(intent.getFlags()&~(
2651 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2652 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2653 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2654 Intent.FLAG_ACTIVITY_NEW_TASK));
2655
2656 // Okay now we need to start the new activity, replacing the
2657 // currently running activity. This is a little tricky because
2658 // we want to start the new one as if the current one is finished,
2659 // but not finish the current one first so that there is no flicker.
2660 // And thus...
2661 final boolean wasFinishing = r.finishing;
2662 r.finishing = true;
2663
2664 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002665 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 final String resultWho = r.resultWho;
2667 final int requestCode = r.requestCode;
2668 r.resultTo = null;
2669 if (resultTo != null) {
2670 resultTo.removeResultsLocked(r, resultWho, requestCode);
2671 }
2672
2673 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002674 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002675 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002676 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002677 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002678 Binder.restoreCallingIdentity(origId);
2679
2680 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002681 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 return false;
2683 }
2684 return true;
2685 }
2686 }
2687
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002688 final int startActivityInPackage(int uid, String callingPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002690 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2691
Dianne Hackborn139748f2012-09-24 11:36:57 -07002692 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002693 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002695 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002696 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002697 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002698 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002699 }
2700
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002701 public final int startActivities(IApplicationThread caller, String callingPackage,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002702 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options,
2703 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002704 enforceNotIsolatedCaller("startActivities");
Amith Yamasani16979ea2012-09-24 18:14:47 -07002705 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Amith Yamasaniea7e9152012-09-24 16:11:18 -07002706 false, true, "startActivity", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002707 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents,
2708 resolvedTypes, resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002709 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002710 }
2711
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002712 final int startActivitiesInPackage(int uid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002713 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002714 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002715
Dianne Hackborn139748f2012-09-24 11:36:57 -07002716 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Dianne Hackborn41203752012-08-31 14:05:51 -07002717 false, true, "startActivityInPackage", null);
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002718 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes,
2719 resultTo, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002720 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002721 }
2722
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002723 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002725 // Quick case: check if the top-most recent task is the same.
2726 if (N > 0 && mRecentTasks.get(0) == task) {
2727 return;
2728 }
2729 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 for (int i=0; i<N; i++) {
2731 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002732 if (task.userId == tr.userId
2733 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2734 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 mRecentTasks.remove(i);
2736 i--;
2737 N--;
2738 if (task.intent == null) {
2739 // If the new recent task we are adding is not fully
2740 // specified, then replace it with the existing recent task.
2741 task = tr;
2742 }
2743 }
2744 }
2745 if (N >= MAX_RECENT_TASKS) {
2746 mRecentTasks.remove(N-1);
2747 }
2748 mRecentTasks.add(0, task);
2749 }
2750
2751 public void setRequestedOrientation(IBinder token,
2752 int requestedOrientation) {
2753 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002754 ActivityRecord r = mMainStack.isInStackLocked(token);
2755 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002756 return;
2757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002759 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002761 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002762 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 if (config != null) {
2764 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002765 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002766 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 }
2768 }
2769 Binder.restoreCallingIdentity(origId);
2770 }
2771 }
2772
2773 public int getRequestedOrientation(IBinder token) {
2774 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002775 ActivityRecord r = mMainStack.isInStackLocked(token);
2776 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2778 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002779 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 }
2781 }
2782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002783 /**
2784 * This is the internal entry point for handling Activity.finish().
2785 *
2786 * @param token The Binder token referencing the Activity we want to finish.
2787 * @param resultCode Result code, if any, from this Activity.
2788 * @param resultData Result data (Intent), if any, from this Activity.
2789 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002790 * @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 -08002791 */
2792 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2793 // Refuse possible leaked file descriptors
2794 if (resultData != null && resultData.hasFileDescriptors() == true) {
2795 throw new IllegalArgumentException("File descriptors passed in Intent");
2796 }
2797
2798 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002799 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002801 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 if (next != null) {
2803 // ask watcher if this is allowed
2804 boolean resumeOK = true;
2805 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002806 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002808 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 }
2810
2811 if (!resumeOK) {
2812 return false;
2813 }
2814 }
2815 }
2816 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002817 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002818 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 Binder.restoreCallingIdentity(origId);
2820 return res;
2821 }
2822 }
2823
Dianne Hackborn860755f2010-06-03 18:47:52 -07002824 public final void finishHeavyWeightApp() {
2825 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2826 != PackageManager.PERMISSION_GRANTED) {
2827 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2828 + Binder.getCallingPid()
2829 + ", uid=" + Binder.getCallingUid()
2830 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2831 Slog.w(TAG, msg);
2832 throw new SecurityException(msg);
2833 }
2834
2835 synchronized(this) {
2836 if (mHeavyWeightProcess == null) {
2837 return;
2838 }
2839
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002840 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002841 mHeavyWeightProcess.activities);
2842 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002843 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002844 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002845 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002846 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002848 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002849 }
2850 }
2851 }
2852
Dianne Hackborn41203752012-08-31 14:05:51 -07002853 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2854 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002855 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002856 }
2857 }
2858
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002859 public void crashApplication(int uid, int initialPid, String packageName,
2860 String message) {
2861 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2862 != PackageManager.PERMISSION_GRANTED) {
2863 String msg = "Permission Denial: crashApplication() from pid="
2864 + Binder.getCallingPid()
2865 + ", uid=" + Binder.getCallingUid()
2866 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2867 Slog.w(TAG, msg);
2868 throw new SecurityException(msg);
2869 }
2870
2871 synchronized(this) {
2872 ProcessRecord proc = null;
2873
2874 // Figure out which process to kill. We don't trust that initialPid
2875 // still has any relation to current pids, so must scan through the
2876 // list.
2877 synchronized (mPidsSelfLocked) {
2878 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2879 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002880 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002881 continue;
2882 }
2883 if (p.pid == initialPid) {
2884 proc = p;
2885 break;
2886 }
2887 for (String str : p.pkgList) {
2888 if (str.equals(packageName)) {
2889 proc = p;
2890 }
2891 }
2892 }
2893 }
2894
2895 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002896 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002897 + " initialPid=" + initialPid
2898 + " packageName=" + packageName);
2899 return;
2900 }
2901
2902 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002903 if (proc.pid == Process.myPid()) {
2904 Log.w(TAG, "crashApplication: trying to crash self!");
2905 return;
2906 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002907 long ident = Binder.clearCallingIdentity();
2908 try {
2909 proc.thread.scheduleCrash(message);
2910 } catch (RemoteException e) {
2911 }
2912 Binder.restoreCallingIdentity(ident);
2913 }
2914 }
2915 }
2916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 public final void finishSubActivity(IBinder token, String resultWho,
2918 int requestCode) {
2919 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002921 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 Binder.restoreCallingIdentity(origId);
2923 }
2924 }
2925
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002926 public boolean finishActivityAffinity(IBinder token) {
2927 synchronized(this) {
2928 final long origId = Binder.clearCallingIdentity();
2929 boolean res = mMainStack.finishActivityAffinityLocked(token);
2930 Binder.restoreCallingIdentity(origId);
2931 return res;
2932 }
2933 }
2934
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002935 public boolean willActivityBeVisible(IBinder token) {
2936 synchronized(this) {
2937 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002938 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2939 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002940 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002941 return true;
2942 }
2943 if (r.fullscreen && !r.finishing) {
2944 return false;
2945 }
2946 }
2947 return true;
2948 }
2949 }
2950
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002951 public void overridePendingTransition(IBinder token, String packageName,
2952 int enterAnim, int exitAnim) {
2953 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002954 ActivityRecord self = mMainStack.isInStackLocked(token);
2955 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002956 return;
2957 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002958
2959 final long origId = Binder.clearCallingIdentity();
2960
2961 if (self.state == ActivityState.RESUMED
2962 || self.state == ActivityState.PAUSING) {
2963 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002964 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002965 }
2966
2967 Binder.restoreCallingIdentity(origId);
2968 }
2969 }
2970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002972 * Main function for removing an existing process from the activity manager
2973 * as a result of that process going away. Clears out all connections
2974 * to the process.
2975 */
2976 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002977 boolean restarting, boolean allowRestart) {
2978 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002980 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 }
2982
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002983 if (mProfileProc == app) {
2984 clearProfilerLocked();
2985 }
2986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002988 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002989 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG,
2990 "App died while pausing: " + mMainStack.mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002991 mMainStack.mPausingActivity = null;
2992 }
2993 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2994 mMainStack.mLastPausedActivity = null;
2995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996
2997 // Remove this application's activities from active lists.
Dianne Hackborncc5a0552012-10-01 16:32:39 -07002998 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999
3000 app.activities.clear();
3001
3002 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003003 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 + " running instrumentation " + app.instrumentationClass);
3005 Bundle info = new Bundle();
3006 info.putString("shortMsg", "Process crashed.");
3007 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
3008 }
3009
3010 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003011 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 // If there was nothing to resume, and we are not already
3013 // restarting this process, but there is a visible activity that
3014 // is hosted by the process... then make sure all visible
3015 // activities are running, taking care of restarting this
3016 // process.
3017 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003018 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 }
3020 }
3021 }
3022 }
3023
3024 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
3025 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003027 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3028 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
3030 return i;
3031 }
3032 }
3033 return -1;
3034 }
3035
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003036 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 IApplicationThread thread) {
3038 if (thread == null) {
3039 return null;
3040 }
3041
3042 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003043 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003046 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 IApplicationThread thread) {
3048
3049 mProcDeaths[0]++;
3050
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07003051 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
3052 synchronized (stats) {
3053 stats.noteProcessDiedLocked(app.info.uid, pid);
3054 }
3055
Magnus Edlund7bb25812010-02-24 15:45:06 +01003056 // Clean up already done if the process has been re-started.
3057 if (app.pid == pid && app.thread != null &&
3058 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07003059 if (!app.killedBackground) {
3060 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
3061 + ") has died.");
3062 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003063 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003064 if (DEBUG_CLEANUP) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 TAG, "Dying app: " + app + ", pid: " + pid
3066 + ", thread: " + thread.asBinder());
3067 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003068 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069
3070 if (doLowMem) {
3071 // If there are no longer any background processes running,
3072 // and the app that died was not running instrumentation,
3073 // then tell everyone we are now low on memory.
3074 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003075 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3076 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003077 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 haveBg = true;
3079 break;
3080 }
3081 }
3082
3083 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003084 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003085 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003086 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3087 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003088 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003089 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3090 // The low memory report is overriding any current
3091 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003092 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003093 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003094 rec.lastRequestedGc = 0;
3095 } else {
3096 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003098 rec.reportLowMemory = true;
3099 rec.lastLowMemory = now;
3100 mProcessesToGc.remove(rec);
3101 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
3103 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003104 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003105 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 }
3107 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003108 } else if (app.pid != pid) {
3109 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003110 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003111 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003112 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003113 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003114 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 + thread.asBinder());
3116 }
3117 }
3118
Dan Egnor42471dd2010-01-07 17:25:22 -08003119 /**
3120 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003121 * @param clearTraces causes the dump file to be erased prior to the new
3122 * traces being written, if true; when false, the new traces will be
3123 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003124 * @param firstPids of dalvik VM processes to dump stack traces for first
3125 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003126 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003127 * @return file containing stack traces, or null if no dump file is configured
3128 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003129 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003130 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003131 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3132 if (tracesPath == null || tracesPath.length() == 0) {
3133 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003135
3136 File tracesFile = new File(tracesPath);
3137 try {
3138 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003139 if (!tracesDir.exists()) {
3140 tracesFile.mkdirs();
3141 if (!SELinux.restorecon(tracesDir)) {
3142 return null;
3143 }
3144 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003145 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3146
Christopher Tate6ee412d2010-05-28 12:01:56 -07003147 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 tracesFile.createNewFile();
3149 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3150 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003151 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003152 return null;
3153 }
3154
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003155 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003156 return tracesFile;
3157 }
3158
3159 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003160 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003161 // Use a FileObserver to detect when traces finish writing.
3162 // The order of traces is considered important to maintain for legibility.
3163 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3164 public synchronized void onEvent(int event, String path) { notify(); }
3165 };
3166
3167 try {
3168 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003169
3170 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003171 if (firstPids != null) {
3172 try {
3173 int num = firstPids.size();
3174 for (int i = 0; i < num; i++) {
3175 synchronized (observer) {
3176 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3177 observer.wait(200); // Wait for write-close, give up after 200msec
3178 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003179 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003180 } catch (InterruptedException e) {
3181 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003182 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003183 }
3184
3185 // Next measure CPU usage.
3186 if (processStats != null) {
3187 processStats.init();
3188 System.gc();
3189 processStats.update();
3190 try {
3191 synchronized (processStats) {
3192 processStats.wait(500); // measure over 1/2 second.
3193 }
3194 } catch (InterruptedException e) {
3195 }
3196 processStats.update();
3197
3198 // We'll take the stack crawls of just the top apps using CPU.
3199 final int N = processStats.countWorkingStats();
3200 int numProcs = 0;
3201 for (int i=0; i<N && numProcs<5; i++) {
3202 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3203 if (lastPids.indexOfKey(stats.pid) >= 0) {
3204 numProcs++;
3205 try {
3206 synchronized (observer) {
3207 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3208 observer.wait(200); // Wait for write-close, give up after 200msec
3209 }
3210 } catch (InterruptedException e) {
3211 Log.wtf(TAG, e);
3212 }
3213
3214 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 }
3216 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003217
Dan Egnor42471dd2010-01-07 17:25:22 -08003218 } finally {
3219 observer.stopWatching();
3220 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003221
3222 if (nativeProcs != null) {
3223 int[] pids = Process.getPidsForCommands(nativeProcs);
3224 if (pids != null) {
3225 for (int pid : pids) {
3226 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3227 }
3228 }
3229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003232 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003233 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003234 return;
3235 }
3236 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3237 if (tracesPath == null || tracesPath.length() == 0) {
3238 return;
3239 }
3240
3241 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3242 StrictMode.allowThreadDiskWrites();
3243 try {
3244 final File tracesFile = new File(tracesPath);
3245 final File tracesDir = tracesFile.getParentFile();
3246 final File tracesTmp = new File(tracesDir, "__tmp__");
3247 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003248 if (!tracesDir.exists()) {
3249 tracesFile.mkdirs();
3250 if (!SELinux.restorecon(tracesDir.getPath())) {
3251 return;
3252 }
3253 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003254 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3255
3256 if (tracesFile.exists()) {
3257 tracesTmp.delete();
3258 tracesFile.renameTo(tracesTmp);
3259 }
3260 StringBuilder sb = new StringBuilder();
3261 Time tobj = new Time();
3262 tobj.set(System.currentTimeMillis());
3263 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3264 sb.append(": ");
3265 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3266 sb.append(" since ");
3267 sb.append(msg);
3268 FileOutputStream fos = new FileOutputStream(tracesFile);
3269 fos.write(sb.toString().getBytes());
3270 if (app == null) {
3271 fos.write("\n*** No application process!".getBytes());
3272 }
3273 fos.close();
3274 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3275 } catch (IOException e) {
3276 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3277 return;
3278 }
3279
3280 if (app != null) {
3281 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3282 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003283 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003284 }
3285
3286 File lastTracesFile = null;
3287 File curTracesFile = null;
3288 for (int i=9; i>=0; i--) {
3289 String name = String.format("slow%02d.txt", i);
3290 curTracesFile = new File(tracesDir, name);
3291 if (curTracesFile.exists()) {
3292 if (lastTracesFile != null) {
3293 curTracesFile.renameTo(lastTracesFile);
3294 } else {
3295 curTracesFile.delete();
3296 }
3297 }
3298 lastTracesFile = curTracesFile;
3299 }
3300 tracesFile.renameTo(curTracesFile);
3301 if (tracesTmp.exists()) {
3302 tracesTmp.renameTo(tracesFile);
3303 }
3304 } finally {
3305 StrictMode.setThreadPolicy(oldPolicy);
3306 }
3307 }
3308
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003309 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003310 ActivityRecord parent, boolean aboveSystem, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003311 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3312 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3313
Dianne Hackborn287952c2010-09-22 22:34:31 -07003314 if (mController != null) {
3315 try {
3316 // 0 == continue, -1 = kill process immediately
3317 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3318 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3319 } catch (RemoteException e) {
3320 mController = null;
3321 }
3322 }
3323
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003324 long anrTime = SystemClock.uptimeMillis();
3325 if (MONITOR_CPU_USAGE) {
3326 updateCpuStatsNow();
3327 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003328
3329 synchronized (this) {
3330 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3331 if (mShuttingDown) {
3332 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3333 return;
3334 } else if (app.notResponding) {
3335 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3336 return;
3337 } else if (app.crashing) {
3338 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3339 return;
3340 }
3341
3342 // In case we come through here for the same app before completing
3343 // this one, mark as anring now so we will bail out.
3344 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003345
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003346 // Log the ANR to the event log.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003347 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
3348 app.processName, app.info.flags, annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003349
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003350 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003351 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003352
3353 int parentPid = app.pid;
3354 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003355 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003356
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003357 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003358
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003359 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3360 ProcessRecord r = mLruProcesses.get(i);
3361 if (r != null && r.thread != null) {
3362 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003363 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3364 if (r.persistent) {
3365 firstPids.add(pid);
3366 } else {
3367 lastPids.put(pid, Boolean.TRUE);
3368 }
3369 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 }
3372 }
3373
Dan Egnor42471dd2010-01-07 17:25:22 -08003374 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003375 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003376 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003377 info.append("ANR in ").append(app.processName);
3378 if (activity != null && activity.shortComponentName != null) {
3379 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003380 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003381 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003383 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003385 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003386 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388
Dianne Hackborn287952c2010-09-22 22:34:31 -07003389 final ProcessStats processStats = new ProcessStats(true);
3390
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003391 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003392
Dan Egnor42471dd2010-01-07 17:25:22 -08003393 String cpuInfo = null;
3394 if (MONITOR_CPU_USAGE) {
3395 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003396 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003397 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003398 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003399 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003400 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 }
3402
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003403 info.append(processStats.printCurrentState(anrTime));
3404
Joe Onorato8a9b2202010-02-26 18:56:32 -08003405 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003406 if (tracesFile == null) {
3407 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3408 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3409 }
3410
Jeff Sharkeya353d262011-10-28 11:12:06 -07003411 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3412 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003413
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003414 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003416 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3417 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003419 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3420 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003421 }
3422 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003423 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
3425 }
3426
Dan Egnor42471dd2010-01-07 17:25:22 -08003427 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3428 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3429 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003430
3431 synchronized (this) {
3432 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003433 Slog.w(TAG, "Killing " + app + ": background ANR");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003434 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003435 app.processName, app.setAdj, "background ANR");
3436 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003437 return;
3438 }
3439
3440 // Set the app's notResponding state, and look up the errorReportReceiver
3441 makeAppNotRespondingLocked(app,
3442 activity != null ? activity.shortComponentName : null,
3443 annotation != null ? "ANR " + annotation : "ANR",
3444 info.toString());
3445
3446 // Bring up the infamous App Not Responding dialog
3447 Message msg = Message.obtain();
3448 HashMap map = new HashMap();
3449 msg.what = SHOW_NOT_RESPONDING_MSG;
3450 msg.obj = map;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07003451 msg.arg1 = aboveSystem ? 1 : 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003452 map.put("app", app);
3453 if (activity != null) {
3454 map.put("activity", activity);
3455 }
3456
3457 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003459 }
3460
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003461 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3462 if (!mLaunchWarningShown) {
3463 mLaunchWarningShown = true;
3464 mHandler.post(new Runnable() {
3465 @Override
3466 public void run() {
3467 synchronized (ActivityManagerService.this) {
3468 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3469 d.show();
3470 mHandler.postDelayed(new Runnable() {
3471 @Override
3472 public void run() {
3473 synchronized (ActivityManagerService.this) {
3474 d.dismiss();
3475 mLaunchWarningShown = false;
3476 }
3477 }
3478 }, 4000);
3479 }
3480 }
3481 });
3482 }
3483 }
3484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003486 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003487 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 int uid = Binder.getCallingUid();
3489 int pid = Binder.getCallingPid();
Dianne Hackborn139748f2012-09-24 11:36:57 -07003490 userId = handleIncomingUser(pid, uid,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003491 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 long callingId = Binder.clearCallingIdentity();
3493 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003494 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003495 int pkgUid = -1;
3496 synchronized(this) {
3497 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003498 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 } catch (RemoteException e) {
3500 }
3501 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003502 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 return false;
3504 }
3505 if (uid == pkgUid || checkComponentPermission(
3506 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003507 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003509 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 } else {
3511 throw new SecurityException(pid+" does not have permission:"+
3512 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3513 "for process:"+packageName);
3514 }
3515 }
3516
3517 try {
3518 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003519 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3521 Uri.fromParts("package", packageName, null));
3522 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003523 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003524 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 } catch (RemoteException e) {
3526 }
3527 } finally {
3528 Binder.restoreCallingIdentity(callingId);
3529 }
3530 return true;
3531 }
3532
Dianne Hackborn1676c852012-09-10 14:52:30 -07003533 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003534 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3535 != PackageManager.PERMISSION_GRANTED &&
3536 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3537 != PackageManager.PERMISSION_GRANTED) {
3538 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 + Binder.getCallingPid()
3540 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003541 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003542 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 throw new SecurityException(msg);
3544 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003545
Dianne Hackborn139748f2012-09-24 11:36:57 -07003546 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003547 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 long callingId = Binder.clearCallingIdentity();
3549 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003550 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003552 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003554 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 } catch (RemoteException e) {
3556 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003557 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003558 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 return;
3560 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003561 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003562 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3563 }
3564 } finally {
3565 Binder.restoreCallingIdentity(callingId);
3566 }
3567 }
3568
3569 public void killAllBackgroundProcesses() {
3570 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3571 != PackageManager.PERMISSION_GRANTED) {
3572 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3573 + Binder.getCallingPid()
3574 + ", uid=" + Binder.getCallingUid()
3575 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3576 Slog.w(TAG, msg);
3577 throw new SecurityException(msg);
3578 }
3579
3580 long callingId = Binder.clearCallingIdentity();
3581 try {
3582 synchronized(this) {
3583 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3584 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3585 final int NA = apps.size();
3586 for (int ia=0; ia<NA; ia++) {
3587 ProcessRecord app = apps.valueAt(ia);
3588 if (app.persistent) {
3589 // we don't kill persistent processes
3590 continue;
3591 }
3592 if (app.removed) {
3593 procs.add(app);
3594 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3595 app.removed = true;
3596 procs.add(app);
3597 }
3598 }
3599 }
3600
3601 int N = procs.size();
3602 for (int i=0; i<N; i++) {
3603 removeProcessLocked(procs.get(i), false, true, "kill all background");
3604 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003605 }
3606 } finally {
3607 Binder.restoreCallingIdentity(callingId);
3608 }
3609 }
3610
Dianne Hackborn1676c852012-09-10 14:52:30 -07003611 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003612 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3613 != PackageManager.PERMISSION_GRANTED) {
3614 String msg = "Permission Denial: forceStopPackage() from pid="
3615 + Binder.getCallingPid()
3616 + ", uid=" + Binder.getCallingUid()
3617 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003618 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003619 throw new SecurityException(msg);
3620 }
Dianne Hackborn139748f2012-09-24 11:36:57 -07003621 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -07003622 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003623 long callingId = Binder.clearCallingIdentity();
3624 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003625 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003626 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003627 int[] users = userId == UserHandle.USER_ALL
3628 ? getUsersLocked() : new int[] { userId };
3629 for (int user : users) {
3630 int pkgUid = -1;
3631 try {
3632 pkgUid = pm.getPackageUid(packageName, user);
3633 } catch (RemoteException e) {
3634 }
3635 if (pkgUid == -1) {
3636 Slog.w(TAG, "Invalid packageName: " + packageName);
3637 continue;
3638 }
3639 try {
3640 pm.setPackageStoppedState(packageName, true, user);
3641 } catch (RemoteException e) {
3642 } catch (IllegalArgumentException e) {
3643 Slog.w(TAG, "Failed trying to unstop package "
3644 + packageName + ": " + e);
3645 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07003646 if (isUserRunningLocked(user, false)) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003647 forceStopPackageLocked(packageName, pkgUid);
3648 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 }
3651 } finally {
3652 Binder.restoreCallingIdentity(callingId);
3653 }
3654 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003655
3656 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003657 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003658 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003659 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003660 if (pkg == null) {
3661 return;
3662 }
3663 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003664 if (appid < 0) {
3665 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003666 return;
3667 }
3668 int callerUid = Binder.getCallingUid();
3669 // Only the system server can kill an application
3670 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003671 // Post an aysnc message to kill the application
3672 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003673 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003674 msg.arg2 = 0;
3675 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003676 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003677 } else {
3678 throw new SecurityException(callerUid + " cannot kill pkg: " +
3679 pkg);
3680 }
3681 }
3682
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003683 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003684 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003685
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003686 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003687 final int uid = Binder.getCallingUid();
3688 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003689 try {
3690 synchronized (this) {
3691 // Only allow this from foreground processes, so that background
3692 // applications can't abuse it to prevent system UI from being shown.
3693 if (uid >= Process.FIRST_APPLICATION_UID) {
3694 ProcessRecord proc;
3695 synchronized (mPidsSelfLocked) {
3696 proc = mPidsSelfLocked.get(pid);
3697 }
3698 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3699 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3700 + " from background process " + proc);
3701 return;
3702 }
3703 }
3704 closeSystemDialogsLocked(reason);
3705 }
3706 } finally {
3707 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003708 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003709 }
3710
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003711 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003712 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003713 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3714 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003715 if (reason != null) {
3716 intent.putExtra("reason", reason);
3717 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003718 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003719
Dianne Hackborne302a162012-05-15 14:58:32 -07003720 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3721 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003722 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003723 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003724 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003725 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003726 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003727
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003728 broadcastIntentLocked(null, null, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003729 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1,
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003730 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003731 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003732
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003733 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003734 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003735 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003736 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3737 for (int i=pids.length-1; i>=0; i--) {
3738 infos[i] = new Debug.MemoryInfo();
3739 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003740 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003741 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003742 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003743
Dianne Hackbornb437e092011-08-05 17:50:29 -07003744 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003745 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003746 long[] pss = new long[pids.length];
3747 for (int i=pids.length-1; i>=0; i--) {
3748 pss[i] = Debug.getPss(pids[i]);
3749 }
3750 return pss;
3751 }
3752
Christopher Tate5e1ab332009-09-01 20:32:49 -07003753 public void killApplicationProcess(String processName, int uid) {
3754 if (processName == null) {
3755 return;
3756 }
3757
3758 int callerUid = Binder.getCallingUid();
3759 // Only the system server can kill an application
3760 if (callerUid == Process.SYSTEM_UID) {
3761 synchronized (this) {
3762 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003763 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003764 try {
3765 app.thread.scheduleSuicide();
3766 } catch (RemoteException e) {
3767 // If the other end already died, then our work here is done.
3768 }
3769 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003770 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003771 + processName + " / " + uid);
3772 }
3773 }
3774 } else {
3775 throw new SecurityException(callerUid + " cannot kill app process: " +
3776 processName);
3777 }
3778 }
3779
Dianne Hackborn03abb812010-01-04 18:43:19 -08003780 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003781 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3782 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3784 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003785 if (!mProcessesReady) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07003786 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3787 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 intent.putExtra(Intent.EXTRA_UID, uid);
Dianne Hackbornc72fc672012-09-20 13:12:03 -07003790 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003792 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Amith Yamasani742a6712011-05-04 14:49:28 -07003793 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003794 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003796
3797 private void forceStopUserLocked(int userId) {
3798 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3799 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07003800 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
3801 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003802 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3803 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08003804 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003805 false, false,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07003806 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003807 }
3808
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003809 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003810 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3811 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003812 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813
Dianne Hackborn03abb812010-01-04 18:43:19 -08003814 // Remove all processes this package may have touched: all with the
3815 // same UID (except for the system or root user), and all whose name
3816 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003817 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003818 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3819 final int NA = apps.size();
3820 for (int ia=0; ia<NA; ia++) {
3821 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003822 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003823 // we don't kill persistent processes
3824 continue;
3825 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003826 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003827 if (doit) {
3828 procs.add(app);
3829 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003830 continue;
3831 }
3832
3833 // Skip process if it doesn't meet our oom adj requirement.
3834 if (app.setAdj < minOomAdj) {
3835 continue;
3836 }
3837
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003838 // If no package is specified, we call all processes under the
3839 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003840 if (packageName == null) {
3841 if (app.userId != userId) {
3842 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003843 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003844 // Package has been specified, we want to hit all processes
3845 // that match it. We need to qualify this by the processes
3846 // that are running under the specified app and user ID.
3847 } else {
3848 if (UserHandle.getAppId(app.uid) != appId) {
3849 continue;
3850 }
3851 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3852 continue;
3853 }
3854 if (!app.pkgList.contains(packageName)) {
3855 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003856 }
3857 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003858
3859 // Process has passed all conditions, kill it!
3860 if (!doit) {
3861 return true;
3862 }
3863 app.removed = true;
3864 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003865 }
3866 }
3867
3868 int N = procs.size();
3869 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003870 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003871 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003872 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003873 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003874
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003875 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003876 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003877 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003878 int i;
3879 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003881 if (userId == UserHandle.USER_ALL && name == null) {
3882 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3883 }
3884
3885 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003887 appId = UserHandle.getAppId(
3888 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 } catch (RemoteException e) {
3890 }
3891 }
3892
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003893 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003894 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003895 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3896 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003897 } else {
3898 Slog.i(TAG, "Force stopping user " + userId);
3899 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003900
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003901 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3902 while (badApps.hasNext()) {
3903 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003904 for (i=ba.size()-1; i>=0; i--) {
3905 boolean remove = false;
3906 final int entUid = ba.keyAt(i);
3907 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003908 if (userId == UserHandle.USER_ALL) {
3909 if (UserHandle.getAppId(entUid) == appId) {
3910 remove = true;
3911 }
3912 } else {
3913 if (entUid == UserHandle.getUid(userId, appId)) {
3914 remove = true;
3915 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003916 }
3917 } else if (UserHandle.getUserId(entUid) == userId) {
3918 remove = true;
3919 }
3920 if (remove) {
3921 ba.removeAt(i);
3922 }
3923 }
3924 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003925 badApps.remove();
3926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003929
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003930 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
Dianne Hackborne62fa822013-01-09 18:31:37 -08003931 -100, callerWillRestart, true, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003932 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003934 TaskRecord lastTask = null;
3935 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003936 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003937 final boolean samePackage = r.packageName.equals(name)
3938 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003939 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003940 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003941 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003942 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003943 if (r.finishing) {
3944 // If this activity is just finishing, then it is not
3945 // interesting as far as something to stop.
3946 continue;
3947 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003948 return true;
3949 }
3950 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003951 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003952 if (samePackage) {
3953 if (r.app != null) {
3954 r.app.removed = true;
3955 }
3956 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003958 lastTask = r.task;
3959 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003960 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003961 i--;
3962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
3964 }
3965
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003966 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3967 if (!doit) {
3968 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003970 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003972
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003973 if (name == null) {
3974 // Remove all sticky broadcasts from this user.
3975 mStickyBroadcasts.remove(userId);
3976 }
3977
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003978 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003979 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3980 userId, providers)) {
3981 if (!doit) {
3982 return true;
3983 }
3984 didSomething = true;
3985 }
3986 N = providers.size();
3987 for (i=0; i<N; i++) {
3988 removeDyingProviderLocked(null, providers.get(i), true);
3989 }
3990
Dianne Hackborn861a3b22012-10-12 15:25:20 -07003991 if (name == null) {
3992 // Remove pending intents. For now we only do this when force
3993 // stopping users, because we have some problems when doing this
3994 // for packages -- app widgets are not currently cleaned up for
3995 // such packages, so they can be left with bad pending intents.
3996 if (mIntentSenderRecords.size() > 0) {
3997 Iterator<WeakReference<PendingIntentRecord>> it
3998 = mIntentSenderRecords.values().iterator();
3999 while (it.hasNext()) {
4000 WeakReference<PendingIntentRecord> wpir = it.next();
4001 if (wpir == null) {
4002 it.remove();
4003 continue;
4004 }
4005 PendingIntentRecord pir = wpir.get();
4006 if (pir == null) {
4007 it.remove();
4008 continue;
4009 }
4010 if (name == null) {
4011 // Stopping user, remove all objects for the user.
4012 if (pir.key.userId != userId) {
4013 // Not the same user, skip it.
4014 continue;
4015 }
4016 } else {
4017 if (UserHandle.getAppId(pir.uid) != appId) {
4018 // Different app id, skip it.
4019 continue;
4020 }
4021 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
4022 // Different user, skip it.
4023 continue;
4024 }
4025 if (!pir.key.packageName.equals(name)) {
4026 // Different package, skip it.
4027 continue;
4028 }
4029 }
4030 if (!doit) {
4031 return true;
4032 }
4033 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004034 it.remove();
Dianne Hackborn861a3b22012-10-12 15:25:20 -07004035 pir.canceled = true;
4036 if (pir.key.activity != null) {
4037 pir.key.activity.pendingResults.remove(pir.ref);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004038 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07004039 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07004040 }
4041 }
4042
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004043 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004044 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004045 AttributeCache ac = AttributeCache.instance();
4046 if (ac != null) {
4047 ac.removePackage(name);
4048 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004049 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07004050 if (mBooted) {
4051 mMainStack.resumeTopActivityLocked(null);
4052 mMainStack.scheduleIdleLocked();
4053 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004054 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004055
4056 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 }
4058
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004059 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004060 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004062 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004063 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004064 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 + "/" + uid + ")");
4066
4067 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004068 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004069 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004070 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4071 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004072 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 boolean needRestart = false;
4075 if (app.pid > 0 && app.pid != MY_PID) {
4076 int pid = app.pid;
4077 synchronized (mPidsSelfLocked) {
4078 mPidsSelfLocked.remove(pid);
4079 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4080 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004081 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004082 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004083 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004084 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004086 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004088 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 } else {
4090 needRestart = true;
4091 }
4092 }
4093 } else {
4094 mRemovedProcesses.add(app);
4095 }
4096
4097 return needRestart;
4098 }
4099
4100 private final void processStartTimedOutLocked(ProcessRecord app) {
4101 final int pid = app.pid;
4102 boolean gone = false;
4103 synchronized (mPidsSelfLocked) {
4104 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4105 if (knownApp != null && knownApp.thread == null) {
4106 mPidsSelfLocked.remove(pid);
4107 gone = true;
4108 }
4109 }
4110
4111 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004112 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004113 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId,
4114 pid, app.uid, app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004115 mProcessNames.remove(app.processName, app.uid);
4116 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004117 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004118 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4119 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004120 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004121 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004122 // Take care of any launching providers waiting for this process.
4123 checkAppInLaunchingProvidersLocked(app, true);
4124 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004125 mServices.processStartTimedOutLocked(app);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004126 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004127 app.processName, app.setAdj, "start timeout");
4128 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004129 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004131 try {
4132 IBackupManager bm = IBackupManager.Stub.asInterface(
4133 ServiceManager.getService(Context.BACKUP_SERVICE));
4134 bm.agentDisconnected(app.info.packageName);
4135 } catch (RemoteException e) {
4136 // Can't happen; the backup manager is local
4137 }
4138 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004139 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004140 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004141 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004144 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
4146 }
4147
4148 private final boolean attachApplicationLocked(IApplicationThread thread,
4149 int pid) {
4150
4151 // Find the application record that is being attached... either via
4152 // the pid if we are running in multiple processes, or just pull the
4153 // next app record if we are emulating process with anonymous threads.
4154 ProcessRecord app;
4155 if (pid != MY_PID && pid >= 0) {
4156 synchronized (mPidsSelfLocked) {
4157 app = mPidsSelfLocked.get(pid);
4158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 } else {
4160 app = null;
4161 }
4162
4163 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004164 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004165 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004166 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004168 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 } else {
4170 try {
4171 thread.scheduleExit();
4172 } catch (Exception e) {
4173 // Ignore exceptions.
4174 }
4175 }
4176 return false;
4177 }
4178
4179 // If this application record is still attached to a previous
4180 // process, clean it up now.
4181 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004182 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 }
4184
4185 // Tell the process all about itself.
4186
Joe Onorato8a9b2202010-02-26 18:56:32 -08004187 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 TAG, "Binding process pid " + pid + " to record " + app);
4189
4190 String processName = app.processName;
4191 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004192 AppDeathRecipient adr = new AppDeathRecipient(
4193 app, pid, thread);
4194 thread.asBinder().linkToDeath(adr, 0);
4195 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 } catch (RemoteException e) {
4197 app.resetPackageList();
4198 startProcessLocked(app, "link fail", processName);
4199 return false;
4200 }
4201
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004202 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203
4204 app.thread = thread;
4205 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004206 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4207 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 app.forcingToForeground = null;
4209 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004210 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 app.debugging = false;
4212
4213 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4214
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004215 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004216 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004218 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004219 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004220 }
4221
Joe Onorato8a9b2202010-02-26 18:56:32 -08004222 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 TAG, "New app record " + app
4224 + " thread=" + thread.asBinder() + " pid=" + pid);
4225 try {
4226 int testMode = IApplicationThread.DEBUG_OFF;
4227 if (mDebugApp != null && mDebugApp.equals(processName)) {
4228 testMode = mWaitForDebugger
4229 ? IApplicationThread.DEBUG_WAIT
4230 : IApplicationThread.DEBUG_ON;
4231 app.debugging = true;
4232 if (mDebugTransient) {
4233 mDebugApp = mOrigDebugApp;
4234 mWaitForDebugger = mOrigWaitForDebugger;
4235 }
4236 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004237 String profileFile = app.instrumentationProfileFile;
4238 ParcelFileDescriptor profileFd = null;
4239 boolean profileAutoStop = false;
4240 if (mProfileApp != null && mProfileApp.equals(processName)) {
4241 mProfileProc = app;
4242 profileFile = mProfileFile;
4243 profileFd = mProfileFd;
4244 profileAutoStop = mAutoStopProfiler;
4245 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004246 boolean enableOpenGlTrace = false;
4247 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4248 enableOpenGlTrace = true;
4249 mOpenGlTraceApp = null;
4250 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004251
Christopher Tate181fafa2009-05-14 11:12:14 -07004252 // If the app is being launched for restore or full backup, set it up specially
4253 boolean isRestrictedBackupMode = false;
4254 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4255 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004256 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004257 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4258 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004259
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004260 ensurePackageDexOpt(app.instrumentationInfo != null
4261 ? app.instrumentationInfo.packageName
4262 : app.info.packageName);
4263 if (app.instrumentationClass != null) {
4264 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004265 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004266 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004267 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004268 ApplicationInfo appInfo = app.instrumentationInfo != null
4269 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004270 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004271 if (profileFd != null) {
4272 profileFd = profileFd.dup();
4273 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004274 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004275 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Svetoslav Ganov80943d82013-01-02 10:25:37 -08004276 app.instrumentationArguments, app.instrumentationWatcher,
4277 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace,
4278 isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004279 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004280 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004281 updateLruProcessLocked(app, false);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004282 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 } catch (Exception e) {
4284 // todo: Yikes! What should we do? For now we will try to
4285 // start another process, but that could easily get us in
4286 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004287 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288
4289 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004290 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 startProcessLocked(app, "bind fail", processName);
4292 return false;
4293 }
4294
4295 // Remove this record from the list of starting applications.
4296 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004297 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4298 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 mProcessesOnHold.remove(app);
4300
4301 boolean badApp = false;
4302 boolean didSomething = false;
4303
4304 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004305 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004306 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004307 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 && processName.equals(hr.processName)) {
4309 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004310 if (mHeadless) {
4311 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4312 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 didSomething = true;
4314 }
4315 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004316 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 + hr.intent.getComponent().flattenToShortString(), e);
4318 badApp = true;
4319 }
4320 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004321 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 }
4323 }
4324
4325 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004326 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004328 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 badApp = true;
4331 }
4332 }
4333
Christopher Tatef46723b2012-01-26 14:19:24 -08004334 // Check if a next-broadcast receiver is in this process...
4335 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004337 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004339 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004341 }
4342 }
4343
Christopher Tate181fafa2009-05-14 11:12:14 -07004344 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004345 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004346 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004347 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004348 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004349 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4350 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4351 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004352 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004353 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004354 e.printStackTrace();
4355 }
4356 }
4357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 if (badApp) {
4359 // todo: Also need to kill application to deal with all
4360 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004361 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 return false;
4363 }
4364
4365 if (!didSomething) {
4366 updateOomAdjLocked();
4367 }
4368
4369 return true;
4370 }
4371
4372 public final void attachApplication(IApplicationThread thread) {
4373 synchronized (this) {
4374 int callingPid = Binder.getCallingPid();
4375 final long origId = Binder.clearCallingIdentity();
4376 attachApplicationLocked(thread, callingPid);
4377 Binder.restoreCallingIdentity(origId);
4378 }
4379 }
4380
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004381 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004383 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4384 if (stopProfiling) {
4385 synchronized (this) {
4386 if (mProfileProc == r.app) {
4387 if (mProfileFd != null) {
4388 try {
4389 mProfileFd.close();
4390 } catch (IOException e) {
4391 }
4392 clearProfilerLocked();
4393 }
4394 }
4395 }
4396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397 Binder.restoreCallingIdentity(origId);
4398 }
4399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004401 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004402 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004404
4405 synchronized (this) {
4406 updateEventDispatchingLocked();
4407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 }
4409
Dianne Hackborn661cd522011-08-22 00:26:20 -07004410 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004411 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004412 mWindowManager.showBootMessage(msg, always);
4413 }
4414
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004415 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004416 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004417 final long token = Binder.clearCallingIdentity();
4418 try {
4419 synchronized (this) {
4420 if (mLockScreenShown) {
4421 mLockScreenShown = false;
4422 comeOutOfSleepIfNeededLocked();
4423 }
4424 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004425 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004426 } finally {
4427 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004428 }
4429 }
4430
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004431 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004432 IntentFilter pkgFilter = new IntentFilter();
4433 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4434 pkgFilter.addDataScheme("package");
4435 mContext.registerReceiver(new BroadcastReceiver() {
4436 @Override
4437 public void onReceive(Context context, Intent intent) {
4438 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4439 if (pkgs != null) {
4440 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004441 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004442 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4443 setResultCode(Activity.RESULT_OK);
4444 return;
4445 }
4446 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004447 }
4448 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004449 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004450 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004451
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004452 synchronized (this) {
4453 // Ensure that any processes we had put on hold are now started
4454 // up.
4455 final int NP = mProcessesOnHold.size();
4456 if (NP > 0) {
4457 ArrayList<ProcessRecord> procs =
4458 new ArrayList<ProcessRecord>(mProcessesOnHold);
4459 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004460 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4461 + procs.get(ip));
4462 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004463 }
4464 }
4465
4466 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004467 // Start looking for apps that are abusing wake locks.
4468 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004469 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004470 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004471 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004472 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004473 for (int i=0; i<mStartedUsers.size(); i++) {
4474 UserStartedState uss = mStartedUsers.valueAt(i);
4475 if (uss.mState == UserStartedState.STATE_BOOTING) {
4476 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004477 final int userId = mStartedUsers.keyAt(i);
4478 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4479 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4480 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004481 null, null, 0, null, null,
4482 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08004483 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID,
4484 userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004485 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004486 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004487 }
4488 }
4489 }
4490
4491 final void ensureBootCompleted() {
4492 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004493 boolean enableScreen;
4494 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004495 booting = mBooting;
4496 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004497 enableScreen = !mBooted;
4498 mBooted = true;
4499 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004500
4501 if (booting) {
4502 finishBooting();
4503 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004504
4505 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004506 enableScreenAfterBoot();
4507 }
4508 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07004509
4510 public final void activityResumed(IBinder token) {
4511 final long origId = Binder.clearCallingIdentity();
4512 mMainStack.activityResumed(token);
4513 Binder.restoreCallingIdentity(origId);
4514 }
4515
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004516 public final void activityPaused(IBinder token) {
4517 final long origId = Binder.clearCallingIdentity();
4518 mMainStack.activityPaused(token, false);
4519 Binder.restoreCallingIdentity(origId);
4520 }
4521
4522 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4523 CharSequence description) {
4524 if (localLOGV) Slog.v(
4525 TAG, "Activity stopped: token=" + token);
4526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 // Refuse possible leaked file descriptors
4528 if (icicle != null && icicle.hasFileDescriptors()) {
4529 throw new IllegalArgumentException("File descriptors passed in Bundle");
4530 }
4531
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004532 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533
4534 final long origId = Binder.clearCallingIdentity();
4535
4536 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004537 r = mMainStack.isInStackLocked(token);
4538 if (r != null) {
4539 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004540 }
4541 }
4542
4543 if (r != null) {
4544 sendPendingThumbnail(r, null, null, null, false);
4545 }
4546
4547 trimApplications();
4548
4549 Binder.restoreCallingIdentity(origId);
4550 }
4551
4552 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004553 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004554 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004555 }
4556
4557 public String getCallingPackage(IBinder token) {
4558 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004559 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004560 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
4562 }
4563
4564 public ComponentName getCallingActivity(IBinder token) {
4565 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004566 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 return r != null ? r.intent.getComponent() : null;
4568 }
4569 }
4570
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004571 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004572 ActivityRecord r = mMainStack.isInStackLocked(token);
4573 if (r == null) {
4574 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004576 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
4578
4579 public ComponentName getActivityClassForToken(IBinder token) {
4580 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004581 ActivityRecord r = mMainStack.isInStackLocked(token);
4582 if (r == null) {
4583 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004585 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 }
4587 }
4588
4589 public String getPackageForToken(IBinder token) {
4590 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004591 ActivityRecord r = mMainStack.isInStackLocked(token);
4592 if (r == null) {
4593 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004594 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004595 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 }
4597 }
4598
4599 public IIntentSender getIntentSender(int type,
4600 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004601 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004602 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004603 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004605 if (intents != null) {
4606 if (intents.length < 1) {
4607 throw new IllegalArgumentException("Intents array length must be >= 1");
4608 }
4609 for (int i=0; i<intents.length; i++) {
4610 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004611 if (intent != null) {
4612 if (intent.hasFileDescriptors()) {
4613 throw new IllegalArgumentException("File descriptors passed in Intent");
4614 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004615 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004616 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4617 throw new IllegalArgumentException(
4618 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4619 }
4620 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004621 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004622 }
4623 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004624 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004625 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004626 }
4627 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004628 if (options != null) {
4629 if (options.hasFileDescriptors()) {
4630 throw new IllegalArgumentException("File descriptors passed in options");
4631 }
4632 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 synchronized(this) {
4635 int callingUid = Binder.getCallingUid();
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004636 int origUserId = userId;
Dianne Hackborn139748f2012-09-24 11:36:57 -07004637 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07004638 type == ActivityManager.INTENT_SENDER_BROADCAST, false,
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -07004639 "getIntentSender", null);
4640 if (origUserId == UserHandle.USER_CURRENT) {
4641 // We don't want to evaluate this until the pending intent is
4642 // actually executed. However, we do want to always do the
4643 // security checking for it above.
4644 userId = UserHandle.USER_CURRENT;
4645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004647 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004648 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004649 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4650 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 String msg = "Permission Denial: getIntentSender() from pid="
4652 + Binder.getCallingPid()
4653 + ", uid=" + Binder.getCallingUid()
4654 + ", (need uid=" + uid + ")"
4655 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004656 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 throw new SecurityException(msg);
4658 }
4659 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004660
4661 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004662 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004664 } catch (RemoteException e) {
4665 throw new SecurityException(e);
4666 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004667 }
4668 }
4669
Dianne Hackborn41203752012-08-31 14:05:51 -07004670 IIntentSender getIntentSenderLocked(int type, String packageName,
4671 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004672 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4673 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004674 if (DEBUG_MU)
4675 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004676 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004677 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004678 activity = mMainStack.isInStackLocked(token);
4679 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004680 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004682 if (activity.finishing) {
4683 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004685 }
4686
4687 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4688 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4689 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4690 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4691 |PendingIntent.FLAG_UPDATE_CURRENT);
4692
4693 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4694 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004695 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004696 WeakReference<PendingIntentRecord> ref;
4697 ref = mIntentSenderRecords.get(key);
4698 PendingIntentRecord rec = ref != null ? ref.get() : null;
4699 if (rec != null) {
4700 if (!cancelCurrent) {
4701 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004702 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004703 rec.key.requestIntent.replaceExtras(intents != null ?
4704 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004705 }
4706 if (intents != null) {
4707 intents[intents.length-1] = rec.key.requestIntent;
4708 rec.key.allIntents = intents;
4709 rec.key.allResolvedTypes = resolvedTypes;
4710 } else {
4711 rec.key.allIntents = null;
4712 rec.key.allResolvedTypes = null;
4713 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004715 return rec;
4716 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004717 rec.canceled = true;
4718 mIntentSenderRecords.remove(key);
4719 }
4720 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004721 return rec;
4722 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004723 rec = new PendingIntentRecord(this, key, callingUid);
4724 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004725 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004726 if (activity.pendingResults == null) {
4727 activity.pendingResults
4728 = new HashSet<WeakReference<PendingIntentRecord>>();
4729 }
4730 activity.pendingResults.add(rec.ref);
4731 }
4732 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 }
4734
4735 public void cancelIntentSender(IIntentSender sender) {
4736 if (!(sender instanceof PendingIntentRecord)) {
4737 return;
4738 }
4739 synchronized(this) {
4740 PendingIntentRecord rec = (PendingIntentRecord)sender;
4741 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004742 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004743 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4744 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 String msg = "Permission Denial: cancelIntentSender() from pid="
4746 + Binder.getCallingPid()
4747 + ", uid=" + Binder.getCallingUid()
4748 + " is not allowed to cancel packges "
4749 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004750 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 throw new SecurityException(msg);
4752 }
4753 } catch (RemoteException e) {
4754 throw new SecurityException(e);
4755 }
4756 cancelIntentSenderLocked(rec, true);
4757 }
4758 }
4759
4760 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4761 rec.canceled = true;
4762 mIntentSenderRecords.remove(rec.key);
4763 if (cleanActivity && rec.key.activity != null) {
4764 rec.key.activity.pendingResults.remove(rec.ref);
4765 }
4766 }
4767
4768 public String getPackageForIntentSender(IIntentSender pendingResult) {
4769 if (!(pendingResult instanceof PendingIntentRecord)) {
4770 return null;
4771 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004772 try {
4773 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4774 return res.key.packageName;
4775 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777 return null;
4778 }
4779
Christopher Tatec4a07d12012-04-06 14:19:13 -07004780 public int getUidForIntentSender(IIntentSender sender) {
4781 if (sender instanceof PendingIntentRecord) {
4782 try {
4783 PendingIntentRecord res = (PendingIntentRecord)sender;
4784 return res.uid;
4785 } catch (ClassCastException e) {
4786 }
4787 }
4788 return -1;
4789 }
4790
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004791 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4792 if (!(pendingResult instanceof PendingIntentRecord)) {
4793 return false;
4794 }
4795 try {
4796 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4797 if (res.key.allIntents == null) {
4798 return false;
4799 }
4800 for (int i=0; i<res.key.allIntents.length; i++) {
4801 Intent intent = res.key.allIntents[i];
4802 if (intent.getPackage() != null && intent.getComponent() != null) {
4803 return false;
4804 }
4805 }
4806 return true;
4807 } catch (ClassCastException e) {
4808 }
4809 return false;
4810 }
4811
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004812 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4813 if (!(pendingResult instanceof PendingIntentRecord)) {
4814 return false;
4815 }
4816 try {
4817 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4818 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4819 return true;
4820 }
4821 return false;
4822 } catch (ClassCastException e) {
4823 }
4824 return false;
4825 }
4826
Dianne Hackborn81038902012-11-26 17:04:09 -08004827 public Intent getIntentForIntentSender(IIntentSender pendingResult) {
4828 if (!(pendingResult instanceof PendingIntentRecord)) {
4829 return null;
4830 }
4831 try {
4832 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4833 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null;
4834 } catch (ClassCastException e) {
4835 }
4836 return null;
4837 }
4838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 public void setProcessLimit(int max) {
4840 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4841 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004842 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004843 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004844 mProcessLimitOverride = max;
4845 }
4846 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004847 }
4848
4849 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004850 synchronized (this) {
4851 return mProcessLimitOverride;
4852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 }
4854
4855 void foregroundTokenDied(ForegroundToken token) {
4856 synchronized (ActivityManagerService.this) {
4857 synchronized (mPidsSelfLocked) {
4858 ForegroundToken cur
4859 = mForegroundProcesses.get(token.pid);
4860 if (cur != token) {
4861 return;
4862 }
4863 mForegroundProcesses.remove(token.pid);
4864 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4865 if (pr == null) {
4866 return;
4867 }
4868 pr.forcingToForeground = null;
4869 pr.foregroundServices = false;
4870 }
4871 updateOomAdjLocked();
4872 }
4873 }
4874
4875 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4876 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4877 "setProcessForeground()");
4878 synchronized(this) {
4879 boolean changed = false;
4880
4881 synchronized (mPidsSelfLocked) {
4882 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004883 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004884 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 return;
4886 }
4887 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4888 if (oldToken != null) {
4889 oldToken.token.unlinkToDeath(oldToken, 0);
4890 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004891 if (pr != null) {
4892 pr.forcingToForeground = null;
4893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004894 changed = true;
4895 }
4896 if (isForeground && token != null) {
4897 ForegroundToken newToken = new ForegroundToken() {
4898 public void binderDied() {
4899 foregroundTokenDied(this);
4900 }
4901 };
4902 newToken.pid = pid;
4903 newToken.token = token;
4904 try {
4905 token.linkToDeath(newToken, 0);
4906 mForegroundProcesses.put(pid, newToken);
4907 pr.forcingToForeground = token;
4908 changed = true;
4909 } catch (RemoteException e) {
4910 // If the process died while doing this, we will later
4911 // do the cleanup with the process death link.
4912 }
4913 }
4914 }
4915
4916 if (changed) {
4917 updateOomAdjLocked();
4918 }
4919 }
4920 }
4921
4922 // =========================================================
4923 // PERMISSIONS
4924 // =========================================================
4925
4926 static class PermissionController extends IPermissionController.Stub {
4927 ActivityManagerService mActivityManagerService;
4928 PermissionController(ActivityManagerService activityManagerService) {
4929 mActivityManagerService = activityManagerService;
4930 }
4931
4932 public boolean checkPermission(String permission, int pid, int uid) {
4933 return mActivityManagerService.checkPermission(permission, pid,
4934 uid) == PackageManager.PERMISSION_GRANTED;
4935 }
4936 }
4937
4938 /**
4939 * This can be called with or without the global lock held.
4940 */
4941 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004942 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004943 // We might be performing an operation on behalf of an indirect binder
4944 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4945 // client identity accordingly before proceeding.
4946 Identity tlsIdentity = sCallerIdentity.get();
4947 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004948 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004949 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4950 uid = tlsIdentity.uid;
4951 pid = tlsIdentity.pid;
4952 }
4953
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004954 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004955 return PackageManager.PERMISSION_GRANTED;
4956 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004957
4958 return ActivityManager.checkComponentPermission(permission, uid,
4959 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004960 }
4961
4962 /**
4963 * As the only public entry point for permissions checking, this method
4964 * can enforce the semantic that requesting a check on a null global
4965 * permission is automatically denied. (Internally a null permission
4966 * string is used when calling {@link #checkComponentPermission} in cases
4967 * when only uid-based security is needed.)
4968 *
4969 * This can be called with or without the global lock held.
4970 */
4971 public int checkPermission(String permission, int pid, int uid) {
4972 if (permission == null) {
4973 return PackageManager.PERMISSION_DENIED;
4974 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004975 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
4977
4978 /**
4979 * Binder IPC calls go through the public entry point.
4980 * This can be called with or without the global lock held.
4981 */
4982 int checkCallingPermission(String permission) {
4983 return checkPermission(permission,
4984 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004985 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 }
4987
4988 /**
4989 * This can be called with or without the global lock held.
4990 */
4991 void enforceCallingPermission(String permission, String func) {
4992 if (checkCallingPermission(permission)
4993 == PackageManager.PERMISSION_GRANTED) {
4994 return;
4995 }
4996
4997 String msg = "Permission Denial: " + func + " from pid="
4998 + Binder.getCallingPid()
4999 + ", uid=" + Binder.getCallingUid()
5000 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005001 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 throw new SecurityException(msg);
5003 }
5004
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005005 /**
5006 * Determine if UID is holding permissions required to access {@link Uri} in
5007 * the given {@link ProviderInfo}. Final permission checking is always done
5008 * in {@link ContentProvider}.
5009 */
5010 private final boolean checkHoldingPermissionsLocked(
5011 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005012 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5013 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005014
5015 if (pi.applicationInfo.uid == uid) {
5016 return true;
5017 } else if (!pi.exported) {
5018 return false;
5019 }
5020
5021 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
5022 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005024 // check if target holds top-level <provider> permissions
5025 if (!readMet && pi.readPermission != null
5026 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
5027 readMet = true;
5028 }
5029 if (!writeMet && pi.writePermission != null
5030 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
5031 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005033
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005034 // track if unprotected read/write is allowed; any denied
5035 // <path-permission> below removes this ability
5036 boolean allowDefaultRead = pi.readPermission == null;
5037 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07005038
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005039 // check if target holds any <path-permission> that match uri
5040 final PathPermission[] pps = pi.pathPermissions;
5041 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005042 final String path = uri.getPath();
5043 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005044 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07005045 i--;
5046 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005047 if (pp.match(path)) {
5048 if (!readMet) {
5049 final String pprperm = pp.getReadPermission();
5050 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
5051 + pprperm + " for " + pp.getPath()
5052 + ": match=" + pp.match(path)
5053 + " check=" + pm.checkUidPermission(pprperm, uid));
5054 if (pprperm != null) {
5055 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
5056 readMet = true;
5057 } else {
5058 allowDefaultRead = false;
5059 }
5060 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005061 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005062 if (!writeMet) {
5063 final String ppwperm = pp.getWritePermission();
5064 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
5065 + ppwperm + " for " + pp.getPath()
5066 + ": match=" + pp.match(path)
5067 + " check=" + pm.checkUidPermission(ppwperm, uid));
5068 if (ppwperm != null) {
5069 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
5070 writeMet = true;
5071 } else {
5072 allowDefaultWrite = false;
5073 }
5074 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005075 }
5076 }
5077 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005078 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005079
5080 // grant unprotected <provider> read/write, if not blocked by
5081 // <path-permission> above
5082 if (allowDefaultRead) readMet = true;
5083 if (allowDefaultWrite) writeMet = true;
5084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005085 } catch (RemoteException e) {
5086 return false;
5087 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07005088
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005089 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 }
5091
5092 private final boolean checkUriPermissionLocked(Uri uri, int uid,
5093 int modeFlags) {
5094 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07005095 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 return true;
5097 }
5098 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
5099 if (perms == null) return false;
5100 UriPermission perm = perms.get(uri);
5101 if (perm == null) return false;
5102 return (modeFlags&perm.modeFlags) == modeFlags;
5103 }
5104
5105 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005106 enforceNotIsolatedCaller("checkUriPermission");
5107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005108 // Another redirected-binder-call permissions check as in
5109 // {@link checkComponentPermission}.
5110 Identity tlsIdentity = sCallerIdentity.get();
5111 if (tlsIdentity != null) {
5112 uid = tlsIdentity.uid;
5113 pid = tlsIdentity.pid;
5114 }
5115
5116 // Our own process gets to do everything.
5117 if (pid == MY_PID) {
5118 return PackageManager.PERMISSION_GRANTED;
5119 }
5120 synchronized(this) {
5121 return checkUriPermissionLocked(uri, uid, modeFlags)
5122 ? PackageManager.PERMISSION_GRANTED
5123 : PackageManager.PERMISSION_DENIED;
5124 }
5125 }
5126
Dianne Hackborn39792d22010-08-19 18:01:52 -07005127 /**
5128 * Check if the targetPkg can be granted permission to access uri by
5129 * the callingUid using the given modeFlags. Throws a security exception
5130 * if callingUid is not allowed to do this. Returns the uid of the target
5131 * if the URI permission grant should be performed; returns -1 if it is not
5132 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005133 * If you already know the uid of the target, you can supply it in
5134 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005135 */
5136 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005137 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5139 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5140 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005141 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 }
5143
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005144 if (targetPkg != null) {
5145 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5146 "Checking grant " + targetPkg + " permission to " + uri);
5147 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005148
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005149 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150
5151 // If this is not a content: uri, we can't do anything with it.
5152 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005153 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005154 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005155 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157
5158 String name = uri.getAuthority();
5159 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005160 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005161 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005162 if (cpr != null) {
5163 pi = cpr.info;
5164 } else {
5165 try {
5166 pi = pm.resolveContentProvider(name,
Dianne Hackborn11f0cb72012-09-16 17:12:34 -07005167 PackageManager.GET_URI_PERMISSION_PATTERNS,
5168 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 } catch (RemoteException ex) {
5170 }
5171 }
5172 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005173 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005174 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 }
5176
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005177 int targetUid = lastTargetUid;
5178 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005179 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005180 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005181 if (targetUid < 0) {
5182 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5183 "Can't grant URI permission no uid for: " + targetPkg);
5184 return -1;
5185 }
5186 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005187 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005189 }
5190
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005191 if (targetUid >= 0) {
5192 // First... does the target actually need this permission?
5193 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5194 // No need to grant the target this permission.
5195 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5196 "Target " + targetPkg + " already has full permission to " + uri);
5197 return -1;
5198 }
5199 } else {
5200 // First... there is no target package, so can anyone access it?
5201 boolean allowed = pi.exported;
5202 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5203 if (pi.readPermission != null) {
5204 allowed = false;
5205 }
5206 }
5207 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5208 if (pi.writePermission != null) {
5209 allowed = false;
5210 }
5211 }
5212 if (allowed) {
5213 return -1;
5214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005215 }
5216
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005217 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 if (!pi.grantUriPermissions) {
5219 throw new SecurityException("Provider " + pi.packageName
5220 + "/" + pi.name
5221 + " does not allow granting of Uri permissions (uri "
5222 + uri + ")");
5223 }
5224 if (pi.uriPermissionPatterns != null) {
5225 final int N = pi.uriPermissionPatterns.length;
5226 boolean allowed = false;
5227 for (int i=0; i<N; i++) {
5228 if (pi.uriPermissionPatterns[i] != null
5229 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5230 allowed = true;
5231 break;
5232 }
5233 }
5234 if (!allowed) {
5235 throw new SecurityException("Provider " + pi.packageName
5236 + "/" + pi.name
5237 + " does not allow granting of permission to path of Uri "
5238 + uri);
5239 }
5240 }
5241
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005242 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005243 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005244 if (callingUid != Process.myUid()) {
5245 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5246 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5247 throw new SecurityException("Uid " + callingUid
5248 + " does not have permission to uri " + uri);
5249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 }
5251 }
5252
Dianne Hackborn39792d22010-08-19 18:01:52 -07005253 return targetUid;
5254 }
5255
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005256 public int checkGrantUriPermission(int callingUid, String targetPkg,
5257 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005258 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005259 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005260 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005261 }
5262 }
5263
Dianne Hackborn39792d22010-08-19 18:01:52 -07005264 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5265 Uri uri, int modeFlags, UriPermissionOwner owner) {
5266 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5267 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5268 if (modeFlags == 0) {
5269 return;
5270 }
5271
5272 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 // to the uri, and the target doesn't. Let's now give this to
5274 // the target.
5275
Joe Onorato8a9b2202010-02-26 18:56:32 -08005276 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005277 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279 HashMap<Uri, UriPermission> targetUris
5280 = mGrantedUriPermissions.get(targetUid);
5281 if (targetUris == null) {
5282 targetUris = new HashMap<Uri, UriPermission>();
5283 mGrantedUriPermissions.put(targetUid, targetUris);
5284 }
5285
5286 UriPermission perm = targetUris.get(uri);
5287 if (perm == null) {
5288 perm = new UriPermission(targetUid, uri);
5289 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005293 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005295 } else {
5296 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5297 perm.readOwners.add(owner);
5298 owner.addReadPermission(perm);
5299 }
5300 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5301 perm.writeOwners.add(owner);
5302 owner.addWritePermission(perm);
5303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005304 }
5305 }
5306
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005307 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5308 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005309 if (targetPkg == null) {
5310 throw new NullPointerException("targetPkg");
5311 }
5312
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005313 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005314 if (targetUid < 0) {
5315 return;
5316 }
5317
5318 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5319 }
5320
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005321 static class NeededUriGrants extends ArrayList<Uri> {
5322 final String targetPkg;
5323 final int targetUid;
5324 final int flags;
5325
5326 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5327 targetPkg = _targetPkg;
5328 targetUid = _targetUid;
5329 flags = _flags;
5330 }
5331 }
5332
Dianne Hackborn39792d22010-08-19 18:01:52 -07005333 /**
5334 * Like checkGrantUriPermissionLocked, but takes an Intent.
5335 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005336 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5337 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005338 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005339 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5340 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005341 + " from " + intent + "; flags=0x"
5342 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5343
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005344 if (targetPkg == null) {
5345 throw new NullPointerException("targetPkg");
5346 }
5347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005348 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005349 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 }
5351 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005352 ClipData clip = intent.getClipData();
5353 if (data == null && clip == null) {
5354 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005355 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005356 if (data != null) {
5357 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5358 mode, needed != null ? needed.targetUid : -1);
5359 if (target > 0) {
5360 if (needed == null) {
5361 needed = new NeededUriGrants(targetPkg, target, mode);
5362 }
5363 needed.add(data);
5364 }
5365 }
5366 if (clip != null) {
5367 for (int i=0; i<clip.getItemCount(); i++) {
5368 Uri uri = clip.getItemAt(i).getUri();
5369 if (uri != null) {
5370 int target = -1;
5371 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5372 mode, needed != null ? needed.targetUid : -1);
5373 if (target > 0) {
5374 if (needed == null) {
5375 needed = new NeededUriGrants(targetPkg, target, mode);
5376 }
5377 needed.add(uri);
5378 }
5379 } else {
5380 Intent clipIntent = clip.getItemAt(i).getIntent();
5381 if (clipIntent != null) {
5382 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5383 callingUid, targetPkg, clipIntent, mode, needed);
5384 if (newNeeded != null) {
5385 needed = newNeeded;
5386 }
5387 }
5388 }
5389 }
5390 }
5391
5392 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005393 }
5394
5395 /**
5396 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5397 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005398 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5399 UriPermissionOwner owner) {
5400 if (needed != null) {
5401 for (int i=0; i<needed.size(); i++) {
5402 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5403 needed.get(i), needed.flags, owner);
5404 }
5405 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005406 }
5407
5408 void grantUriPermissionFromIntentLocked(int callingUid,
5409 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005410 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005411 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005412 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005413 return;
5414 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005415
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005416 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 }
5418
5419 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5420 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005421 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 synchronized(this) {
5423 final ProcessRecord r = getRecordForAppLocked(caller);
5424 if (r == null) {
5425 throw new SecurityException("Unable to find app for caller "
5426 + caller
5427 + " when granting permission to uri " + uri);
5428 }
5429 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005430 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 }
5432 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005433 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434 }
5435
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005436 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 null);
5438 }
5439 }
5440
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005441 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5443 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5444 HashMap<Uri, UriPermission> perms
5445 = mGrantedUriPermissions.get(perm.uid);
5446 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005447 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005448 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 perms.remove(perm.uri);
5450 if (perms.size() == 0) {
5451 mGrantedUriPermissions.remove(perm.uid);
5452 }
5453 }
5454 }
5455 }
5456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5458 int modeFlags) {
5459 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5460 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5461 if (modeFlags == 0) {
5462 return;
5463 }
5464
Joe Onorato8a9b2202010-02-26 18:56:32 -08005465 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005466 "Revoking all granted permissions to " + uri);
5467
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005468 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469
5470 final String authority = uri.getAuthority();
5471 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005472 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005473 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 if (cpr != null) {
5475 pi = cpr.info;
5476 } else {
5477 try {
5478 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005479 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005480 } catch (RemoteException ex) {
5481 }
5482 }
5483 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005484 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 return;
5486 }
5487
5488 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005489 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 // Right now, if you are not the original owner of the permission,
5491 // you are not allowed to revoke it.
5492 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5493 throw new SecurityException("Uid " + callingUid
5494 + " does not have permission to uri " + uri);
5495 //}
5496 }
5497
5498 // Go through all of the permissions and remove any that match.
5499 final List<String> SEGMENTS = uri.getPathSegments();
5500 if (SEGMENTS != null) {
5501 final int NS = SEGMENTS.size();
5502 int N = mGrantedUriPermissions.size();
5503 for (int i=0; i<N; i++) {
5504 HashMap<Uri, UriPermission> perms
5505 = mGrantedUriPermissions.valueAt(i);
5506 Iterator<UriPermission> it = perms.values().iterator();
5507 toploop:
5508 while (it.hasNext()) {
5509 UriPermission perm = it.next();
5510 Uri targetUri = perm.uri;
5511 if (!authority.equals(targetUri.getAuthority())) {
5512 continue;
5513 }
5514 List<String> targetSegments = targetUri.getPathSegments();
5515 if (targetSegments == null) {
5516 continue;
5517 }
5518 if (targetSegments.size() < NS) {
5519 continue;
5520 }
5521 for (int j=0; j<NS; j++) {
5522 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5523 continue toploop;
5524 }
5525 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005526 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005527 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 perm.clearModes(modeFlags);
5529 if (perm.modeFlags == 0) {
5530 it.remove();
5531 }
5532 }
5533 if (perms.size() == 0) {
5534 mGrantedUriPermissions.remove(
5535 mGrantedUriPermissions.keyAt(i));
5536 N--;
5537 i--;
5538 }
5539 }
5540 }
5541 }
5542
5543 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5544 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005545 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 synchronized(this) {
5547 final ProcessRecord r = getRecordForAppLocked(caller);
5548 if (r == null) {
5549 throw new SecurityException("Unable to find app for caller "
5550 + caller
5551 + " when revoking permission to uri " + uri);
5552 }
5553 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005554 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 return;
5556 }
5557
5558 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5559 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5560 if (modeFlags == 0) {
5561 return;
5562 }
5563
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005564 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565
5566 final String authority = uri.getAuthority();
5567 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005568 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 if (cpr != null) {
5570 pi = cpr.info;
5571 } else {
5572 try {
5573 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005574 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 } catch (RemoteException ex) {
5576 }
5577 }
5578 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005579 Slog.w(TAG, "No content provider found for permission revoke: "
5580 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 return;
5582 }
5583
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005584 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005585 }
5586 }
5587
Dianne Hackborn7e269642010-08-25 19:50:20 -07005588 @Override
5589 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005590 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005591 synchronized(this) {
5592 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5593 return owner.getExternalTokenLocked();
5594 }
5595 }
5596
5597 @Override
5598 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5599 Uri uri, int modeFlags) {
5600 synchronized(this) {
5601 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5602 if (owner == null) {
5603 throw new IllegalArgumentException("Unknown owner: " + token);
5604 }
5605 if (fromUid != Binder.getCallingUid()) {
5606 if (Binder.getCallingUid() != Process.myUid()) {
5607 // Only system code can grant URI permissions on behalf
5608 // of other users.
5609 throw new SecurityException("nice try");
5610 }
5611 }
5612 if (targetPkg == null) {
5613 throw new IllegalArgumentException("null target");
5614 }
5615 if (uri == null) {
5616 throw new IllegalArgumentException("null uri");
5617 }
5618
5619 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5620 }
5621 }
5622
5623 @Override
5624 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5625 synchronized(this) {
5626 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5627 if (owner == null) {
5628 throw new IllegalArgumentException("Unknown owner: " + token);
5629 }
5630
5631 if (uri == null) {
5632 owner.removeUriPermissionsLocked(mode);
5633 } else {
5634 owner.removeUriPermissionLocked(uri, mode);
5635 }
5636 }
5637 }
5638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5640 synchronized (this) {
5641 ProcessRecord app =
5642 who != null ? getRecordForAppLocked(who) : null;
5643 if (app == null) return;
5644
5645 Message msg = Message.obtain();
5646 msg.what = WAIT_FOR_DEBUGGER_MSG;
5647 msg.obj = app;
5648 msg.arg1 = waiting ? 1 : 0;
5649 mHandler.sendMessage(msg);
5650 }
5651 }
5652
5653 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005654 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5655 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005657 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005658 outInfo.threshold = homeAppMem;
5659 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5660 outInfo.hiddenAppThreshold = hiddenAppMem;
5661 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005662 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005663 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5664 ProcessList.VISIBLE_APP_ADJ);
5665 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5666 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 }
5668
5669 // =========================================================
5670 // TASK MANAGEMENT
5671 // =========================================================
5672
5673 public List getTasks(int maxNum, int flags,
5674 IThumbnailReceiver receiver) {
5675 ArrayList list = new ArrayList();
5676
5677 PendingThumbnailsRecord pending = null;
5678 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005679 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680
5681 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005682 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5684 + ", receiver=" + receiver);
5685
5686 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5687 != PackageManager.PERMISSION_GRANTED) {
5688 if (receiver != null) {
5689 // If the caller wants to wait for pending thumbnails,
5690 // it ain't gonna get them.
5691 try {
5692 receiver.finished();
5693 } catch (RemoteException ex) {
5694 }
5695 }
5696 String msg = "Permission Denial: getTasks() from pid="
5697 + Binder.getCallingPid()
5698 + ", uid=" + Binder.getCallingUid()
5699 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005700 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 throw new SecurityException(msg);
5702 }
5703
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005704 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005705 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005706 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005707 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 TaskRecord curTask = null;
5709 int numActivities = 0;
5710 int numRunning = 0;
5711 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005712 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005714 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715
5716 // Initialize state for next task if needed.
5717 if (top == null ||
5718 (top.state == ActivityState.INITIALIZING
5719 && top.task == r.task)) {
5720 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 curTask = r.task;
5722 numActivities = numRunning = 0;
5723 }
5724
5725 // Add 'r' into the current task.
5726 numActivities++;
5727 if (r.app != null && r.app.thread != null) {
5728 numRunning++;
5729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730
Joe Onorato8a9b2202010-02-26 18:56:32 -08005731 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 TAG, r.intent.getComponent().flattenToShortString()
5733 + ": task=" + r.task);
5734
5735 // If the next one is a different task, generate a new
5736 // TaskInfo entry for what we have.
5737 if (next == null || next.task != curTask) {
5738 ActivityManager.RunningTaskInfo ci
5739 = new ActivityManager.RunningTaskInfo();
5740 ci.id = curTask.taskId;
5741 ci.baseActivity = r.intent.getComponent();
5742 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005743 if (top.thumbHolder != null) {
5744 ci.description = top.thumbHolder.lastDescription;
5745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005746 ci.numActivities = numActivities;
5747 ci.numRunning = numRunning;
5748 //System.out.println(
5749 // "#" + maxNum + ": " + " descr=" + ci.description);
5750 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005751 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 TAG, "State=" + top.state + "Idle=" + top.idle
5753 + " app=" + top.app
5754 + " thr=" + (top.app != null ? top.app.thread : null));
5755 if (top.state == ActivityState.RESUMED
5756 || top.state == ActivityState.PAUSING) {
5757 if (top.idle && top.app != null
5758 && top.app.thread != null) {
5759 topRecord = top;
5760 topThumbnail = top.app.thread;
5761 } else {
5762 top.thumbnailNeeded = true;
5763 }
5764 }
5765 if (pending == null) {
5766 pending = new PendingThumbnailsRecord(receiver);
5767 }
5768 pending.pendingRecords.add(top);
5769 }
5770 list.add(ci);
5771 maxNum--;
5772 top = null;
5773 }
5774 }
5775
5776 if (pending != null) {
5777 mPendingThumbnails.add(pending);
5778 }
5779 }
5780
Joe Onorato8a9b2202010-02-26 18:56:32 -08005781 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782
5783 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005784 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005786 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005788 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005789 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 }
5791 }
5792
5793 if (pending == null && receiver != null) {
5794 // In this case all thumbnails were available and the client
5795 // is being asked to be told when the remaining ones come in...
5796 // which is unusually, since the top-most currently running
5797 // activity should never have a canned thumbnail! Oh well.
5798 try {
5799 receiver.finished();
5800 } catch (RemoteException ex) {
5801 }
5802 }
5803
5804 return list;
5805 }
5806
5807 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005808 int flags, int userId) {
Dianne Hackborn139748f2012-09-24 11:36:57 -07005809 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
5810 false, true, "getRecentTasks", null);
Amith Yamasani82644082012-08-03 13:09:11 -07005811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 synchronized (this) {
5813 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5814 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005815 final boolean detailed = checkCallingPermission(
5816 android.Manifest.permission.GET_DETAILED_TASKS)
5817 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005819 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 final int N = mRecentTasks.size();
5822 ArrayList<ActivityManager.RecentTaskInfo> res
5823 = new ArrayList<ActivityManager.RecentTaskInfo>(
5824 maxNum < N ? maxNum : N);
5825 for (int i=0; i<N && maxNum > 0; i++) {
5826 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005827 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005828 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005829 // Return the entry if desired by the caller. We always return
5830 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005831 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005832 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5833 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005834
Dianne Hackborn905577f2011-09-07 18:31:28 -07005835 if (i == 0
5836 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005837 || (tr.intent == null)
5838 || ((tr.intent.getFlags()
5839 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5840 ActivityManager.RecentTaskInfo rti
5841 = new ActivityManager.RecentTaskInfo();
5842 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005843 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 rti.baseIntent = new Intent(
5845 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005846 if (!detailed) {
5847 rti.baseIntent.replaceExtras((Bundle)null);
5848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005850 rti.description = tr.lastDescription;
5851
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005852 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5853 // Check whether this activity is currently available.
5854 try {
5855 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005856 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005857 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005858 continue;
5859 }
5860 } else if (rti.baseIntent != null) {
5861 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005862 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005863 continue;
5864 }
5865 }
5866 } catch (RemoteException e) {
5867 // Will never happen.
5868 }
5869 }
5870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 res.add(rti);
5872 maxNum--;
5873 }
5874 }
5875 return res;
5876 }
5877 }
5878
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005879 private TaskRecord taskForIdLocked(int id) {
5880 final int N = mRecentTasks.size();
5881 for (int i=0; i<N; i++) {
5882 TaskRecord tr = mRecentTasks.get(i);
5883 if (tr.taskId == id) {
5884 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005885 }
5886 }
5887 return null;
5888 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005889
5890 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5891 synchronized (this) {
5892 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5893 "getTaskThumbnails()");
5894 TaskRecord tr = taskForIdLocked(id);
5895 if (tr != null) {
5896 return mMainStack.getTaskThumbnailsLocked(tr);
5897 }
5898 }
5899 return null;
5900 }
5901
Dianne Hackborn15491c62012-09-19 10:59:14 -07005902 public Bitmap getTaskTopThumbnail(int id) {
5903 synchronized (this) {
5904 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5905 "getTaskTopThumbnail()");
5906 TaskRecord tr = taskForIdLocked(id);
5907 if (tr != null) {
5908 return mMainStack.getTaskTopThumbnailLocked(tr);
5909 }
5910 }
5911 return null;
5912 }
5913
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005914 public boolean removeSubTask(int taskId, int subTaskIndex) {
5915 synchronized (this) {
5916 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5917 "removeSubTask()");
5918 long ident = Binder.clearCallingIdentity();
5919 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005920 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5921 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005922 } finally {
5923 Binder.restoreCallingIdentity(ident);
5924 }
5925 }
5926 }
5927
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005928 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5929 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005930 Intent baseIntent = new Intent(
5931 tr.intent != null ? tr.intent : tr.affinityIntent);
5932 ComponentName component = baseIntent.getComponent();
5933 if (component == null) {
5934 Slog.w(TAG, "Now component for base intent of task: " + tr);
5935 return;
5936 }
5937
5938 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005939 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005940
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005941 if (killProcesses) {
5942 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005943 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005944 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005945 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5946 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5947 for (int i=0; i<uids.size(); i++) {
5948 ProcessRecord proc = uids.valueAt(i);
5949 if (proc.userId != tr.userId) {
5950 continue;
5951 }
5952 if (!proc.pkgList.contains(pkg)) {
5953 continue;
5954 }
5955 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005956 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005957 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005958
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005959 // Kill the running processes.
5960 for (int i=0; i<procs.size(); i++) {
5961 ProcessRecord pr = procs.get(i);
5962 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5963 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005964 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid,
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005965 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005966 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005967 Process.killProcessQuiet(pr.pid);
5968 } else {
5969 pr.waitingToKill = "remove task";
5970 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005971 }
5972 }
5973 }
5974
5975 public boolean removeTask(int taskId, int flags) {
5976 synchronized (this) {
5977 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5978 "removeTask()");
5979 long ident = Binder.clearCallingIdentity();
5980 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005981 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5982 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005983 if (r != null) {
5984 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005985 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005986 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005987 } else {
5988 TaskRecord tr = null;
5989 int i=0;
5990 while (i < mRecentTasks.size()) {
5991 TaskRecord t = mRecentTasks.get(i);
5992 if (t.taskId == taskId) {
5993 tr = t;
5994 break;
5995 }
5996 i++;
5997 }
5998 if (tr != null) {
5999 if (tr.numActivities <= 0) {
6000 // Caller is just removing a recent task that is
6001 // not actively running. That is easy!
6002 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07006003 cleanUpRemovedTaskLocked(tr, flags);
6004 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07006005 } else {
6006 Slog.w(TAG, "removeTask: task " + taskId
6007 + " does not have activities to remove, "
6008 + " but numActivities=" + tr.numActivities
6009 + ": " + tr);
6010 }
6011 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006012 }
6013 } finally {
6014 Binder.restoreCallingIdentity(ident);
6015 }
6016 }
6017 return false;
6018 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08006019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
6021 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006022 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 TaskRecord jt = startTask;
6024
6025 // First look backwards
6026 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006027 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 if (r.task != jt) {
6029 jt = r.task;
6030 if (affinity.equals(jt.affinity)) {
6031 return j;
6032 }
6033 }
6034 }
6035
6036 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006037 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 jt = startTask;
6039 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006040 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 if (r.task != jt) {
6042 if (affinity.equals(jt.affinity)) {
6043 return j;
6044 }
6045 jt = r.task;
6046 }
6047 }
6048
6049 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006050 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 return N-1;
6052 }
6053
6054 return -1;
6055 }
6056
6057 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006058 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006060 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6062 "moveTaskToFront()");
6063
6064 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006065 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6066 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006067 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006068 return;
6069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 final long origId = Binder.clearCallingIdentity();
6071 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006072 TaskRecord tr = taskForIdLocked(task);
6073 if (tr != null) {
6074 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6075 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006077 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6078 // Caller wants the home activity moved with it. To accomplish this,
6079 // we'll just move the home task to the top first.
6080 mMainStack.moveHomeToFrontLocked();
6081 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006082 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07006083 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006085 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
6086 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08006088 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
6089 mMainStack.mUserLeaving = true;
6090 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08006091 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
6092 // Caller wants the home activity moved with it. To accomplish this,
6093 // we'll just move the home task to the top first.
6094 mMainStack.moveHomeToFrontLocked();
6095 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006096 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 return;
6098 }
6099 }
6100 } finally {
6101 Binder.restoreCallingIdentity(origId);
6102 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006103 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 }
6105 }
6106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 public void moveTaskToBack(int task) {
6108 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6109 "moveTaskToBack()");
6110
6111 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006112 if (mMainStack.mResumedActivity != null
6113 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006114 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6115 Binder.getCallingUid(), "Task to back")) {
6116 return;
6117 }
6118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006120 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 Binder.restoreCallingIdentity(origId);
6122 }
6123 }
6124
6125 /**
6126 * Moves an activity, and all of the other activities within the same task, to the bottom
6127 * of the history stack. The activity's order within the task is unchanged.
6128 *
6129 * @param token A reference to the activity we wish to move
6130 * @param nonRoot If false then this only works if the activity is the root
6131 * of a task; if true it will work for any activity in a task.
6132 * @return Returns true if the move completed, false if not.
6133 */
6134 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006135 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 synchronized(this) {
6137 final long origId = Binder.clearCallingIdentity();
6138 int taskId = getTaskForActivityLocked(token, !nonRoot);
6139 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006140 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 }
6142 Binder.restoreCallingIdentity(origId);
6143 }
6144 return false;
6145 }
6146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 public void moveTaskBackwards(int task) {
6148 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6149 "moveTaskBackwards()");
6150
6151 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006152 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6153 Binder.getCallingUid(), "Task backwards")) {
6154 return;
6155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 final long origId = Binder.clearCallingIdentity();
6157 moveTaskBackwardsLocked(task);
6158 Binder.restoreCallingIdentity(origId);
6159 }
6160 }
6161
6162 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006163 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 }
6165
6166 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6167 synchronized(this) {
6168 return getTaskForActivityLocked(token, onlyRoot);
6169 }
6170 }
6171
6172 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006173 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 TaskRecord lastTask = null;
6175 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006176 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006177 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 if (!onlyRoot || lastTask != r.task) {
6179 return r.task.taskId;
6180 }
6181 return -1;
6182 }
6183 lastTask = r.task;
6184 }
6185
6186 return -1;
6187 }
6188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 // =========================================================
6190 // THUMBNAILS
6191 // =========================================================
6192
6193 public void reportThumbnail(IBinder token,
6194 Bitmap thumbnail, CharSequence description) {
6195 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6196 final long origId = Binder.clearCallingIdentity();
6197 sendPendingThumbnail(null, token, thumbnail, description, true);
6198 Binder.restoreCallingIdentity(origId);
6199 }
6200
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006201 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 Bitmap thumbnail, CharSequence description, boolean always) {
6203 TaskRecord task = null;
6204 ArrayList receivers = null;
6205
6206 //System.out.println("Send pending thumbnail: " + r);
6207
6208 synchronized(this) {
6209 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006210 r = mMainStack.isInStackLocked(token);
6211 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 return;
6213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006215 if (thumbnail == null && r.thumbHolder != null) {
6216 thumbnail = r.thumbHolder.lastThumbnail;
6217 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 }
6219 if (thumbnail == null && !always) {
6220 // If there is no thumbnail, and this entry is not actually
6221 // going away, then abort for now and pick up the next
6222 // thumbnail we get.
6223 return;
6224 }
6225 task = r.task;
6226
6227 int N = mPendingThumbnails.size();
6228 int i=0;
6229 while (i<N) {
6230 PendingThumbnailsRecord pr =
6231 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6232 //System.out.println("Looking in " + pr.pendingRecords);
6233 if (pr.pendingRecords.remove(r)) {
6234 if (receivers == null) {
6235 receivers = new ArrayList();
6236 }
6237 receivers.add(pr);
6238 if (pr.pendingRecords.size() == 0) {
6239 pr.finished = true;
6240 mPendingThumbnails.remove(i);
6241 N--;
6242 continue;
6243 }
6244 }
6245 i++;
6246 }
6247 }
6248
6249 if (receivers != null) {
6250 final int N = receivers.size();
6251 for (int i=0; i<N; i++) {
6252 try {
6253 PendingThumbnailsRecord pr =
6254 (PendingThumbnailsRecord)receivers.get(i);
6255 pr.receiver.newThumbnail(
6256 task != null ? task.taskId : -1, thumbnail, description);
6257 if (pr.finished) {
6258 pr.receiver.finished();
6259 }
6260 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006261 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 }
6263 }
6264 }
6265 }
6266
6267 // =========================================================
6268 // CONTENT PROVIDERS
6269 // =========================================================
6270
Jeff Brown10e89712011-07-08 18:52:57 -07006271 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6272 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006274 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006275 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006276 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 } catch (RemoteException ex) {
6278 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006279 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006280 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6281 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006283 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 for (int i=0; i<N; i++) {
6285 ProviderInfo cpi =
6286 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006287 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6288 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006289 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006290 // This is a singleton provider, but a user besides the
6291 // default user is asking to initialize a process it runs
6292 // in... well, no, it doesn't actually run in this process,
6293 // it runs in the process of the default user. Get rid of it.
6294 providers.remove(i);
6295 N--;
6296 continue;
6297 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006298
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006299 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006300 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006302 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006303 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006305 if (DEBUG_MU)
6306 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 app.pubProviders.put(cpi.name, cpr);
6308 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006309 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 }
6311 }
6312 return providers;
6313 }
6314
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006315 /**
6316 * Check if {@link ProcessRecord} has a possible chance at accessing the
6317 * given {@link ProviderInfo}. Final permission checking is always done
6318 * in {@link ContentProvider}.
6319 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006321 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006323 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006325 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006326 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return null;
6328 }
6329 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006330 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 == PackageManager.PERMISSION_GRANTED) {
6332 return null;
6333 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006334
6335 PathPermission[] pps = cpi.pathPermissions;
6336 if (pps != null) {
6337 int i = pps.length;
6338 while (i > 0) {
6339 i--;
6340 PathPermission pp = pps[i];
6341 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006342 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006343 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006344 return null;
6345 }
6346 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006347 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006348 == PackageManager.PERMISSION_GRANTED) {
6349 return null;
6350 }
6351 }
6352 }
6353
Dianne Hackbornb424b632010-08-18 15:59:05 -07006354 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6355 if (perms != null) {
6356 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6357 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6358 return null;
6359 }
6360 }
6361 }
6362
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006363 String msg;
6364 if (!cpi.exported) {
6365 msg = "Permission Denial: opening provider " + cpi.name
6366 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6367 + ", uid=" + callingUid + ") that is not exported from uid "
6368 + cpi.applicationInfo.uid;
6369 } else {
6370 msg = "Permission Denial: opening provider " + cpi.name
6371 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6372 + ", uid=" + callingUid + ") requires "
6373 + cpi.readPermission + " or " + cpi.writePermission;
6374 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006375 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 return msg;
6377 }
6378
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006379 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6380 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006381 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006382 for (int i=0; i<r.conProviders.size(); i++) {
6383 ContentProviderConnection conn = r.conProviders.get(i);
6384 if (conn.provider == cpr) {
6385 if (DEBUG_PROVIDER) Slog.v(TAG,
6386 "Adding provider requested by "
6387 + r.processName + " from process "
6388 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6389 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6390 if (stable) {
6391 conn.stableCount++;
6392 conn.numStableIncs++;
6393 } else {
6394 conn.unstableCount++;
6395 conn.numUnstableIncs++;
6396 }
6397 return conn;
6398 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006399 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006400 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6401 if (stable) {
6402 conn.stableCount = 1;
6403 conn.numStableIncs = 1;
6404 } else {
6405 conn.unstableCount = 1;
6406 conn.numUnstableIncs = 1;
6407 }
6408 cpr.connections.add(conn);
6409 r.conProviders.add(conn);
6410 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006411 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006412 cpr.addExternalProcessHandleLocked(externalProcessToken);
6413 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006414 }
6415
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006416 boolean decProviderCountLocked(ContentProviderConnection conn,
6417 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6418 if (conn != null) {
6419 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006420 if (DEBUG_PROVIDER) Slog.v(TAG,
6421 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006422 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006423 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6425 if (stable) {
6426 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006427 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006428 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006429 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006430 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6431 cpr.connections.remove(conn);
6432 conn.client.conProviders.remove(conn);
6433 return true;
6434 }
6435 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006437 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006438 return false;
6439 }
6440
Amith Yamasani742a6712011-05-04 14:49:28 -07006441 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006442 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006444 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006445 ProviderInfo cpi = null;
6446
6447 synchronized(this) {
6448 ProcessRecord r = null;
6449 if (caller != null) {
6450 r = getRecordForAppLocked(caller);
6451 if (r == null) {
6452 throw new SecurityException(
6453 "Unable to find app for caller " + caller
6454 + " (pid=" + Binder.getCallingPid()
6455 + ") when getting content provider " + name);
6456 }
6457 }
6458
6459 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006460 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006461 boolean providerRunning = cpr != null;
6462 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006464 String msg;
6465 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6466 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 }
6468
6469 if (r != null && cpr.canRunHere(r)) {
6470 // This provider has been published or is in the process
6471 // of being published... but it is also allowed to run
6472 // in the caller's process, so don't make a connection
6473 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006474 ContentProviderHolder holder = cpr.newHolder(null);
6475 // don't give caller the provider object, it needs
6476 // to make its own.
6477 holder.provider = null;
6478 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 }
6480
6481 final long origId = Binder.clearCallingIdentity();
6482
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006483 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006485 conn = incProviderCountLocked(r, cpr, token, stable);
6486 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006487 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006488 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006489 // make sure to count it as being accessed and thus
6490 // back up on the LRU list. This is good because
6491 // content providers are often expensive to start.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006492 updateLruProcessLocked(cpr.proc, false);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006493 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006494 }
6495
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006496 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006497 if (false) {
6498 if (cpr.name.flattenToShortString().equals(
6499 "com.android.providers.calendar/.CalendarProvider2")) {
6500 Slog.v(TAG, "****************** KILLING "
6501 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006502 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006503 }
6504 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006505 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006506 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6507 // NOTE: there is still a race here where a signal could be
6508 // pending on the process even though we managed to update its
6509 // adj level. Not sure what to do about this, but at least
6510 // the race is now smaller.
6511 if (!success) {
6512 // Uh oh... it looks like the provider's process
6513 // has been killed on us. We need to wait for a new
6514 // process to be started, and make sure its death
6515 // doesn't kill our process.
6516 Slog.i(TAG,
6517 "Existing provider " + cpr.name.flattenToShortString()
6518 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006519 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006520 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006521 if (!lastRef) {
6522 // This wasn't the last ref our process had on
6523 // the provider... we have now been killed, bail.
6524 return null;
6525 }
6526 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006527 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
6530
6531 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006534 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006535 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006537 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006538 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006539 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 } catch (RemoteException ex) {
6541 }
6542 if (cpi == null) {
6543 return null;
6544 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006545 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6546 cpi.name, cpi.flags);
6547 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006548 userId = 0;
6549 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006550 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006551
Dianne Hackbornb424b632010-08-18 15:59:05 -07006552 String msg;
6553 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6554 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 }
6556
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006557 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006558 && !cpi.processName.equals("system")) {
6559 // If this content provider does not run in the system
6560 // process, and the system is not yet ready to run other
6561 // processes, then fail fast instead of hanging.
6562 throw new IllegalArgumentException(
6563 "Attempt to launch content provider before system ready");
6564 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006565
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006566 // Make sure that the user who owns this provider is started. If not,
6567 // we don't want to allow it to run.
6568 if (mStartedUsers.get(userId) == null) {
6569 Slog.w(TAG, "Unable to launch app "
6570 + cpi.applicationInfo.packageName + "/"
6571 + cpi.applicationInfo.uid + " for provider "
6572 + name + ": user " + userId + " is stopped");
6573 return null;
6574 }
6575
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006576 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006577 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 final boolean firstClass = cpr == null;
6579 if (firstClass) {
6580 try {
6581 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006582 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 getApplicationInfo(
6584 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006585 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006587 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006588 + cpi.name);
6589 return null;
6590 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006591 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006592 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 } catch (RemoteException ex) {
6594 // pm is in same process, this will never happen.
6595 }
6596 }
6597
6598 if (r != null && cpr.canRunHere(r)) {
6599 // If this is a multiprocess provider, then just return its
6600 // info and allow the caller to instantiate it. Only do
6601 // this if the provider is the same user as the caller's
6602 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006603 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006606 if (DEBUG_PROVIDER) {
6607 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006608 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006609 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
6611
6612 // This is single process, and our app is now connecting to it.
6613 // See if we are already in the process of launching this
6614 // provider.
6615 final int N = mLaunchingProviders.size();
6616 int i;
6617 for (i=0; i<N; i++) {
6618 if (mLaunchingProviders.get(i) == cpr) {
6619 break;
6620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 }
6622
6623 // If the provider is not already being launched, then get it
6624 // started.
6625 if (i >= N) {
6626 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006627
6628 try {
6629 // Content provider is now in use, its package can't be stopped.
6630 try {
6631 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006632 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006633 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006634 } catch (IllegalArgumentException e) {
6635 Slog.w(TAG, "Failed trying to unstop package "
6636 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006637 }
6638
6639 ProcessRecord proc = startProcessLocked(cpi.processName,
6640 cpr.appInfo, false, 0, "content provider",
6641 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006642 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006643 if (proc == null) {
6644 Slog.w(TAG, "Unable to launch app "
6645 + cpi.applicationInfo.packageName + "/"
6646 + cpi.applicationInfo.uid + " for provider "
6647 + name + ": process is bad");
6648 return null;
6649 }
6650 cpr.launchingApp = proc;
6651 mLaunchingProviders.add(cpr);
6652 } finally {
6653 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 }
6656
6657 // Make sure the provider is published (the same provider class
6658 // may be published under multiple names).
6659 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006660 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006662
Amith Yamasani742a6712011-05-04 14:49:28 -07006663 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006664 conn = incProviderCountLocked(r, cpr, token, stable);
6665 if (conn != null) {
6666 conn.waiting = true;
6667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 }
6669 }
6670
6671 // Wait for the provider to be published...
6672 synchronized (cpr) {
6673 while (cpr.provider == null) {
6674 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006675 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 + cpi.applicationInfo.packageName + "/"
6677 + cpi.applicationInfo.uid + " for provider "
6678 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006679 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07006680 UserHandle.getUserId(cpi.applicationInfo.uid),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 cpi.applicationInfo.packageName,
6682 cpi.applicationInfo.uid, name);
6683 return null;
6684 }
6685 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006686 if (DEBUG_MU) {
6687 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6688 + cpr.launchingApp);
6689 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006690 if (conn != null) {
6691 conn.waiting = true;
6692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 cpr.wait();
6694 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006695 } finally {
6696 if (conn != null) {
6697 conn.waiting = false;
6698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
6700 }
6701 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006702 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 }
6704
6705 public final ContentProviderHolder getContentProvider(
Jeff Sharkey6d515712012-09-20 16:06:08 -07006706 IApplicationThread caller, String name, int userId, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006707 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 if (caller == null) {
6709 String msg = "null IApplicationThread when getting content provider "
6710 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006711 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 throw new SecurityException(msg);
6713 }
6714
Dianne Hackborn139748f2012-09-24 11:36:57 -07006715 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006716 false, true, "getContentProvider", null);
6717 return getContentProviderImpl(caller, name, null, stable, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 }
6719
Jeff Sharkey6d515712012-09-20 16:06:08 -07006720 public ContentProviderHolder getContentProviderExternal(
6721 String name, int userId, IBinder token) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006722 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6723 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006724 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
Jeff Sharkey6d515712012-09-20 16:06:08 -07006725 false, true, "getContentProvider", null);
6726 return getContentProviderExternalUnchecked(name, token, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006727 }
6728
Dianne Hackborn41203752012-08-31 14:05:51 -07006729 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6730 IBinder token, int userId) {
6731 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 }
6733
6734 /**
6735 * Drop a content provider from a ProcessRecord's bookkeeping
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006736 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006737 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006738 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006740 ContentProviderConnection conn;
6741 try {
6742 conn = (ContentProviderConnection)connection;
6743 } catch (ClassCastException e) {
6744 String msg ="removeContentProvider: " + connection
6745 + " not a ContentProviderConnection";
6746 Slog.w(TAG, msg);
6747 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006749 if (conn == null) {
6750 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006751 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006752 if (decProviderCountLocked(conn, null, null, stable)) {
6753 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
6756 }
6757
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006758 public void removeContentProviderExternal(String name, IBinder token) {
6759 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6760 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006761 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006762 }
6763
Dianne Hackborn41203752012-08-31 14:05:51 -07006764 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006766 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 if(cpr == null) {
6768 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006769 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 return;
6771 }
6772
6773 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006774 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006775 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006776 if (localCpr.hasExternalProcessHandles()) {
6777 if (localCpr.removeExternalProcessHandleLocked(token)) {
6778 updateOomAdjLocked();
6779 } else {
6780 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6781 + " with no external reference for token: "
6782 + token + ".");
6783 }
6784 } else {
6785 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6786 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 }
6789 }
6790
6791 public final void publishContentProviders(IApplicationThread caller,
6792 List<ContentProviderHolder> providers) {
6793 if (providers == null) {
6794 return;
6795 }
6796
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006797 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006798 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006800 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006801 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 if (r == null) {
6803 throw new SecurityException(
6804 "Unable to find app for caller " + caller
6805 + " (pid=" + Binder.getCallingPid()
6806 + ") when publishing content providers");
6807 }
6808
6809 final long origId = Binder.clearCallingIdentity();
6810
6811 final int N = providers.size();
6812 for (int i=0; i<N; i++) {
6813 ContentProviderHolder src = providers.get(i);
6814 if (src == null || src.info == null || src.provider == null) {
6815 continue;
6816 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006817 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006818 if (DEBUG_MU)
6819 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006821 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006822 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 String names[] = dst.info.authority.split(";");
6824 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006825 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006826 }
6827
6828 int NL = mLaunchingProviders.size();
6829 int j;
6830 for (j=0; j<NL; j++) {
6831 if (mLaunchingProviders.get(j) == dst) {
6832 mLaunchingProviders.remove(j);
6833 j--;
6834 NL--;
6835 }
6836 }
6837 synchronized (dst) {
6838 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006839 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 dst.notifyAll();
6841 }
6842 updateOomAdjLocked(r);
6843 }
6844 }
6845
6846 Binder.restoreCallingIdentity(origId);
6847 }
6848 }
6849
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006850 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6851 ContentProviderConnection conn;
6852 try {
6853 conn = (ContentProviderConnection)connection;
6854 } catch (ClassCastException e) {
6855 String msg ="refContentProvider: " + connection
6856 + " not a ContentProviderConnection";
6857 Slog.w(TAG, msg);
6858 throw new IllegalArgumentException(msg);
6859 }
6860 if (conn == null) {
6861 throw new NullPointerException("connection is null");
6862 }
6863
6864 synchronized (this) {
6865 if (stable > 0) {
6866 conn.numStableIncs += stable;
6867 }
6868 stable = conn.stableCount + stable;
6869 if (stable < 0) {
6870 throw new IllegalStateException("stableCount < 0: " + stable);
6871 }
6872
6873 if (unstable > 0) {
6874 conn.numUnstableIncs += unstable;
6875 }
6876 unstable = conn.unstableCount + unstable;
6877 if (unstable < 0) {
6878 throw new IllegalStateException("unstableCount < 0: " + unstable);
6879 }
6880
6881 if ((stable+unstable) <= 0) {
6882 throw new IllegalStateException("ref counts can't go to zero here: stable="
6883 + stable + " unstable=" + unstable);
6884 }
6885 conn.stableCount = stable;
6886 conn.unstableCount = unstable;
6887 return !conn.dead;
6888 }
6889 }
6890
6891 public void unstableProviderDied(IBinder connection) {
6892 ContentProviderConnection conn;
6893 try {
6894 conn = (ContentProviderConnection)connection;
6895 } catch (ClassCastException e) {
6896 String msg ="refContentProvider: " + connection
6897 + " not a ContentProviderConnection";
6898 Slog.w(TAG, msg);
6899 throw new IllegalArgumentException(msg);
6900 }
6901 if (conn == null) {
6902 throw new NullPointerException("connection is null");
6903 }
6904
6905 // Safely retrieve the content provider associated with the connection.
6906 IContentProvider provider;
6907 synchronized (this) {
6908 provider = conn.provider.provider;
6909 }
6910
6911 if (provider == null) {
6912 // Um, yeah, we're way ahead of you.
6913 return;
6914 }
6915
6916 // Make sure the caller is being honest with us.
6917 if (provider.asBinder().pingBinder()) {
6918 // Er, no, still looks good to us.
6919 synchronized (this) {
6920 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6921 + " says " + conn + " died, but we don't agree");
6922 return;
6923 }
6924 }
6925
6926 // Well look at that! It's dead!
6927 synchronized (this) {
6928 if (conn.provider.provider != provider) {
6929 // But something changed... good enough.
6930 return;
6931 }
6932
6933 ProcessRecord proc = conn.provider.proc;
6934 if (proc == null || proc.thread == null) {
6935 // Seems like the process is already cleaned up.
6936 return;
6937 }
6938
6939 // As far as we're concerned, this is just like receiving a
6940 // death notification... just a bit prematurely.
6941 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6942 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006943 final long ident = Binder.clearCallingIdentity();
6944 try {
6945 appDiedLocked(proc, proc.pid, proc.thread);
6946 } finally {
6947 Binder.restoreCallingIdentity(ident);
6948 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006949 }
6950 }
6951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006952 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006953 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006954 synchronized (mSelf) {
6955 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6956 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006957 if (providers != null) {
6958 for (int i=providers.size()-1; i>=0; i--) {
6959 ProviderInfo pi = (ProviderInfo)providers.get(i);
6960 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6961 Slog.w(TAG, "Not installing system proc provider " + pi.name
6962 + ": not system .apk");
6963 providers.remove(i);
6964 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006965 }
6966 }
6967 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006968 if (providers != null) {
6969 mSystemThread.installSystemProviders(providers);
6970 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006971
6972 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006973
6974 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 }
6976
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006977 /**
6978 * Allows app to retrieve the MIME type of a URI without having permission
6979 * to access its content provider.
6980 *
6981 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6982 *
6983 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6984 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6985 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006986 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006987 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn139748f2012-09-24 11:36:57 -07006988 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006989 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006990 final String name = uri.getAuthority();
6991 final long ident = Binder.clearCallingIdentity();
6992 ContentProviderHolder holder = null;
6993
6994 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006995 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006996 if (holder != null) {
6997 return holder.provider.getType(uri);
6998 }
6999 } catch (RemoteException e) {
7000 Log.w(TAG, "Content provider dead retrieving " + uri, e);
7001 return null;
7002 } finally {
7003 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07007004 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07007005 }
7006 Binder.restoreCallingIdentity(ident);
7007 }
7008
7009 return null;
7010 }
7011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 // =========================================================
7013 // GLOBAL MANAGEMENT
7014 // =========================================================
7015
7016 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007017 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 String proc = customProcess != null ? customProcess : info.processName;
7019 BatteryStatsImpl.Uid.Proc ps = null;
7020 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007021 int uid = info.uid;
7022 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007023 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007024 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
7025 uid = 0;
7026 while (true) {
7027 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
7028 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
7029 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
7030 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007031 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007032 mNextIsolatedProcessUid++;
7033 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
7034 // No process for this uid, use it.
7035 break;
7036 }
7037 stepsLeft--;
7038 if (stepsLeft <= 0) {
7039 return null;
7040 }
7041 }
7042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 synchronized (stats) {
7044 ps = stats.getProcessStatsLocked(info.uid, proc);
7045 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007046 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 }
7048
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007049 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
7050 ProcessRecord app;
7051 if (!isolated) {
7052 app = getProcessRecordLocked(info.processName, info.uid);
7053 } else {
7054 app = null;
7055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056
7057 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007058 app = newProcessRecordLocked(null, info, null, isolated);
7059 mProcessNames.put(info.processName, app.uid, app);
7060 if (isolated) {
7061 mIsolatedProcesses.put(app.uid, app);
7062 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007063 updateLruProcessLocked(app, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 }
7065
Dianne Hackborne7f97212011-02-24 14:40:20 -08007066 // This package really, really can not be stopped.
7067 try {
7068 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07007069 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08007070 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08007071 } catch (IllegalArgumentException e) {
7072 Slog.w(TAG, "Failed trying to unstop package "
7073 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08007074 }
7075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
7077 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
7078 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007079 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007080 }
7081 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
7082 mPersistentStartingProcesses.add(app);
7083 startProcessLocked(app, "added application", app.processName);
7084 }
7085
7086 return app;
7087 }
7088
7089 public void unhandledBack() {
7090 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
7091 "unhandledBack()");
7092
7093 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007094 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08007095 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007096 TAG, "Performing unhandledBack(): stack size = " + count);
7097 if (count > 1) {
7098 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007099 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007100 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 Binder.restoreCallingIdentity(origId);
7102 }
7103 }
7104 }
7105
7106 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007107 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007108 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007110 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007111 ParcelFileDescriptor pfd = null;
7112 if (cph != null) {
7113 // We record the binder invoker's uid in thread-local storage before
7114 // going to the content provider to open the file. Later, in the code
7115 // that handles all permissions checks, we look for this uid and use
7116 // that rather than the Activity Manager's own uid. The effect is that
7117 // we do the check against the caller's permissions even though it looks
7118 // to the content provider like the Activity Manager itself is making
7119 // the request.
7120 sCallerIdentity.set(new Identity(
7121 Binder.getCallingPid(), Binder.getCallingUid()));
7122 try {
Dianne Hackborn35654b62013-01-14 17:38:02 -08007123 pfd = cph.provider.openFile(null, uri, "r");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 } catch (FileNotFoundException e) {
7125 // do nothing; pfd will be returned null
7126 } finally {
7127 // Ensure that whatever happens, we clean up the identity state
7128 sCallerIdentity.remove();
7129 }
7130
7131 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007132 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007133 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007134 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 }
7136 return pfd;
7137 }
7138
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007139 // Actually is sleeping or shutting down or whatever else in the future
7140 // is an inactive state.
7141 public boolean isSleeping() {
7142 return mSleeping || mShuttingDown;
7143 }
7144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007145 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007146 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7147 != PackageManager.PERMISSION_GRANTED) {
7148 throw new SecurityException("Requires permission "
7149 + android.Manifest.permission.DEVICE_POWER);
7150 }
7151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007153 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007154 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007156 if (!mSleeping) {
7157 mSleeping = true;
7158 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007159
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007160 // Initialize the wake times of all processes.
7161 checkExcessivePowerUsageLocked(false);
7162 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7163 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7164 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 }
7167 }
7168
Dianne Hackborn55280a92009-05-07 15:53:46 -07007169 public boolean shutdown(int timeout) {
7170 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7171 != PackageManager.PERMISSION_GRANTED) {
7172 throw new SecurityException("Requires permission "
7173 + android.Manifest.permission.SHUTDOWN);
7174 }
7175
7176 boolean timedout = false;
7177
7178 synchronized(this) {
7179 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007180 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007181
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007182 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007183 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007184 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007185 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007186 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007187 long delay = endTime - System.currentTimeMillis();
7188 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007189 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007190 timedout = true;
7191 break;
7192 }
7193 try {
7194 this.wait();
7195 } catch (InterruptedException e) {
7196 }
7197 }
7198 }
7199 }
Dianne Hackborna06de0f2012-12-11 16:34:47 -08007200
7201 mAppOpsService.shutdown();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007202 mUsageStatsService.shutdown();
7203 mBatteryStatsService.shutdown();
7204
7205 return timedout;
7206 }
7207
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007208 public final void activitySlept(IBinder token) {
7209 if (localLOGV) Slog.v(
7210 TAG, "Activity slept: token=" + token);
7211
7212 ActivityRecord r = null;
7213
7214 final long origId = Binder.clearCallingIdentity();
7215
7216 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007217 r = mMainStack.isInStackLocked(token);
7218 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007219 mMainStack.activitySleptLocked(r);
7220 }
7221 }
7222
7223 Binder.restoreCallingIdentity(origId);
7224 }
7225
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007226 private void comeOutOfSleepIfNeededLocked() {
7227 if (!mWentToSleep && !mLockScreenShown) {
7228 if (mSleeping) {
7229 mSleeping = false;
7230 mMainStack.awakeFromSleepingLocked();
7231 mMainStack.resumeTopActivityLocked(null);
7232 }
7233 }
7234 }
7235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007236 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007237 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7238 != PackageManager.PERMISSION_GRANTED) {
7239 throw new SecurityException("Requires permission "
7240 + android.Manifest.permission.DEVICE_POWER);
7241 }
7242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007244 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007245 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007246 comeOutOfSleepIfNeededLocked();
7247 }
7248 }
7249
Jeff Brownc042ee22012-05-08 13:03:42 -07007250 private void updateEventDispatchingLocked() {
7251 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7252 }
7253
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007254 public void setLockScreenShown(boolean shown) {
7255 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7256 != PackageManager.PERMISSION_GRANTED) {
7257 throw new SecurityException("Requires permission "
7258 + android.Manifest.permission.DEVICE_POWER);
7259 }
7260
7261 synchronized(this) {
7262 mLockScreenShown = shown;
7263 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007264 }
7265 }
7266
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007267 public void stopAppSwitches() {
7268 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7269 != PackageManager.PERMISSION_GRANTED) {
7270 throw new SecurityException("Requires permission "
7271 + android.Manifest.permission.STOP_APP_SWITCHES);
7272 }
7273
7274 synchronized(this) {
7275 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7276 + APP_SWITCH_DELAY_TIME;
7277 mDidAppSwitch = false;
7278 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7279 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7280 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7281 }
7282 }
7283
7284 public void resumeAppSwitches() {
7285 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7286 != PackageManager.PERMISSION_GRANTED) {
7287 throw new SecurityException("Requires permission "
7288 + android.Manifest.permission.STOP_APP_SWITCHES);
7289 }
7290
7291 synchronized(this) {
7292 // Note that we don't execute any pending app switches... we will
7293 // let those wait until either the timeout, or the next start
7294 // activity request.
7295 mAppSwitchesAllowedTime = 0;
7296 }
7297 }
7298
7299 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7300 String name) {
7301 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7302 return true;
7303 }
7304
7305 final int perm = checkComponentPermission(
7306 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007307 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007308 if (perm == PackageManager.PERMISSION_GRANTED) {
7309 return true;
7310 }
7311
Joe Onorato8a9b2202010-02-26 18:56:32 -08007312 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007313 return false;
7314 }
7315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 public void setDebugApp(String packageName, boolean waitForDebugger,
7317 boolean persistent) {
7318 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7319 "setDebugApp()");
7320
7321 // Note that this is not really thread safe if there are multiple
7322 // callers into it at the same time, but that's not a situation we
7323 // care about.
7324 if (persistent) {
7325 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007326 Settings.Global.putString(
7327 resolver, Settings.Global.DEBUG_APP,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 packageName);
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007329 Settings.Global.putInt(
7330 resolver, Settings.Global.WAIT_FOR_DEBUGGER,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 waitForDebugger ? 1 : 0);
7332 }
7333
7334 synchronized (this) {
7335 if (!persistent) {
7336 mOrigDebugApp = mDebugApp;
7337 mOrigWaitForDebugger = mWaitForDebugger;
7338 }
7339 mDebugApp = packageName;
7340 mWaitForDebugger = waitForDebugger;
7341 mDebugTransient = !persistent;
7342 if (packageName != null) {
7343 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007344 forceStopPackageLocked(packageName, -1, false, false, true, true,
7345 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 Binder.restoreCallingIdentity(origId);
7347 }
7348 }
7349 }
7350
Siva Velusamy92a8b222012-03-09 16:24:04 -08007351 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7352 synchronized (this) {
7353 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7354 if (!isDebuggable) {
7355 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7356 throw new SecurityException("Process not debuggable: " + app.packageName);
7357 }
7358 }
7359
7360 mOpenGlTraceApp = processName;
7361 }
7362 }
7363
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007364 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7365 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7366 synchronized (this) {
7367 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7368 if (!isDebuggable) {
7369 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7370 throw new SecurityException("Process not debuggable: " + app.packageName);
7371 }
7372 }
7373 mProfileApp = processName;
7374 mProfileFile = profileFile;
7375 if (mProfileFd != null) {
7376 try {
7377 mProfileFd.close();
7378 } catch (IOException e) {
7379 }
7380 mProfileFd = null;
7381 }
7382 mProfileFd = profileFd;
7383 mProfileType = 0;
7384 mAutoStopProfiler = autoStopProfiler;
7385 }
7386 }
7387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007388 public void setAlwaysFinish(boolean enabled) {
7389 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7390 "setAlwaysFinish()");
7391
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007392 Settings.Global.putInt(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007393 mContext.getContentResolver(),
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007394 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395
7396 synchronized (this) {
7397 mAlwaysFinishActivities = enabled;
7398 }
7399 }
7400
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007401 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007402 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007403 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007405 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 }
7407 }
7408
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007409 public boolean isUserAMonkey() {
7410 // For now the fact that there is a controller implies
7411 // we have a monkey.
7412 synchronized (this) {
7413 return mController != null;
7414 }
7415 }
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007416
7417 public void requestBugReport() {
7418 // No permission check because this can't do anything harmful --
7419 // it will just eventually cause the user to be presented with
7420 // a UI to select where the bug report goes.
7421 SystemProperties.set("ctl.start", "bugreport");
7422 }
7423
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007424 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7425 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7426 != PackageManager.PERMISSION_GRANTED) {
7427 throw new SecurityException("Requires permission "
7428 + android.Manifest.permission.FILTER_EVENTS);
7429 }
7430
7431 ProcessRecord proc;
7432
7433 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7434 synchronized (this) {
7435 synchronized (mPidsSelfLocked) {
7436 proc = mPidsSelfLocked.get(pid);
7437 }
7438 if (proc != null) {
7439 if (proc.debugging) {
7440 return -1;
7441 }
7442
7443 if (mDidDexOpt) {
7444 // Give more time since we were dexopting.
7445 mDidDexOpt = false;
7446 return -1;
7447 }
7448
7449 if (proc.instrumentationClass != null) {
7450 Bundle info = new Bundle();
7451 info.putString("shortMsg", "keyDispatchingTimedOut");
7452 info.putString("longMsg", "Timed out while dispatching key event");
7453 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7454 proc = null;
7455 }
7456 }
7457 }
7458
7459 if (proc != null) {
7460 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7461 if (proc.instrumentationClass != null || proc.usingWrapper) {
7462 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7463 }
7464 }
7465
7466 return KEY_DISPATCHING_TIMEOUT;
7467 }
7468
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007469 public Bundle getTopActivityExtras(int requestType) {
7470 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7471 "getTopActivityExtras()");
7472 PendingActivityExtras pae;
7473 Bundle extras = new Bundle();
7474 synchronized (this) {
7475 ActivityRecord activity = mMainStack.mResumedActivity;
7476 if (activity == null) {
7477 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7478 return null;
7479 }
7480 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7481 if (activity.app == null || activity.app.thread == null) {
7482 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7483 return extras;
7484 }
7485 if (activity.app.pid == Binder.getCallingPid()) {
7486 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7487 return extras;
7488 }
7489 pae = new PendingActivityExtras(activity);
7490 try {
7491 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7492 mPendingActivityExtras.add(pae);
7493 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7494 } catch (RemoteException e) {
7495 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7496 return extras;
7497 }
7498 }
7499 synchronized (pae) {
7500 while (!pae.haveResult) {
7501 try {
7502 pae.wait();
7503 } catch (InterruptedException e) {
7504 }
7505 }
7506 if (pae.result != null) {
7507 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7508 }
7509 }
7510 synchronized (this) {
7511 mPendingActivityExtras.remove(pae);
7512 mHandler.removeCallbacks(pae);
7513 }
7514 return extras;
7515 }
7516
7517 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7518 PendingActivityExtras pae = (PendingActivityExtras)token;
7519 synchronized (pae) {
7520 pae.result = extras;
7521 pae.haveResult = true;
7522 pae.notifyAll();
7523 }
7524 }
7525
Jeff Sharkeya4620792011-05-20 15:29:23 -07007526 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007527 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7528 "registerProcessObserver()");
7529 synchronized (this) {
7530 mProcessObservers.register(observer);
7531 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007532 }
7533
7534 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007535 synchronized (this) {
7536 mProcessObservers.unregister(observer);
7537 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007538 }
7539
Daniel Sandler69a48172010-06-23 16:29:36 -04007540 public void setImmersive(IBinder token, boolean immersive) {
7541 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007542 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007543 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007544 throw new IllegalArgumentException();
7545 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007546 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007547
7548 // update associated state if we're frontmost
7549 if (r == mFocusedActivity) {
7550 if (DEBUG_IMMERSIVE) {
7551 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7552 }
7553 applyUpdateLockStateLocked(r);
7554 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007555 }
7556 }
7557
7558 public boolean isImmersive(IBinder token) {
7559 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007560 ActivityRecord r = mMainStack.isInStackLocked(token);
7561 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007562 throw new IllegalArgumentException();
7563 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007564 return r.immersive;
7565 }
7566 }
7567
7568 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007569 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007570 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007571 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007572 return (r != null) ? r.immersive : false;
7573 }
7574 }
7575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 public final void enterSafeMode() {
7577 synchronized(this) {
7578 // It only makes sense to do this before the system is ready
7579 // and started launching other packages.
7580 if (!mSystemReady) {
7581 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007582 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 } catch (RemoteException e) {
7584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
7586 }
7587 }
7588
Jeff Brownb09abc12011-01-13 21:08:27 -08007589 public final void showSafeModeOverlay() {
7590 View v = LayoutInflater.from(mContext).inflate(
7591 com.android.internal.R.layout.safe_mode, null);
7592 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7593 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7594 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7595 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007596 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007597 lp.format = v.getBackground().getOpacity();
7598 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7599 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007600 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007601 ((WindowManager)mContext.getSystemService(
7602 Context.WINDOW_SERVICE)).addView(v, lp);
7603 }
7604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 public void noteWakeupAlarm(IIntentSender sender) {
7606 if (!(sender instanceof PendingIntentRecord)) {
7607 return;
7608 }
7609 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7610 synchronized (stats) {
7611 if (mBatteryStatsService.isOnBattery()) {
7612 mBatteryStatsService.enforceCallingPermission();
7613 PendingIntentRecord rec = (PendingIntentRecord)sender;
7614 int MY_UID = Binder.getCallingUid();
7615 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7616 BatteryStatsImpl.Uid.Pkg pkg =
7617 stats.getPackageStatsLocked(uid, rec.key.packageName);
7618 pkg.incWakeupsLocked();
7619 }
7620 }
7621 }
7622
Dianne Hackborn64825172011-03-02 21:32:58 -08007623 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007625 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007627 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 // XXX Note: don't acquire main activity lock here, because the window
7629 // manager calls in with its locks held.
7630
7631 boolean killed = false;
7632 synchronized (mPidsSelfLocked) {
7633 int[] types = new int[pids.length];
7634 int worstType = 0;
7635 for (int i=0; i<pids.length; i++) {
7636 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7637 if (proc != null) {
7638 int type = proc.setAdj;
7639 types[i] = type;
7640 if (type > worstType) {
7641 worstType = type;
7642 }
7643 }
7644 }
7645
Dianne Hackborn64825172011-03-02 21:32:58 -08007646 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007648 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7649 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007650 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007652
7653 // If this is not a secure call, don't let it kill processes that
7654 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007655 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7656 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007657 }
7658
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007659 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 for (int i=0; i<pids.length; i++) {
7661 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7662 if (proc == null) {
7663 continue;
7664 }
7665 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007666 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007667 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007668 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007669 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007671 proc.killedBackground = true;
7672 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 }
7674 }
7675 }
7676 return killed;
7677 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007678
7679 @Override
7680 public boolean killProcessesBelowForeground(String reason) {
7681 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7682 throw new SecurityException("killProcessesBelowForeground() only available to system");
7683 }
7684
7685 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7686 }
7687
7688 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7689 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7690 throw new SecurityException("killProcessesBelowAdj() only available to system");
7691 }
7692
7693 boolean killed = false;
7694 synchronized (mPidsSelfLocked) {
7695 final int size = mPidsSelfLocked.size();
7696 for (int i = 0; i < size; i++) {
7697 final int pid = mPidsSelfLocked.keyAt(i);
7698 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7699 if (proc == null) continue;
7700
7701 final int adj = proc.setAdj;
7702 if (adj > belowAdj && !proc.killedBackground) {
7703 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007704 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7705 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007706 killed = true;
7707 proc.killedBackground = true;
7708 Process.killProcessQuiet(pid);
7709 }
7710 }
7711 }
7712 return killed;
7713 }
7714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 public final void startRunning(String pkg, String cls, String action,
7716 String data) {
7717 synchronized(this) {
7718 if (mStartRunning) {
7719 return;
7720 }
7721 mStartRunning = true;
7722 mTopComponent = pkg != null && cls != null
7723 ? new ComponentName(pkg, cls) : null;
7724 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7725 mTopData = data;
7726 if (!mSystemReady) {
7727 return;
7728 }
7729 }
7730
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007731 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 }
7733
7734 private void retrieveSettings() {
7735 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007736 String debugApp = Settings.Global.getString(
7737 resolver, Settings.Global.DEBUG_APP);
7738 boolean waitForDebugger = Settings.Global.getInt(
7739 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7740 boolean alwaysFinishActivities = Settings.Global.getInt(
7741 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742
7743 Configuration configuration = new Configuration();
7744 Settings.System.getConfiguration(resolver, configuration);
7745
7746 synchronized (this) {
7747 mDebugApp = mOrigDebugApp = debugApp;
7748 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7749 mAlwaysFinishActivities = alwaysFinishActivities;
7750 // This happens before any activities are started, so we can
7751 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007752 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007753 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 }
7755 }
7756
7757 public boolean testIsSystemReady() {
7758 // no need to synchronize(this) just to read & return the value
7759 return mSystemReady;
7760 }
7761
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007762 private static File getCalledPreBootReceiversFile() {
7763 File dataDir = Environment.getDataDirectory();
7764 File systemDir = new File(dataDir, "system");
7765 File fname = new File(systemDir, "called_pre_boots.dat");
7766 return fname;
7767 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007768
7769 static final int LAST_DONE_VERSION = 10000;
7770
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007771 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7772 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7773 File file = getCalledPreBootReceiversFile();
7774 FileInputStream fis = null;
7775 try {
7776 fis = new FileInputStream(file);
7777 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007778 int fvers = dis.readInt();
7779 if (fvers == LAST_DONE_VERSION) {
7780 String vers = dis.readUTF();
7781 String codename = dis.readUTF();
7782 String build = dis.readUTF();
7783 if (android.os.Build.VERSION.RELEASE.equals(vers)
7784 && android.os.Build.VERSION.CODENAME.equals(codename)
7785 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7786 int num = dis.readInt();
7787 while (num > 0) {
7788 num--;
7789 String pkg = dis.readUTF();
7790 String cls = dis.readUTF();
7791 lastDoneReceivers.add(new ComponentName(pkg, cls));
7792 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007793 }
7794 }
7795 } catch (FileNotFoundException e) {
7796 } catch (IOException e) {
7797 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7798 } finally {
7799 if (fis != null) {
7800 try {
7801 fis.close();
7802 } catch (IOException e) {
7803 }
7804 }
7805 }
7806 return lastDoneReceivers;
7807 }
7808
7809 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7810 File file = getCalledPreBootReceiversFile();
7811 FileOutputStream fos = null;
7812 DataOutputStream dos = null;
7813 try {
7814 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7815 fos = new FileOutputStream(file);
7816 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007817 dos.writeInt(LAST_DONE_VERSION);
7818 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007819 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007820 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007821 dos.writeInt(list.size());
7822 for (int i=0; i<list.size(); i++) {
7823 dos.writeUTF(list.get(i).getPackageName());
7824 dos.writeUTF(list.get(i).getClassName());
7825 }
7826 } catch (IOException e) {
7827 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7828 file.delete();
7829 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007830 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007831 if (dos != null) {
7832 try {
7833 dos.close();
7834 } catch (IOException e) {
7835 // TODO Auto-generated catch block
7836 e.printStackTrace();
7837 }
7838 }
7839 }
7840 }
7841
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007842 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 synchronized(this) {
7844 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007845 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 return;
7847 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007848
7849 // Check to see if there are any update receivers to run.
7850 if (!mDidUpdate) {
7851 if (mWaitingUpdate) {
7852 return;
7853 }
7854 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7855 List<ResolveInfo> ris = null;
7856 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007857 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007858 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007859 } catch (RemoteException e) {
7860 }
7861 if (ris != null) {
7862 for (int i=ris.size()-1; i>=0; i--) {
7863 if ((ris.get(i).activityInfo.applicationInfo.flags
7864 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7865 ris.remove(i);
7866 }
7867 }
7868 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007869
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007870 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007871
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007872 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007873 for (int i=0; i<ris.size(); i++) {
7874 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007875 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7876 if (lastDoneReceivers.contains(comp)) {
7877 ris.remove(i);
7878 i--;
7879 }
7880 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007881
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007882 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007883 for (int i=0; i<ris.size(); i++) {
7884 ActivityInfo ai = ris.get(i).activityInfo;
7885 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7886 doneReceivers.add(comp);
7887 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007888 for (int j=0; j<users.length; j++) {
7889 IIntentReceiver finisher = null;
7890 if (i == ris.size()-1 && j == users.length-1) {
7891 finisher = new IIntentReceiver.Stub() {
7892 public void performReceive(Intent intent, int resultCode,
7893 String data, Bundle extras, boolean ordered,
7894 boolean sticky, int sendingUser) {
7895 // The raw IIntentReceiver interface is called
7896 // with the AM lock held, so redispatch to
7897 // execute our code without the lock.
7898 mHandler.post(new Runnable() {
7899 public void run() {
7900 synchronized (ActivityManagerService.this) {
7901 mDidUpdate = true;
7902 }
7903 writeLastDonePreBootReceivers(doneReceivers);
7904 showBootMessage(mContext.getText(
7905 R.string.android_upgrading_complete),
7906 false);
7907 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007908 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007909 });
7910 }
7911 };
7912 }
7913 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7914 + " for user " + users[j]);
7915 broadcastIntentLocked(null, null, intent, null, finisher,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007916 0, null, null, null, AppOpsManager.OP_NONE,
7917 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007918 users[j]);
7919 if (finisher != null) {
7920 mWaitingUpdate = true;
7921 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007922 }
7923 }
7924 }
7925 if (mWaitingUpdate) {
7926 return;
7927 }
7928 mDidUpdate = true;
7929 }
7930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007931 mSystemReady = true;
7932 if (!mStartRunning) {
7933 return;
7934 }
7935 }
7936
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007937 ArrayList<ProcessRecord> procsToKill = null;
7938 synchronized(mPidsSelfLocked) {
7939 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7940 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7941 if (!isAllowedWhileBooting(proc.info)){
7942 if (procsToKill == null) {
7943 procsToKill = new ArrayList<ProcessRecord>();
7944 }
7945 procsToKill.add(proc);
7946 }
7947 }
7948 }
7949
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007950 synchronized(this) {
7951 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007952 for (int i=procsToKill.size()-1; i>=0; i--) {
7953 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007954 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007955 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007956 }
7957 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007958
7959 // Now that we have cleaned up any update processes, we
7960 // are ready to start launching real processes and know that
7961 // we won't trample on them any more.
7962 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007963 }
7964
Joe Onorato8a9b2202010-02-26 18:56:32 -08007965 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007966 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 SystemClock.uptimeMillis());
7968
7969 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007970 // Make sure we have no pre-ready processes sitting around.
7971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7973 ResolveInfo ri = mContext.getPackageManager()
7974 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007975 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 CharSequence errorMsg = null;
7977 if (ri != null) {
7978 ActivityInfo ai = ri.activityInfo;
7979 ApplicationInfo app = ai.applicationInfo;
7980 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7981 mTopAction = Intent.ACTION_FACTORY_TEST;
7982 mTopData = null;
7983 mTopComponent = new ComponentName(app.packageName,
7984 ai.name);
7985 } else {
7986 errorMsg = mContext.getResources().getText(
7987 com.android.internal.R.string.factorytest_not_system);
7988 }
7989 } else {
7990 errorMsg = mContext.getResources().getText(
7991 com.android.internal.R.string.factorytest_no_action);
7992 }
7993 if (errorMsg != null) {
7994 mTopAction = null;
7995 mTopData = null;
7996 mTopComponent = null;
7997 Message msg = Message.obtain();
7998 msg.what = SHOW_FACTORY_ERROR_MSG;
7999 msg.getData().putCharSequence("msg", errorMsg);
8000 mHandler.sendMessage(msg);
8001 }
8002 }
8003 }
8004
8005 retrieveSettings();
8006
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008007 if (goingCallback != null) goingCallback.run();
8008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008009 synchronized (this) {
8010 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8011 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008012 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008013 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 if (apps != null) {
8015 int N = apps.size();
8016 int i;
8017 for (i=0; i<N; i++) {
8018 ApplicationInfo info
8019 = (ApplicationInfo)apps.get(i);
8020 if (info != null &&
8021 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008022 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 }
8024 }
8025 }
8026 } catch (RemoteException ex) {
8027 // pm is in same process, this will never happen.
8028 }
8029 }
8030
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008031 // Start up initial activity.
8032 mBooting = true;
8033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008035 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 Message msg = Message.obtain();
8037 msg.what = SHOW_UID_ERROR_MSG;
8038 mHandler.sendMessage(msg);
8039 }
8040 } catch (RemoteException e) {
8041 }
8042
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008043 long ident = Binder.clearCallingIdentity();
8044 try {
8045 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008046 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
8047 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008048 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8049 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008050 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008051 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008052 intent = new Intent(Intent.ACTION_USER_STARTING);
8053 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8054 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8055 broadcastIntentLocked(null, null, intent,
8056 null, new IIntentReceiver.Stub() {
8057 @Override
8058 public void performReceive(Intent intent, int resultCode, String data,
8059 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
8060 throws RemoteException {
8061 }
8062 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008063 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08008064 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008065 } finally {
8066 Binder.restoreCallingIdentity(ident);
8067 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008068 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008069 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 }
8071 }
8072
Dan Egnorb7f03672009-12-09 16:22:32 -08008073 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008074 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008076 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008077 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 startAppProblemLocked(app);
8079 app.stopFreezingAllLocked();
8080 return handleAppCrashLocked(app);
8081 }
8082
Dan Egnorb7f03672009-12-09 16:22:32 -08008083 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008084 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008085 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008086 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008087 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8088 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008089 startAppProblemLocked(app);
8090 app.stopFreezingAllLocked();
8091 }
8092
8093 /**
8094 * Generate a process error record, suitable for attachment to a ProcessRecord.
8095 *
8096 * @param app The ProcessRecord in which the error occurred.
8097 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8098 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008099 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008100 * @param shortMsg Short message describing the crash.
8101 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008102 * @param stackTrace Full crash stack trace, may be null.
8103 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 * @return Returns a fully-formed AppErrorStateInfo record.
8105 */
8106 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008107 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 report.condition = condition;
8111 report.processName = app.processName;
8112 report.pid = app.pid;
8113 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008114 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 report.shortMsg = shortMsg;
8116 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008117 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008118
8119 return report;
8120 }
8121
Dan Egnor42471dd2010-01-07 17:25:22 -08008122 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008123 synchronized (this) {
8124 app.crashing = false;
8125 app.crashingReport = null;
8126 app.notResponding = false;
8127 app.notRespondingReport = null;
8128 if (app.anrDialog == fromDialog) {
8129 app.anrDialog = null;
8130 }
8131 if (app.waitDialog == fromDialog) {
8132 app.waitDialog = null;
8133 }
8134 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008135 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008136 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008137 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008138 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008139 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008143
Dan Egnorb7f03672009-12-09 16:22:32 -08008144 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008145 if (mHeadless) {
8146 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8147 return false;
8148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 long now = SystemClock.uptimeMillis();
8150
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008151 Long crashTime;
8152 if (!app.isolated) {
8153 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8154 } else {
8155 crashTime = null;
8156 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008157 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008159 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008161 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008162 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008163 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8164 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008166 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008168 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8169 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 }
8171 }
8172 if (!app.persistent) {
8173 // We don't want to start this process again until the user
8174 // explicitly does so... but for persistent process, we really
8175 // need to keep it running. If a persistent process is actually
8176 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008177 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008178 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008179 if (!app.isolated) {
8180 // XXX We don't have a way to mark isolated processes
8181 // as bad, since they don't have a peristent identity.
8182 mBadProcesses.put(app.info.processName, app.uid, now);
8183 mProcessCrashTimes.remove(app.info.processName, app.uid);
8184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008187 // Don't let services in this process be restarted and potentially
8188 // annoy the user repeatedly. Unless it is persistent, since those
8189 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008190 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008191 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 return false;
8193 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008194 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008195 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008196 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008197 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008198 // If the top running activity is from this crashing
8199 // process, then terminate it to avoid getting in a loop.
8200 Slog.w(TAG, " Force finishing activity "
8201 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008202 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008203 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008204 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008205 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008206 // stopped, to avoid a situation where one will get
8207 // re-start our crashing activity once it gets resumed again.
8208 index--;
8209 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008210 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008211 if (r.state == ActivityState.RESUMED
8212 || r.state == ActivityState.PAUSING
8213 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008214 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008215 Slog.w(TAG, " Force finishing activity "
8216 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008217 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008218 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008219 }
8220 }
8221 }
8222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 }
8224
8225 // Bump up the crash count of any services currently running in the proc.
8226 if (app.services.size() != 0) {
8227 // Any services running in the application need to be placed
8228 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008229 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008230 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008231 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 sr.crashCount++;
8233 }
8234 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008235
8236 // If the crashing process is what we consider to be the "home process" and it has been
8237 // replaced by a third-party app, clear the package preferred activities from packages
8238 // with a home activity running in the process to prevent a repeatedly crashing app
8239 // from blocking the user to manually clear the list.
8240 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8241 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8242 Iterator it = mHomeProcess.activities.iterator();
8243 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008244 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008245 if (r.isHomeActivity) {
8246 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8247 try {
8248 ActivityThread.getPackageManager()
8249 .clearPackagePreferredActivities(r.packageName);
8250 } catch (RemoteException c) {
8251 // pm is in same process, this will never happen.
8252 }
8253 }
8254 }
8255 }
8256
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008257 if (!app.isolated) {
8258 // XXX Can't keep track of crash times for isolated processes,
8259 // because they don't have a perisistent identity.
8260 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8261 }
8262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008263 return true;
8264 }
8265
8266 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008267 if (app.userId == mCurrentUserId) {
8268 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8269 mContext, app.info.packageName, app.info.flags);
8270 } else {
8271 // If this app is not running under the current user, then we
8272 // can't give it a report button because that would require
8273 // launching the report UI under a different user.
8274 app.errorReportReceiver = null;
8275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 skipCurrentReceiverLocked(app);
8277 }
8278
8279 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008280 for (BroadcastQueue queue : mBroadcastQueues) {
8281 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 }
8283 }
8284
Dan Egnor60d87622009-12-16 16:32:58 -08008285 /**
8286 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8287 * The application process will exit immediately after this call returns.
8288 * @param app object of the crashing app, null for the system server
8289 * @param crashInfo describing the exception
8290 */
8291 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008292 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008293 final String processName = app == null ? "system_server"
8294 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008295
8296 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008297 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008298 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008299 crashInfo.exceptionClassName,
8300 crashInfo.exceptionMessage,
8301 crashInfo.throwFileName,
8302 crashInfo.throwLineNumber);
8303
Jeff Sharkeya353d262011-10-28 11:12:06 -07008304 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008305
8306 crashApplication(r, crashInfo);
8307 }
8308
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008309 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008310 IBinder app,
8311 int violationMask,
8312 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008313 ProcessRecord r = findAppProcess(app, "StrictMode");
8314 if (r == null) {
8315 return;
8316 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008317
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008318 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008319 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008320 boolean logIt = true;
8321 synchronized (mAlreadyLoggedViolatedStacks) {
8322 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8323 logIt = false;
8324 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008325 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008326 // the relative pain numbers, without logging all
8327 // the stack traces repeatedly. We'd want to do
8328 // likewise in the client code, which also does
8329 // dup suppression, before the Binder call.
8330 } else {
8331 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8332 mAlreadyLoggedViolatedStacks.clear();
8333 }
8334 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8335 }
8336 }
8337 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008338 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008339 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008340 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008341
8342 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8343 AppErrorResult result = new AppErrorResult();
8344 synchronized (this) {
8345 final long origId = Binder.clearCallingIdentity();
8346
8347 Message msg = Message.obtain();
8348 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8349 HashMap<String, Object> data = new HashMap<String, Object>();
8350 data.put("result", result);
8351 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008352 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008353 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008354 msg.obj = data;
8355 mHandler.sendMessage(msg);
8356
8357 Binder.restoreCallingIdentity(origId);
8358 }
8359 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008360 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008361 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008362 }
8363
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008364 // Depending on the policy in effect, there could be a bunch of
8365 // these in quick succession so we try to batch these together to
8366 // minimize disk writes, number of dropbox entries, and maximize
8367 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008368 private void logStrictModeViolationToDropBox(
8369 ProcessRecord process,
8370 StrictMode.ViolationInfo info) {
8371 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008372 return;
8373 }
8374 final boolean isSystemApp = process == null ||
8375 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8376 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008377 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008378 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8379 final DropBoxManager dbox = (DropBoxManager)
8380 mContext.getSystemService(Context.DROPBOX_SERVICE);
8381
8382 // Exit early if the dropbox isn't configured to accept this report type.
8383 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8384
8385 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008386 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008387 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8388 synchronized (sb) {
8389 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008390 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008391 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8392 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008393 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8394 if (info.violationNumThisLoop != 0) {
8395 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8396 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008397 if (info.numAnimationsRunning != 0) {
8398 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8399 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008400 if (info.broadcastIntentAction != null) {
8401 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8402 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008403 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008404 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008405 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008406 if (info.numInstances != -1) {
8407 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8408 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008409 if (info.tags != null) {
8410 for (String tag : info.tags) {
8411 sb.append("Span-Tag: ").append(tag).append("\n");
8412 }
8413 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008414 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008415 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8416 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008417 }
8418 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008419
8420 // Only buffer up to ~64k. Various logging bits truncate
8421 // things at 128k.
8422 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008423 }
8424
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008425 // Flush immediately if the buffer's grown too large, or this
8426 // is a non-system app. Non-system apps are isolated with a
8427 // different tag & policy and not batched.
8428 //
8429 // Batching is useful during internal testing with
8430 // StrictMode settings turned up high. Without batching,
8431 // thousands of separate files could be created on boot.
8432 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008433 new Thread("Error dump: " + dropboxTag) {
8434 @Override
8435 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008436 String report;
8437 synchronized (sb) {
8438 report = sb.toString();
8439 sb.delete(0, sb.length());
8440 sb.trimToSize();
8441 }
8442 if (report.length() != 0) {
8443 dbox.addText(dropboxTag, report);
8444 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008445 }
8446 }.start();
8447 return;
8448 }
8449
8450 // System app batching:
8451 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008452 // An existing dropbox-writing thread is outstanding, so
8453 // we don't need to start it up. The existing thread will
8454 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008455 return;
8456 }
8457
8458 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8459 // (After this point, we shouldn't access AMS internal data structures.)
8460 new Thread("Error dump: " + dropboxTag) {
8461 @Override
8462 public void run() {
8463 // 5 second sleep to let stacks arrive and be batched together
8464 try {
8465 Thread.sleep(5000); // 5 seconds
8466 } catch (InterruptedException e) {}
8467
8468 String errorReport;
8469 synchronized (mStrictModeBuffer) {
8470 errorReport = mStrictModeBuffer.toString();
8471 if (errorReport.length() == 0) {
8472 return;
8473 }
8474 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8475 mStrictModeBuffer.trimToSize();
8476 }
8477 dbox.addText(dropboxTag, errorReport);
8478 }
8479 }.start();
8480 }
8481
Dan Egnor60d87622009-12-16 16:32:58 -08008482 /**
8483 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8484 * @param app object of the crashing app, null for the system server
8485 * @param tag reported by the caller
8486 * @param crashInfo describing the context of the error
8487 * @return true if the process should exit immediately (WTF is fatal)
8488 */
8489 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008490 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008491 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008492 final String processName = app == null ? "system_server"
8493 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008494
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008495 EventLog.writeEvent(EventLogTags.AM_WTF,
8496 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008497 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008498 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008499 tag, crashInfo.exceptionMessage);
8500
Jeff Sharkeya353d262011-10-28 11:12:06 -07008501 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008502
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008503 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008504 Settings.Global.getInt(mContext.getContentResolver(),
8505 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008506 crashApplication(r, crashInfo);
8507 return true;
8508 } else {
8509 return false;
8510 }
8511 }
8512
8513 /**
8514 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8515 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8516 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008517 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008518 if (app == null) {
8519 return null;
8520 }
8521
8522 synchronized (this) {
8523 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8524 final int NA = apps.size();
8525 for (int ia=0; ia<NA; ia++) {
8526 ProcessRecord p = apps.valueAt(ia);
8527 if (p.thread != null && p.thread.asBinder() == app) {
8528 return p;
8529 }
8530 }
8531 }
8532
Dianne Hackborncb44d962011-03-10 17:02:27 -08008533 Slog.w(TAG, "Can't find mystery application for " + reason
8534 + " from pid=" + Binder.getCallingPid()
8535 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008536 return null;
8537 }
8538 }
8539
8540 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008541 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8542 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008543 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008544 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8545 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008546 // Watchdog thread ends up invoking this function (with
8547 // a null ProcessRecord) to add the stack file to dropbox.
8548 // Do not acquire a lock on this (am) in such cases, as it
8549 // could cause a potential deadlock, if and when watchdog
8550 // is invoked due to unavailability of lock on am and it
8551 // would prevent watchdog from killing system_server.
8552 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008553 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008554 return;
8555 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008556 // Note: ProcessRecord 'process' is guarded by the service
8557 // instance. (notably process.pkgList, which could otherwise change
8558 // concurrently during execution of this method)
8559 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008560 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008561 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008562 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008563 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8564 for (String pkg : process.pkgList) {
8565 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008566 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008567 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008568 if (pi != null) {
8569 sb.append(" v").append(pi.versionCode);
8570 if (pi.versionName != null) {
8571 sb.append(" (").append(pi.versionName).append(")");
8572 }
8573 }
8574 } catch (RemoteException e) {
8575 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008576 }
Dan Egnora455d192010-03-12 08:52:28 -08008577 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008578 }
Dan Egnora455d192010-03-12 08:52:28 -08008579 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008580 }
8581
8582 private static String processClass(ProcessRecord process) {
8583 if (process == null || process.pid == MY_PID) {
8584 return "system_server";
8585 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8586 return "system_app";
8587 } else {
8588 return "data_app";
8589 }
8590 }
8591
8592 /**
8593 * Write a description of an error (crash, WTF, ANR) to the drop box.
8594 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8595 * @param process which caused the error, null means the system server
8596 * @param activity which triggered the error, null if unknown
8597 * @param parent activity related to the error, null if unknown
8598 * @param subject line related to the error, null if absent
8599 * @param report in long form describing the error, null if absent
8600 * @param logFile to include in the report, null if none
8601 * @param crashInfo giving an application stack trace, null if absent
8602 */
8603 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008604 ProcessRecord process, String processName, ActivityRecord activity,
8605 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008606 final String report, final File logFile,
8607 final ApplicationErrorReport.CrashInfo crashInfo) {
8608 // NOTE -- this must never acquire the ActivityManagerService lock,
8609 // otherwise the watchdog may be prevented from resetting the system.
8610
8611 final String dropboxTag = processClass(process) + "_" + eventType;
8612 final DropBoxManager dbox = (DropBoxManager)
8613 mContext.getSystemService(Context.DROPBOX_SERVICE);
8614
8615 // Exit early if the dropbox isn't configured to accept this report type.
8616 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8617
8618 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008619 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008620 if (activity != null) {
8621 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8622 }
8623 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8624 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8625 }
8626 if (parent != null && parent != activity) {
8627 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8628 }
8629 if (subject != null) {
8630 sb.append("Subject: ").append(subject).append("\n");
8631 }
8632 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008633 if (Debug.isDebuggerConnected()) {
8634 sb.append("Debugger: Connected\n");
8635 }
Dan Egnora455d192010-03-12 08:52:28 -08008636 sb.append("\n");
8637
8638 // Do the rest in a worker thread to avoid blocking the caller on I/O
8639 // (After this point, we shouldn't access AMS internal data structures.)
8640 Thread worker = new Thread("Error dump: " + dropboxTag) {
8641 @Override
8642 public void run() {
8643 if (report != null) {
8644 sb.append(report);
8645 }
8646 if (logFile != null) {
8647 try {
8648 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8649 } catch (IOException e) {
8650 Slog.e(TAG, "Error reading " + logFile, e);
8651 }
8652 }
8653 if (crashInfo != null && crashInfo.stackTrace != null) {
8654 sb.append(crashInfo.stackTrace);
8655 }
8656
Jeff Sharkey625239a2012-09-26 22:03:49 -07008657 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8658 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008659 if (lines > 0) {
8660 sb.append("\n");
8661
8662 // Merge several logcat streams, and take the last N lines
8663 InputStreamReader input = null;
8664 try {
8665 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8666 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8667 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8668
8669 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8670 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8671 input = new InputStreamReader(logcat.getInputStream());
8672
8673 int num;
8674 char[] buf = new char[8192];
8675 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8676 } catch (IOException e) {
8677 Slog.e(TAG, "Error running logcat", e);
8678 } finally {
8679 if (input != null) try { input.close(); } catch (IOException e) {}
8680 }
8681 }
8682
8683 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008684 }
Dan Egnora455d192010-03-12 08:52:28 -08008685 };
8686
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008687 if (process == null) {
8688 // If process is null, we are being called from some internal code
8689 // and may be about to die -- run this synchronously.
8690 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008691 } else {
8692 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008693 }
8694 }
8695
8696 /**
8697 * Bring up the "unexpected error" dialog box for a crashing app.
8698 * Deal with edge cases (intercepts from instrumented applications,
8699 * ActivityController, error intent receivers, that sort of thing).
8700 * @param r the application crashing
8701 * @param crashInfo describing the failure
8702 */
8703 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008704 long timeMillis = System.currentTimeMillis();
8705 String shortMsg = crashInfo.exceptionClassName;
8706 String longMsg = crashInfo.exceptionMessage;
8707 String stackTrace = crashInfo.stackTrace;
8708 if (shortMsg != null && longMsg != null) {
8709 longMsg = shortMsg + ": " + longMsg;
8710 } else if (shortMsg != null) {
8711 longMsg = shortMsg;
8712 }
8713
Dan Egnor60d87622009-12-16 16:32:58 -08008714 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008715 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008716 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717 try {
8718 String name = r != null ? r.processName : null;
8719 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008720 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008721 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008722 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 + " at watcher's request");
8724 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008725 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 }
8727 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008728 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008729 }
8730 }
8731
8732 final long origId = Binder.clearCallingIdentity();
8733
8734 // If this process is running instrumentation, finish it.
8735 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008736 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008738 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8739 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008740 Bundle info = new Bundle();
8741 info.putString("shortMsg", shortMsg);
8742 info.putString("longMsg", longMsg);
8743 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8744 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008745 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 }
8747
Dan Egnor60d87622009-12-16 16:32:58 -08008748 // If we can't identify the process or it's already exceeded its crash quota,
8749 // quit right away without showing a crash dialog.
8750 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008752 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 }
8754
8755 Message msg = Message.obtain();
8756 msg.what = SHOW_ERROR_MSG;
8757 HashMap data = new HashMap();
8758 data.put("result", result);
8759 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760 msg.obj = data;
8761 mHandler.sendMessage(msg);
8762
8763 Binder.restoreCallingIdentity(origId);
8764 }
8765
8766 int res = result.get();
8767
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008768 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008770 if (r != null && !r.isolated) {
8771 // XXX Can't keep track of crash time for isolated processes,
8772 // since they don't have a persistent identity.
8773 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 SystemClock.uptimeMillis());
8775 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008776 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008777 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008778 }
8779 }
8780
8781 if (appErrorIntent != null) {
8782 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008783 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008784 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008785 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008789
8790 Intent createAppErrorIntentLocked(ProcessRecord r,
8791 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8792 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008793 if (report == null) {
8794 return null;
8795 }
8796 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8797 result.setComponent(r.errorReportReceiver);
8798 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8799 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8800 return result;
8801 }
8802
Dan Egnorb7f03672009-12-09 16:22:32 -08008803 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8804 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008805 if (r.errorReportReceiver == null) {
8806 return null;
8807 }
8808
8809 if (!r.crashing && !r.notResponding) {
8810 return null;
8811 }
8812
Dan Egnorb7f03672009-12-09 16:22:32 -08008813 ApplicationErrorReport report = new ApplicationErrorReport();
8814 report.packageName = r.info.packageName;
8815 report.installerPackageName = r.errorReportReceiver.getPackageName();
8816 report.processName = r.processName;
8817 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008818 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008819
Dan Egnorb7f03672009-12-09 16:22:32 -08008820 if (r.crashing) {
8821 report.type = ApplicationErrorReport.TYPE_CRASH;
8822 report.crashInfo = crashInfo;
8823 } else if (r.notResponding) {
8824 report.type = ApplicationErrorReport.TYPE_ANR;
8825 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008826
Dan Egnorb7f03672009-12-09 16:22:32 -08008827 report.anrInfo.activity = r.notRespondingReport.tag;
8828 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8829 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008830 }
8831
Dan Egnorb7f03672009-12-09 16:22:32 -08008832 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008833 }
8834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008835 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008836 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 // assume our apps are happy - lazy create the list
8838 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8839
Dianne Hackborn0c380492012-08-20 17:23:30 -07008840 final boolean allUsers = ActivityManager.checkUidPermission(
8841 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8842 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8843 int userId = UserHandle.getUserId(Binder.getCallingUid());
8844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 synchronized (this) {
8846
8847 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008848 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8849 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008850 if (!allUsers && app.userId != userId) {
8851 continue;
8852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8854 // This one's in trouble, so we'll generate a report for it
8855 // crashes are higher priority (in case there's a crash *and* an anr)
8856 ActivityManager.ProcessErrorStateInfo report = null;
8857 if (app.crashing) {
8858 report = app.crashingReport;
8859 } else if (app.notResponding) {
8860 report = app.notRespondingReport;
8861 }
8862
8863 if (report != null) {
8864 if (errList == null) {
8865 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8866 }
8867 errList.add(report);
8868 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008869 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 " crashing = " + app.crashing +
8871 " notResponding = " + app.notResponding);
8872 }
8873 }
8874 }
8875 }
8876
8877 return errList;
8878 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008879
8880 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008881 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008882 if (currApp != null) {
8883 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8884 }
8885 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008886 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8887 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008888 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8889 if (currApp != null) {
8890 currApp.lru = 0;
8891 }
8892 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008893 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008894 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8895 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8896 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8897 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8898 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8899 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8900 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8901 } else {
8902 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8903 }
8904 }
8905
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008906 private void fillInProcMemInfo(ProcessRecord app,
8907 ActivityManager.RunningAppProcessInfo outInfo) {
8908 outInfo.pid = app.pid;
8909 outInfo.uid = app.info.uid;
8910 if (mHeavyWeightProcess == app) {
8911 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8912 }
8913 if (app.persistent) {
8914 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8915 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008916 if (app.hasActivities) {
8917 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8918 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008919 outInfo.lastTrimLevel = app.trimMemoryLevel;
8920 int adj = app.curAdj;
8921 outInfo.importance = oomAdjToImportance(adj, outInfo);
8922 outInfo.importanceReasonCode = app.adjTypeCode;
8923 }
8924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008926 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 // Lazy instantiation of list
8928 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008929 final boolean allUsers = ActivityManager.checkUidPermission(
8930 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8931 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8932 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 synchronized (this) {
8934 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008935 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8936 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008937 if (!allUsers && app.userId != userId) {
8938 continue;
8939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8941 // Generate process state info for running application
8942 ActivityManager.RunningAppProcessInfo currApp =
8943 new ActivityManager.RunningAppProcessInfo(app.processName,
8944 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008945 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008946 if (app.adjSource instanceof ProcessRecord) {
8947 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008948 currApp.importanceReasonImportance = oomAdjToImportance(
8949 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008950 } else if (app.adjSource instanceof ActivityRecord) {
8951 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008952 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8953 }
8954 if (app.adjTarget instanceof ComponentName) {
8955 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8956 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008957 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 // + " lru=" + currApp.lru);
8959 if (runList == null) {
8960 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8961 }
8962 runList.add(currApp);
8963 }
8964 }
8965 }
8966 return runList;
8967 }
8968
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008969 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008970 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008971 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8972 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8973 if (runningApps != null && runningApps.size() > 0) {
8974 Set<String> extList = new HashSet<String>();
8975 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8976 if (app.pkgList != null) {
8977 for (String pkg : app.pkgList) {
8978 extList.add(pkg);
8979 }
8980 }
8981 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008982 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008983 for (String pkg : extList) {
8984 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008985 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008986 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8987 retList.add(info);
8988 }
8989 } catch (RemoteException e) {
8990 }
8991 }
8992 }
8993 return retList;
8994 }
8995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008997 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8998 enforceNotIsolatedCaller("getMyMemoryState");
8999 synchronized (this) {
9000 ProcessRecord proc;
9001 synchronized (mPidsSelfLocked) {
9002 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9003 }
9004 fillInProcMemInfo(proc, outInfo);
9005 }
9006 }
9007
9008 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009009 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 if (checkCallingPermission(android.Manifest.permission.DUMP)
9011 != PackageManager.PERMISSION_GRANTED) {
9012 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9013 + Binder.getCallingPid()
9014 + ", uid=" + Binder.getCallingUid()
9015 + " without permission "
9016 + android.Manifest.permission.DUMP);
9017 return;
9018 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009019
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009022 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023
9024 int opti = 0;
9025 while (opti < args.length) {
9026 String opt = args[opti];
9027 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9028 break;
9029 }
9030 opti++;
9031 if ("-a".equals(opt)) {
9032 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009033 } else if ("-c".equals(opt)) {
9034 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009035 } else if ("-h".equals(opt)) {
9036 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009037 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009038 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009039 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009040 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009041 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
9042 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009043 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009044 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08009045 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009046 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009047 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009048 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009049 pw.println(" all: dump all activities");
9050 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009052 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
9053 pw.println(" a partial substring in a component name, a");
9054 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009055 pw.println(" -a: include all available server state.");
9056 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 } else {
9059 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009061 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009062
9063 long origId = Binder.clearCallingIdentity();
9064 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009065 // Is the caller requesting to dump a particular piece of data?
9066 if (opti < args.length) {
9067 String cmd = args[opti];
9068 opti++;
9069 if ("activities".equals(cmd) || "a".equals(cmd)) {
9070 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009071 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009074 String[] newArgs;
9075 String name;
9076 if (opti >= args.length) {
9077 name = null;
9078 newArgs = EMPTY_STRING_ARRAY;
9079 } else {
9080 name = args[opti];
9081 opti++;
9082 newArgs = new String[args.length - opti];
9083 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9084 args.length - opti);
9085 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009087 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009090 String[] newArgs;
9091 String name;
9092 if (opti >= args.length) {
9093 name = null;
9094 newArgs = EMPTY_STRING_ARRAY;
9095 } else {
9096 name = args[opti];
9097 opti++;
9098 newArgs = new String[args.length - opti];
9099 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9100 args.length - opti);
9101 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009102 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009103 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009105 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009106 String[] newArgs;
9107 String name;
9108 if (opti >= args.length) {
9109 name = null;
9110 newArgs = EMPTY_STRING_ARRAY;
9111 } else {
9112 name = args[opti];
9113 opti++;
9114 newArgs = new String[args.length - opti];
9115 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9116 args.length - opti);
9117 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009118 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009119 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009120 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009121 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9122 synchronized (this) {
9123 dumpOomLocked(fd, pw, args, opti, true);
9124 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009125 } else if ("provider".equals(cmd)) {
9126 String[] newArgs;
9127 String name;
9128 if (opti >= args.length) {
9129 name = null;
9130 newArgs = EMPTY_STRING_ARRAY;
9131 } else {
9132 name = args[opti];
9133 opti++;
9134 newArgs = new String[args.length - opti];
9135 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9136 }
9137 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9138 pw.println("No providers match: " + name);
9139 pw.println("Use -h for help.");
9140 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009141 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9142 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009143 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009144 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009146 String[] newArgs;
9147 String name;
9148 if (opti >= args.length) {
9149 name = null;
9150 newArgs = EMPTY_STRING_ARRAY;
9151 } else {
9152 name = args[opti];
9153 opti++;
9154 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009155 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9156 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009158 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 pw.println("No services match: " + name);
9160 pw.println("Use -h for help.");
9161 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009162 } else if ("package".equals(cmd)) {
9163 String[] newArgs;
9164 if (opti >= args.length) {
9165 pw.println("package: no package name specified");
9166 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009167 } else {
9168 dumpPackage = args[opti];
9169 opti++;
9170 newArgs = new String[args.length - opti];
9171 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9172 args.length - opti);
9173 args = newArgs;
9174 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009175 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9178 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009179 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009181 } else {
9182 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009183 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9184 pw.println("Bad activity command, or no activities match: " + cmd);
9185 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009186 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009187 }
9188 if (!more) {
9189 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009190 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009192 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009193
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 // No piece of data specified, dump everything.
9195 synchronized (this) {
9196 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009197 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009198 if (needSep) {
9199 pw.println(" ");
9200 }
9201 if (dumpAll) {
9202 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009203 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009204 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009205 if (needSep) {
9206 pw.println(" ");
9207 }
9208 if (dumpAll) {
9209 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009211 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009212 if (needSep) {
9213 pw.println(" ");
9214 }
9215 if (dumpAll) {
9216 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009218 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009219 if (needSep) {
9220 pw.println(" ");
9221 }
9222 if (dumpAll) {
9223 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009224 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009225 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009226 if (needSep) {
9227 pw.println(" ");
9228 }
9229 if (dumpAll) {
9230 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009231 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009232 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009234 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009235 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009236
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009237 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009238 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9240 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009241 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9242 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 pw.println(" ");
9244 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009245 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9246 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009247 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009249 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009250 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009251 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009252 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009253 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009255 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009256 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009257 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009258 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009259 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9260 pw.println(" ");
9261 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009262 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009264 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009265 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009266 pw.println(" ");
9267 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009268 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009273 if (mMainStack.mPausingActivity != null) {
9274 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009275 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009276 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009278 if (dumpAll) {
9279 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9280 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009281 pw.println(" mDismissKeyguardOnNextActivity: "
9282 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009284
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009285 if (mRecentTasks.size() > 0) {
9286 pw.println();
9287 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009288
9289 final int N = mRecentTasks.size();
9290 for (int i=0; i<N; i++) {
9291 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009292 if (dumpPackage != null) {
9293 if (tr.realActivity == null ||
9294 !dumpPackage.equals(tr.realActivity)) {
9295 continue;
9296 }
9297 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009298 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9299 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009300 if (dumpAll) {
9301 mRecentTasks.get(i).dump(pw, " ");
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 }
9304 }
9305
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009306 if (dumpAll) {
9307 pw.println(" ");
9308 pw.println(" mCurTask: " + mCurTask);
9309 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009310
9311 return true;
9312 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009313
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009314 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009315 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 boolean needSep = false;
9317 int numPers = 0;
9318
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009319 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9320
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009321 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009322 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9323 final int NA = procs.size();
9324 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009325 ProcessRecord r = procs.valueAt(ia);
9326 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9327 continue;
9328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009329 if (!needSep) {
9330 pw.println(" All known processes:");
9331 needSep = true;
9332 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009333 pw.print(r.persistent ? " *PERS*" : " *APP*");
9334 pw.print(" UID "); pw.print(procs.keyAt(ia));
9335 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009336 r.dump(pw, " ");
9337 if (r.persistent) {
9338 numPers++;
9339 }
9340 }
9341 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009342 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009343
9344 if (mIsolatedProcesses.size() > 0) {
9345 if (needSep) pw.println(" ");
9346 needSep = true;
9347 pw.println(" Isolated process list (sorted by uid):");
9348 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9349 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9350 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9351 continue;
9352 }
9353 pw.println(String.format("%sIsolated #%2d: %s",
9354 " ", i, r.toString()));
9355 }
9356 }
9357
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009358 if (mLruProcesses.size() > 0) {
9359 if (needSep) pw.println(" ");
9360 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009361 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009362 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009363 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009364 needSep = true;
9365 }
9366
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009367 if (dumpAll) {
9368 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009369 boolean printed = false;
9370 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9371 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9372 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9373 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009374 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009375 if (!printed) {
9376 if (needSep) pw.println(" ");
9377 needSep = true;
9378 pw.println(" PID mappings:");
9379 printed = true;
9380 }
9381 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9382 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 }
9384 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009385 }
9386
9387 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009388 synchronized (mPidsSelfLocked) {
9389 boolean printed = false;
9390 for (int i=0; i<mForegroundProcesses.size(); i++) {
9391 ProcessRecord r = mPidsSelfLocked.get(
9392 mForegroundProcesses.valueAt(i).pid);
9393 if (dumpPackage != null && (r == null
9394 || !dumpPackage.equals(r.info.packageName))) {
9395 continue;
9396 }
9397 if (!printed) {
9398 if (needSep) pw.println(" ");
9399 needSep = true;
9400 pw.println(" Foreground Processes:");
9401 printed = true;
9402 }
9403 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9404 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009407 }
9408
9409 if (mPersistentStartingProcesses.size() > 0) {
9410 if (needSep) pw.println(" ");
9411 needSep = true;
9412 pw.println(" Persisent processes that are starting:");
9413 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009414 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009416
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009417 if (mRemovedProcesses.size() > 0) {
9418 if (needSep) pw.println(" ");
9419 needSep = true;
9420 pw.println(" Processes that are being removed:");
9421 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009422 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009423 }
9424
9425 if (mProcessesOnHold.size() > 0) {
9426 if (needSep) pw.println(" ");
9427 needSep = true;
9428 pw.println(" Processes that are on old until the system is ready:");
9429 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009430 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009432
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009433 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009434
9435 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009436 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009437 long now = SystemClock.uptimeMillis();
9438 for (Map.Entry<String, SparseArray<Long>> procs
9439 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009440 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009441 SparseArray<Long> uids = procs.getValue();
9442 final int N = uids.size();
9443 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009444 int puid = uids.keyAt(i);
9445 ProcessRecord r = mProcessNames.get(pname, puid);
9446 if (dumpPackage != null && (r == null
9447 || !dumpPackage.equals(r.info.packageName))) {
9448 continue;
9449 }
9450 if (!printed) {
9451 if (needSep) pw.println(" ");
9452 needSep = true;
9453 pw.println(" Time since processes crashed:");
9454 printed = true;
9455 }
9456 pw.print(" Process "); pw.print(pname);
9457 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009458 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009459 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9460 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009461 }
9462 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009465 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009466 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009467 for (Map.Entry<String, SparseArray<Long>> procs
9468 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009469 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009470 SparseArray<Long> uids = procs.getValue();
9471 final int N = uids.size();
9472 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009473 int puid = uids.keyAt(i);
9474 ProcessRecord r = mProcessNames.get(pname, puid);
9475 if (dumpPackage != null && (r == null
9476 || !dumpPackage.equals(r.info.packageName))) {
9477 continue;
9478 }
9479 if (!printed) {
9480 if (needSep) pw.println(" ");
9481 needSep = true;
9482 pw.println(" Bad processes:");
9483 }
9484 pw.print(" Bad process "); pw.print(pname);
9485 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009486 pw.print(": crashed at time ");
9487 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009488 }
9489 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009491
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009492 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009493 pw.println(" mStartedUsers:");
9494 for (int i=0; i<mStartedUsers.size(); i++) {
9495 UserStartedState uss = mStartedUsers.valueAt(i);
9496 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009497 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009498 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009499 pw.print(" mStartedUserArray: [");
9500 for (int i=0; i<mStartedUserArray.length; i++) {
9501 if (i > 0) pw.print(", ");
9502 pw.print(mStartedUserArray[i]);
9503 }
9504 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009505 pw.print(" mUserLru: [");
9506 for (int i=0; i<mUserLru.size(); i++) {
9507 if (i > 0) pw.print(", ");
9508 pw.print(mUserLru.get(i));
9509 }
9510 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009511 if (dumpAll) {
9512 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9513 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009514 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009515 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009516 if (dumpAll) {
9517 StringBuilder sb = new StringBuilder(128);
9518 sb.append(" mPreviousProcessVisibleTime: ");
9519 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9520 pw.println(sb);
9521 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009522 if (mHeavyWeightProcess != null) {
9523 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9524 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009526 if (dumpAll) {
9527 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009528 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009530 for (Map.Entry<String, Integer> entry
9531 : mCompatModePackages.getPackages().entrySet()) {
9532 String pkg = entry.getKey();
9533 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009534 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9535 continue;
9536 }
9537 if (!printed) {
9538 pw.println(" mScreenCompatPackages:");
9539 printed = true;
9540 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009541 pw.print(" "); pw.print(pkg); pw.print(": ");
9542 pw.print(mode); pw.println();
9543 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009544 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009545 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009546 if (mSleeping || mWentToSleep || mLockScreenShown) {
9547 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9548 + " mLockScreenShown " + mLockScreenShown);
9549 }
9550 if (mShuttingDown) {
9551 pw.println(" mShuttingDown=" + mShuttingDown);
9552 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009553 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9554 || mOrigWaitForDebugger) {
9555 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9556 + " mDebugTransient=" + mDebugTransient
9557 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9558 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009559 if (mOpenGlTraceApp != null) {
9560 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9561 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009562 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9563 || mProfileFd != null) {
9564 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9565 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9566 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9567 + mAutoStopProfiler);
9568 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 if (mAlwaysFinishActivities || mController != null) {
9570 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9571 + " mController=" + mController);
9572 }
9573 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009576 + " mProcessesReady=" + mProcessesReady
9577 + " mSystemReady=" + mSystemReady);
9578 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009579 + " mBooted=" + mBooted
9580 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009581 pw.print(" mLastPowerCheckRealtime=");
9582 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9583 pw.println("");
9584 pw.print(" mLastPowerCheckUptime=");
9585 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9586 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009587 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9588 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009589 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009590 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9591 + " mNumHiddenProcs=" + mNumHiddenProcs
9592 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009593 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009595
9596 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 }
9598
Dianne Hackborn287952c2010-09-22 22:34:31 -07009599 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009600 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009601 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009603 long now = SystemClock.uptimeMillis();
9604 for (int i=0; i<mProcessesToGc.size(); i++) {
9605 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009606 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9607 continue;
9608 }
9609 if (!printed) {
9610 if (needSep) pw.println(" ");
9611 needSep = true;
9612 pw.println(" Processes that are waiting to GC:");
9613 printed = true;
9614 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009615 pw.print(" Process "); pw.println(proc);
9616 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9617 pw.print(", last gced=");
9618 pw.print(now-proc.lastRequestedGc);
9619 pw.print(" ms ago, last lowMem=");
9620 pw.print(now-proc.lastLowMemory);
9621 pw.println(" ms ago");
9622
9623 }
9624 }
9625 return needSep;
9626 }
9627
9628 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9629 int opti, boolean dumpAll) {
9630 boolean needSep = false;
9631
9632 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009633 if (needSep) pw.println(" ");
9634 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009635 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009636 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009637 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009638 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9639 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9640 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9641 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9642 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009643 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009644 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009645 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009646 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009647 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009648 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009649
9650 if (needSep) pw.println(" ");
9651 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009652 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009653 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009655 needSep = true;
9656 }
9657
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009658 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009659
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009660 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009661 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009662 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009663 if (mHeavyWeightProcess != null) {
9664 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9665 }
9666
9667 return true;
9668 }
9669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 /**
9671 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009672 * - no provider specified: dump all the providers
9673 * - a flattened component name that matched an existing provider was specified as the
9674 * first arg: dump that one provider
9675 * - the first arg isn't the flattened component name of an existing provider:
9676 * dump all providers whose component contains the first arg as a substring
9677 */
9678 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9679 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009680 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009681 }
9682
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009683 static class ItemMatcher {
9684 ArrayList<ComponentName> components;
9685 ArrayList<String> strings;
9686 ArrayList<Integer> objects;
9687 boolean all;
9688
9689 ItemMatcher() {
9690 all = true;
9691 }
9692
9693 void build(String name) {
9694 ComponentName componentName = ComponentName.unflattenFromString(name);
9695 if (componentName != null) {
9696 if (components == null) {
9697 components = new ArrayList<ComponentName>();
9698 }
9699 components.add(componentName);
9700 all = false;
9701 } else {
9702 int objectId = 0;
9703 // Not a '/' separated full component name; maybe an object ID?
9704 try {
9705 objectId = Integer.parseInt(name, 16);
9706 if (objects == null) {
9707 objects = new ArrayList<Integer>();
9708 }
9709 objects.add(objectId);
9710 all = false;
9711 } catch (RuntimeException e) {
9712 // Not an integer; just do string match.
9713 if (strings == null) {
9714 strings = new ArrayList<String>();
9715 }
9716 strings.add(name);
9717 all = false;
9718 }
9719 }
9720 }
9721
9722 int build(String[] args, int opti) {
9723 for (; opti<args.length; opti++) {
9724 String name = args[opti];
9725 if ("--".equals(name)) {
9726 return opti+1;
9727 }
9728 build(name);
9729 }
9730 return opti;
9731 }
9732
9733 boolean match(Object object, ComponentName comp) {
9734 if (all) {
9735 return true;
9736 }
9737 if (components != null) {
9738 for (int i=0; i<components.size(); i++) {
9739 if (components.get(i).equals(comp)) {
9740 return true;
9741 }
9742 }
9743 }
9744 if (objects != null) {
9745 for (int i=0; i<objects.size(); i++) {
9746 if (System.identityHashCode(object) == objects.get(i)) {
9747 return true;
9748 }
9749 }
9750 }
9751 if (strings != null) {
9752 String flat = comp.flattenToString();
9753 for (int i=0; i<strings.size(); i++) {
9754 if (flat.contains(strings.get(i))) {
9755 return true;
9756 }
9757 }
9758 }
9759 return false;
9760 }
9761 }
9762
Dianne Hackborn625ac272010-09-17 18:29:22 -07009763 /**
9764 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009765 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009766 * - the cmd arg isn't the flattened component name of an existing activity:
9767 * dump all activity whose component contains the cmd as a substring
9768 * - A hex number of the ActivityRecord object instance.
9769 */
9770 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9771 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009772 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009773
9774 if ("all".equals(name)) {
9775 synchronized (this) {
9776 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009777 activities.add(r1);
9778 }
9779 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009780 } else if ("top".equals(name)) {
9781 synchronized (this) {
9782 final int N = mMainStack.mHistory.size();
9783 if (N > 0) {
9784 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9785 }
9786 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009787 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009788 ItemMatcher matcher = new ItemMatcher();
9789 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790
9791 synchronized (this) {
9792 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009793 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009794 activities.add(r1);
9795 }
9796 }
9797 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009798 }
9799
9800 if (activities.size() <= 0) {
9801 return false;
9802 }
9803
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009804 String[] newArgs = new String[args.length - opti];
9805 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9806
Dianne Hackborn30d71892010-12-11 10:37:55 -08009807 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009808 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009809 for (int i=activities.size()-1; i>=0; i--) {
9810 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009811 if (needSep) {
9812 pw.println();
9813 }
9814 needSep = true;
9815 synchronized (this) {
9816 if (lastTask != r.task) {
9817 lastTask = r.task;
9818 pw.print("TASK "); pw.print(lastTask.affinity);
9819 pw.print(" id="); pw.println(lastTask.taskId);
9820 if (dumpAll) {
9821 lastTask.dump(pw, " ");
9822 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009823 }
9824 }
9825 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009826 }
9827 return true;
9828 }
9829
9830 /**
9831 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9832 * there is a thread associated with the activity.
9833 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009834 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009835 final ActivityRecord r, String[] args, boolean dumpAll) {
9836 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009837 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9839 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9840 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009841 if (r.app != null) pw.println(r.app.pid);
9842 else pw.println("(not running)");
9843 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009844 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009845 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009846 }
9847 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009848 // flush anything that is already in the PrintWriter since the thread is going
9849 // to write to the file descriptor directly
9850 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009851 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009852 TransferPipe tp = new TransferPipe();
9853 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009854 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9855 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 tp.go(fd);
9857 } finally {
9858 tp.kill();
9859 }
9860 } catch (IOException e) {
9861 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009862 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009863 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009864 }
9865 }
9866 }
9867
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009868 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009869 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009870 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009871 boolean onlyHistory = false;
9872
9873 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009874 if (opti < args.length && "-s".equals(args[opti])) {
9875 dumpAll = false;
9876 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009877 onlyHistory = true;
9878 dumpPackage = null;
9879 }
9880
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009881 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009882 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009883 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009884 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009885 Iterator it = mRegisteredReceivers.values().iterator();
9886 while (it.hasNext()) {
9887 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009888 if (dumpPackage != null && (r.app == null ||
9889 !dumpPackage.equals(r.app.info.packageName))) {
9890 continue;
9891 }
9892 if (!printed) {
9893 pw.println(" Registered Receivers:");
9894 needSep = true;
9895 printed = true;
9896 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009897 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009898 r.dump(pw, " ");
9899 }
9900 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009901
9902 if (mReceiverResolver.dump(pw, needSep ?
9903 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9904 " ", dumpPackage, false)) {
9905 needSep = true;
9906 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009907 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009908
9909 for (BroadcastQueue q : mBroadcastQueues) {
9910 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009913 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009914
Dianne Hackborn786b4402012-08-27 15:14:02 -07009915 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009916 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9917 if (needSep) {
9918 pw.println();
9919 }
9920 needSep = true;
9921 pw.print(" Sticky broadcasts for user ");
9922 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9923 StringBuilder sb = new StringBuilder(128);
9924 for (Map.Entry<String, ArrayList<Intent>> ent
9925 : mStickyBroadcasts.valueAt(user).entrySet()) {
9926 pw.print(" * Sticky action "); pw.print(ent.getKey());
9927 if (dumpAll) {
9928 pw.println(":");
9929 ArrayList<Intent> intents = ent.getValue();
9930 final int N = intents.size();
9931 for (int i=0; i<N; i++) {
9932 sb.setLength(0);
9933 sb.append(" Intent: ");
9934 intents.get(i).toShortString(sb, false, true, false, false);
9935 pw.println(sb.toString());
9936 Bundle bundle = intents.get(i).getExtras();
9937 if (bundle != null) {
9938 pw.print(" ");
9939 pw.println(bundle.toString());
9940 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009941 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009942 } else {
9943 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009944 }
9945 }
9946 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009947 }
9948
Dianne Hackborn786b4402012-08-27 15:14:02 -07009949 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009950 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009951 for (BroadcastQueue queue : mBroadcastQueues) {
9952 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9953 + queue.mBroadcastsScheduled);
9954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009955 pw.println(" mHandler:");
9956 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009957 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009958 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009959
9960 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009961 }
9962
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009963 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009964 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009965 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009966
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009967 ItemMatcher matcher = new ItemMatcher();
9968 matcher.build(args, opti);
9969
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009970 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009971
9972 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009973
9974 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009975 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009976 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009977 ContentProviderRecord r = mLaunchingProviders.get(i);
9978 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9979 continue;
9980 }
9981 if (!printed) {
9982 if (needSep) pw.println(" ");
9983 needSep = true;
9984 pw.println(" Launching content providers:");
9985 printed = true;
9986 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009987 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009988 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009989 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009990 }
9991
9992 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009993 if (needSep) pw.println();
9994 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009995 pw.println("Granted Uri Permissions:");
9996 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9997 int uid = mGrantedUriPermissions.keyAt(i);
9998 HashMap<Uri, UriPermission> perms
9999 = mGrantedUriPermissions.valueAt(i);
10000 pw.print(" * UID "); pw.print(uid);
10001 pw.println(" holds:");
10002 for (UriPermission perm : perms.values()) {
10003 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010004 if (dumpAll) {
10005 perm.dump(pw, " ");
10006 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010007 }
10008 }
10009 needSep = true;
10010 }
10011
10012 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010013 }
10014
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010015 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010016 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010017 boolean needSep = false;
10018
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010019 if (mIntentSenderRecords.size() > 0) {
10020 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010021 Iterator<WeakReference<PendingIntentRecord>> it
10022 = mIntentSenderRecords.values().iterator();
10023 while (it.hasNext()) {
10024 WeakReference<PendingIntentRecord> ref = it.next();
10025 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010026 if (dumpPackage != null && (rec == null
10027 || !dumpPackage.equals(rec.key.packageName))) {
10028 continue;
10029 }
10030 if (!printed) {
10031 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10032 printed = true;
10033 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010034 needSep = true;
10035 if (rec != null) {
10036 pw.print(" * "); pw.println(rec);
10037 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010038 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010039 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010040 } else {
10041 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010042 }
10043 }
10044 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010045
10046 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010047 }
10048
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010049 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010050 String prefix, String label, boolean complete, boolean brief, boolean client,
10051 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010052 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010053 boolean needNL = false;
10054 final String innerPrefix = prefix + " ";
10055 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010056 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010058 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10059 continue;
10060 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010061 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010062 if (needNL) {
10063 pw.println(" ");
10064 needNL = false;
10065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010066 if (lastTask != r.task) {
10067 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010068 pw.print(prefix);
10069 pw.print(full ? "* " : " ");
10070 pw.println(lastTask);
10071 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010072 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010073 } else if (complete) {
10074 // Complete + brief == give a summary. Isn't that obvious?!?
10075 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010076 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010077 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010080 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010081 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10082 pw.print(" #"); pw.print(i); pw.print(": ");
10083 pw.println(r);
10084 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010085 r.dump(pw, innerPrefix);
10086 } else if (complete) {
10087 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010088 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010089 if (r.app != null) {
10090 pw.print(innerPrefix); pw.println(r.app);
10091 }
10092 }
10093 if (client && r.app != null && r.app.thread != null) {
10094 // flush anything that is already in the PrintWriter since the thread is going
10095 // to write to the file descriptor directly
10096 pw.flush();
10097 try {
10098 TransferPipe tp = new TransferPipe();
10099 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010100 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10101 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010102 // Short timeout, since blocking here can
10103 // deadlock with the application.
10104 tp.go(fd, 2000);
10105 } finally {
10106 tp.kill();
10107 }
10108 } catch (IOException e) {
10109 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10110 } catch (RemoteException e) {
10111 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10112 }
10113 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010115 }
10116 }
10117
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010118 private static String buildOomTag(String prefix, String space, int val, int base) {
10119 if (val == base) {
10120 if (space == null) return prefix;
10121 return prefix + " ";
10122 }
10123 return prefix + "+" + Integer.toString(val-base);
10124 }
10125
10126 private static final int dumpProcessList(PrintWriter pw,
10127 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010128 String prefix, String normalLabel, String persistentLabel,
10129 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010130 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010131 final int N = list.size()-1;
10132 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010133 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010134 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10135 continue;
10136 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010137 pw.println(String.format("%s%s #%2d: %s",
10138 prefix, (r.persistent ? persistentLabel : normalLabel),
10139 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010140 if (r.persistent) {
10141 numPers++;
10142 }
10143 }
10144 return numPers;
10145 }
10146
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010147 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010148 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010149 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010150 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010151
Dianne Hackborn905577f2011-09-07 18:31:28 -070010152 ArrayList<Pair<ProcessRecord, Integer>> list
10153 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10154 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010155 ProcessRecord r = origList.get(i);
10156 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10157 continue;
10158 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010159 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10160 }
10161
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010162 if (list.size() <= 0) {
10163 return false;
10164 }
10165
Dianne Hackborn905577f2011-09-07 18:31:28 -070010166 Comparator<Pair<ProcessRecord, Integer>> comparator
10167 = new Comparator<Pair<ProcessRecord, Integer>>() {
10168 @Override
10169 public int compare(Pair<ProcessRecord, Integer> object1,
10170 Pair<ProcessRecord, Integer> object2) {
10171 if (object1.first.setAdj != object2.first.setAdj) {
10172 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10173 }
10174 if (object1.second.intValue() != object2.second.intValue()) {
10175 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10176 }
10177 return 0;
10178 }
10179 };
10180
10181 Collections.sort(list, comparator);
10182
Dianne Hackborn287952c2010-09-22 22:34:31 -070010183 final long curRealtime = SystemClock.elapsedRealtime();
10184 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10185 final long curUptime = SystemClock.uptimeMillis();
10186 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10187
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010188 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010189 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010190 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010191 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010192 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010193 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10194 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010195 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10196 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010197 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10198 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010199 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10200 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010201 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010202 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010203 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10204 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10205 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10206 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10207 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10208 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10209 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10210 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010211 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10212 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010213 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10214 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010215 } else {
10216 oomAdj = Integer.toString(r.setAdj);
10217 }
10218 String schedGroup;
10219 switch (r.setSchedGroup) {
10220 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10221 schedGroup = "B";
10222 break;
10223 case Process.THREAD_GROUP_DEFAULT:
10224 schedGroup = "F";
10225 break;
10226 default:
10227 schedGroup = Integer.toString(r.setSchedGroup);
10228 break;
10229 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010230 String foreground;
10231 if (r.foregroundActivities) {
10232 foreground = "A";
10233 } else if (r.foregroundServices) {
10234 foreground = "S";
10235 } else {
10236 foreground = " ";
10237 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010238 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010239 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010240 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10241 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010242 if (r.adjSource != null || r.adjTarget != null) {
10243 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010244 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010245 if (r.adjTarget instanceof ComponentName) {
10246 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10247 } else if (r.adjTarget != null) {
10248 pw.print(r.adjTarget.toString());
10249 } else {
10250 pw.print("{null}");
10251 }
10252 pw.print("<=");
10253 if (r.adjSource instanceof ProcessRecord) {
10254 pw.print("Proc{");
10255 pw.print(((ProcessRecord)r.adjSource).toShortString());
10256 pw.println("}");
10257 } else if (r.adjSource != null) {
10258 pw.println(r.adjSource.toString());
10259 } else {
10260 pw.println("{null}");
10261 }
10262 }
10263 if (inclDetails) {
10264 pw.print(prefix);
10265 pw.print(" ");
10266 pw.print("oom: max="); pw.print(r.maxAdj);
10267 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010268 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010269 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010270 pw.print(" curRaw="); pw.print(r.curRawAdj);
10271 pw.print(" setRaw="); pw.print(r.setRawAdj);
10272 pw.print(" cur="); pw.print(r.curAdj);
10273 pw.print(" set="); pw.println(r.setAdj);
10274 pw.print(prefix);
10275 pw.print(" ");
10276 pw.print("keeping="); pw.print(r.keeping);
10277 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010278 pw.print(" empty="); pw.print(r.empty);
10279 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010280
10281 if (!r.keeping) {
10282 if (r.lastWakeTime != 0) {
10283 long wtime;
10284 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10285 synchronized (stats) {
10286 wtime = stats.getProcessWakeTime(r.info.uid,
10287 r.pid, curRealtime);
10288 }
10289 long timeUsed = wtime - r.lastWakeTime;
10290 pw.print(prefix);
10291 pw.print(" ");
10292 pw.print("keep awake over ");
10293 TimeUtils.formatDuration(realtimeSince, pw);
10294 pw.print(" used ");
10295 TimeUtils.formatDuration(timeUsed, pw);
10296 pw.print(" (");
10297 pw.print((timeUsed*100)/realtimeSince);
10298 pw.println("%)");
10299 }
10300 if (r.lastCpuTime != 0) {
10301 long timeUsed = r.curCpuTime - r.lastCpuTime;
10302 pw.print(prefix);
10303 pw.print(" ");
10304 pw.print("run cpu over ");
10305 TimeUtils.formatDuration(uptimeSince, pw);
10306 pw.print(" used ");
10307 TimeUtils.formatDuration(timeUsed, pw);
10308 pw.print(" (");
10309 pw.print((timeUsed*100)/uptimeSince);
10310 pw.println("%)");
10311 }
10312 }
10313 }
10314 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010315 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010316 }
10317
Dianne Hackbornb437e092011-08-05 17:50:29 -070010318 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010319 ArrayList<ProcessRecord> procs;
10320 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010321 if (args != null && args.length > start
10322 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010323 procs = new ArrayList<ProcessRecord>();
10324 int pid = -1;
10325 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010326 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010327 } catch (NumberFormatException e) {
10328
10329 }
10330 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10331 ProcessRecord proc = mLruProcesses.get(i);
10332 if (proc.pid == pid) {
10333 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010335 procs.add(proc);
10336 }
10337 }
10338 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010339 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010340 return null;
10341 }
10342 } else {
10343 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10344 }
10345 }
10346 return procs;
10347 }
10348
10349 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10350 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010351 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010352 if (procs == null) {
10353 return;
10354 }
10355
10356 long uptime = SystemClock.uptimeMillis();
10357 long realtime = SystemClock.elapsedRealtime();
10358 pw.println("Applications Graphics Acceleration Info:");
10359 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10360
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010361 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10362 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010363 if (r.thread != null) {
10364 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10365 pw.flush();
10366 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010367 TransferPipe tp = new TransferPipe();
10368 try {
10369 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10370 tp.go(fd);
10371 } finally {
10372 tp.kill();
10373 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010374 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010375 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010376 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010377 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010378 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010379 pw.flush();
10380 }
10381 }
10382 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010383 }
10384
Jeff Brown6754ba22011-12-14 20:20:01 -080010385 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10386 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10387 if (procs == null) {
10388 return;
10389 }
10390
10391 pw.println("Applications Database Info:");
10392
10393 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10394 ProcessRecord r = procs.get(i);
10395 if (r.thread != null) {
10396 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10397 pw.flush();
10398 try {
10399 TransferPipe tp = new TransferPipe();
10400 try {
10401 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10402 tp.go(fd);
10403 } finally {
10404 tp.kill();
10405 }
10406 } catch (IOException e) {
10407 pw.println("Failure while dumping the app: " + r);
10408 pw.flush();
10409 } catch (RemoteException e) {
10410 pw.println("Got a RemoteException while dumping the app " + r);
10411 pw.flush();
10412 }
10413 }
10414 }
10415 }
10416
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010417 final static class MemItem {
10418 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010419 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010420 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010421 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010422 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010423
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010424 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010425 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010426 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010427 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010428 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010429 }
10430 }
10431
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010432 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010433 boolean sort) {
10434 if (sort) {
10435 Collections.sort(items, new Comparator<MemItem>() {
10436 @Override
10437 public int compare(MemItem lhs, MemItem rhs) {
10438 if (lhs.pss < rhs.pss) {
10439 return 1;
10440 } else if (lhs.pss > rhs.pss) {
10441 return -1;
10442 }
10443 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010444 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010445 });
10446 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010447
10448 for (int i=0; i<items.size(); i++) {
10449 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010450 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010451 if (mi.subitems != null) {
10452 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10453 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010454 }
10455 }
10456
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010457 // These are in KB.
10458 static final long[] DUMP_MEM_BUCKETS = new long[] {
10459 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10460 120*1024, 160*1024, 200*1024,
10461 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10462 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10463 };
10464
Dianne Hackborn672342c2011-11-29 11:29:02 -080010465 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10466 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010467 int start = label.lastIndexOf('.');
10468 if (start >= 0) start++;
10469 else start = 0;
10470 int end = label.length();
10471 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10472 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10473 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10474 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010475 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010476 out.append(label, start, end);
10477 return;
10478 }
10479 }
10480 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010481 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010482 out.append(label, start, end);
10483 }
10484
10485 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10486 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10487 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10488 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10489 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10490 };
10491 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10492 "System", "Persistent", "Foreground",
10493 "Visible", "Perceptible", "Heavy Weight",
10494 "Backup", "A Services", "Home", "Previous",
10495 "B Services", "Background"
10496 };
10497
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010498 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010499 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010500 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010501 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010502 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010503
10504 int opti = 0;
10505 while (opti < args.length) {
10506 String opt = args[opti];
10507 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10508 break;
10509 }
10510 opti++;
10511 if ("-a".equals(opt)) {
10512 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010513 } else if ("--oom".equals(opt)) {
10514 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010515 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010516 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010517 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010518 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010519 pw.println("If [process] is specified it can be the name or ");
10520 pw.println("pid of a specific process to dump.");
10521 return;
10522 } else {
10523 pw.println("Unknown argument: " + opt + "; use -h for help");
10524 }
10525 }
10526
10527 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010528 if (procs == null) {
10529 return;
10530 }
10531
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010532 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 long uptime = SystemClock.uptimeMillis();
10534 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010535
10536 if (procs.size() == 1 || isCheckinRequest) {
10537 dumpAll = true;
10538 }
10539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 if (isCheckinRequest) {
10541 // short checkin version
10542 pw.println(uptime + "," + realtime);
10543 pw.flush();
10544 } else {
10545 pw.println("Applications Memory Usage (kB):");
10546 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10547 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010548
Dianne Hackbornb437e092011-08-05 17:50:29 -070010549 String[] innerArgs = new String[args.length-opti];
10550 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10551
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010552 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10553 long nativePss=0, dalvikPss=0, otherPss=0;
10554 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10555
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010556 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10557 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10558 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010559
10560 long totalPss = 0;
10561
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010562 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10563 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010565 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10567 pw.flush();
10568 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010569 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010570 if (dumpAll) {
10571 try {
10572 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10573 } catch (RemoteException e) {
10574 if (!isCheckinRequest) {
10575 pw.println("Got RemoteException!");
10576 pw.flush();
10577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010579 } else {
10580 mi = new Debug.MemoryInfo();
10581 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010583
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010584 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010585 long myTotalPss = mi.getTotalPss();
10586 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010587 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010588 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010589 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010590
10591 nativePss += mi.nativePss;
10592 dalvikPss += mi.dalvikPss;
10593 otherPss += mi.otherPss;
10594 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10595 long mem = mi.getOtherPss(j);
10596 miscPss[j] += mem;
10597 otherPss -= mem;
10598 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010599
10600 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010601 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10602 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010603 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010604 if (oomProcs[oomIndex] == null) {
10605 oomProcs[oomIndex] = new ArrayList<MemItem>();
10606 }
10607 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010608 break;
10609 }
10610 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010612 }
10613 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010614
10615 if (!isCheckinRequest && procs.size() > 1) {
10616 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10617
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010618 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10619 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10620 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010621 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010622 String label = Debug.MemoryInfo.getOtherLabel(j);
10623 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010624 }
10625
Dianne Hackbornb437e092011-08-05 17:50:29 -070010626 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10627 for (int j=0; j<oomPss.length; j++) {
10628 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010629 String label = DUMP_MEM_OOM_LABEL[j];
10630 MemItem item = new MemItem(label, label, oomPss[j],
10631 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010632 item.subitems = oomProcs[j];
10633 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010634 }
10635 }
10636
Dianne Hackborn672342c2011-11-29 11:29:02 -080010637 if (outTag != null || outStack != null) {
10638 if (outTag != null) {
10639 appendMemBucket(outTag, totalPss, "total", false);
10640 }
10641 if (outStack != null) {
10642 appendMemBucket(outStack, totalPss, "total", true);
10643 }
10644 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010645 for (int i=0; i<oomMems.size(); i++) {
10646 MemItem miCat = oomMems.get(i);
10647 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10648 continue;
10649 }
10650 if (miCat.id < ProcessList.SERVICE_ADJ
10651 || miCat.id == ProcessList.HOME_APP_ADJ
10652 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010653 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10654 outTag.append(" / ");
10655 }
10656 if (outStack != null) {
10657 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10658 if (firstLine) {
10659 outStack.append(":");
10660 firstLine = false;
10661 }
10662 outStack.append("\n\t at ");
10663 } else {
10664 outStack.append("$");
10665 }
10666 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010667 for (int j=0; j<miCat.subitems.size(); j++) {
10668 MemItem mi = miCat.subitems.get(j);
10669 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010670 if (outTag != null) {
10671 outTag.append(" ");
10672 }
10673 if (outStack != null) {
10674 outStack.append("$");
10675 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010676 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010677 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10678 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10679 }
10680 if (outStack != null) {
10681 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10682 }
10683 }
10684 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10685 outStack.append("(");
10686 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10687 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10688 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10689 outStack.append(":");
10690 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10691 }
10692 }
10693 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010694 }
10695 }
10696 }
10697 }
10698
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010699 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010700 pw.println();
10701 pw.println("Total PSS by process:");
10702 dumpMemItems(pw, " ", procMems, true);
10703 pw.println();
10704 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010705 pw.println("Total PSS by OOM adjustment:");
10706 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010707 if (!oomOnly) {
10708 PrintWriter out = categoryPw != null ? categoryPw : pw;
10709 out.println();
10710 out.println("Total PSS by category:");
10711 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010712 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010713 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010714 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010715 final int[] SINGLE_LONG_FORMAT = new int[] {
10716 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10717 };
10718 long[] longOut = new long[1];
10719 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10720 SINGLE_LONG_FORMAT, null, longOut, null);
10721 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10722 longOut[0] = 0;
10723 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10724 SINGLE_LONG_FORMAT, null, longOut, null);
10725 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10726 longOut[0] = 0;
10727 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10728 SINGLE_LONG_FORMAT, null, longOut, null);
10729 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10730 longOut[0] = 0;
10731 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10732 SINGLE_LONG_FORMAT, null, longOut, null);
10733 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10734 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10735 pw.print(shared); pw.println(" kB");
10736 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10737 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 }
10740
10741 /**
10742 * Searches array of arguments for the specified string
10743 * @param args array of argument strings
10744 * @param value value to search for
10745 * @return true if the value is contained in the array
10746 */
10747 private static boolean scanArgs(String[] args, String value) {
10748 if (args != null) {
10749 for (String arg : args) {
10750 if (value.equals(arg)) {
10751 return true;
10752 }
10753 }
10754 }
10755 return false;
10756 }
10757
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010758 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10759 ContentProviderRecord cpr, boolean always) {
10760 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10761
10762 if (!inLaunching || always) {
10763 synchronized (cpr) {
10764 cpr.launchingApp = null;
10765 cpr.notifyAll();
10766 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010767 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010768 String names[] = cpr.info.authority.split(";");
10769 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010770 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 }
10772 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010773
10774 for (int i=0; i<cpr.connections.size(); i++) {
10775 ContentProviderConnection conn = cpr.connections.get(i);
10776 if (conn.waiting) {
10777 // If this connection is waiting for the provider, then we don't
10778 // need to mess with its process unless we are always removing
10779 // or for some reason the provider is not currently launching.
10780 if (inLaunching && !always) {
10781 continue;
10782 }
10783 }
10784 ProcessRecord capp = conn.client;
10785 conn.dead = true;
10786 if (conn.stableCount > 0) {
10787 if (!capp.persistent && capp.thread != null
10788 && capp.pid != 0
10789 && capp.pid != MY_PID) {
10790 Slog.i(TAG, "Kill " + capp.processName
10791 + " (pid " + capp.pid + "): provider " + cpr.info.name
10792 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010793 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010794 capp.processName, capp.setAdj, "dying provider "
10795 + cpr.name.toShortString());
10796 Process.killProcessQuiet(capp.pid);
10797 }
10798 } else if (capp.thread != null && conn.provider.provider != null) {
10799 try {
10800 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10801 } catch (RemoteException e) {
10802 }
10803 // In the protocol here, we don't expect the client to correctly
10804 // clean up this connection, we'll just remove it.
10805 cpr.connections.remove(i);
10806 conn.client.conProviders.remove(conn);
10807 }
10808 }
10809
10810 if (inLaunching && always) {
10811 mLaunchingProviders.remove(cpr);
10812 }
10813 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 }
10815
10816 /**
10817 * Main code for cleaning up a process when it has gone away. This is
10818 * called both as a result of the process dying, or directly when stopping
10819 * a process when running in single process mode.
10820 */
10821 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010822 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010824 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 }
10826
Dianne Hackborn36124872009-10-08 16:22:03 -070010827 mProcessesToGc.remove(app);
10828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 // Dismiss any open dialogs.
10830 if (app.crashDialog != null) {
10831 app.crashDialog.dismiss();
10832 app.crashDialog = null;
10833 }
10834 if (app.anrDialog != null) {
10835 app.anrDialog.dismiss();
10836 app.anrDialog = null;
10837 }
10838 if (app.waitDialog != null) {
10839 app.waitDialog.dismiss();
10840 app.waitDialog = null;
10841 }
10842
10843 app.crashing = false;
10844 app.notResponding = false;
10845
10846 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010847 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 app.thread = null;
10849 app.forcingToForeground = null;
10850 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010851 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010852 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010853 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010855 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856
10857 boolean restart = false;
10858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 // Remove published content providers.
10860 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010861 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010863 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010864
10865 final boolean always = app.bad || !allowRestart;
10866 if (removeDyingProviderLocked(app, cpr, always) || always) {
10867 // We left the provider in the launching list, need to
10868 // restart it.
10869 restart = true;
10870 }
10871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010872 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010873 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874 }
10875 app.pubProviders.clear();
10876 }
10877
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010878 // Take care of any launching providers waiting for this process.
10879 if (checkAppInLaunchingProvidersLocked(app, false)) {
10880 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 // Unregister from connected content providers.
10884 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010885 for (int i=0; i<app.conProviders.size(); i++) {
10886 ContentProviderConnection conn = app.conProviders.get(i);
10887 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 }
10889 app.conProviders.clear();
10890 }
10891
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010892 // At this point there may be remaining entries in mLaunchingProviders
10893 // where we were the only one waiting, so they are no longer of use.
10894 // Look for these and clean up if found.
10895 // XXX Commented out for now. Trying to figure out a way to reproduce
10896 // the actual situation to identify what is actually going on.
10897 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010898 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010899 ContentProviderRecord cpr = (ContentProviderRecord)
10900 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010901 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010902 synchronized (cpr) {
10903 cpr.launchingApp = null;
10904 cpr.notifyAll();
10905 }
10906 }
10907 }
10908 }
10909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 skipCurrentReceiverLocked(app);
10911
10912 // Unregister any receivers.
10913 if (app.receivers.size() > 0) {
10914 Iterator<ReceiverList> it = app.receivers.iterator();
10915 while (it.hasNext()) {
10916 removeReceiverLocked(it.next());
10917 }
10918 app.receivers.clear();
10919 }
10920
Christopher Tate181fafa2009-05-14 11:12:14 -070010921 // If the app is undergoing backup, tell the backup manager about it
10922 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010923 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10924 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010925 try {
10926 IBackupManager bm = IBackupManager.Stub.asInterface(
10927 ServiceManager.getService(Context.BACKUP_SERVICE));
10928 bm.agentDisconnected(app.info.packageName);
10929 } catch (RemoteException e) {
10930 // can't happen; backup manager is local
10931 }
10932 }
10933
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010934 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10935 ProcessChangeItem item = mPendingProcessChanges.get(i);
10936 if (item.pid == app.pid) {
10937 mPendingProcessChanges.remove(i);
10938 mAvailProcessChanges.add(item);
10939 }
10940 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010941 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010943 // If the caller is restarting this app, then leave it in its
10944 // current lists and let the caller take care of it.
10945 if (restarting) {
10946 return;
10947 }
10948
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010949 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010950 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010952 mProcessNames.remove(app.processName, app.uid);
10953 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010954 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010955 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10956 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010957 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010959 } else if (!app.removed) {
10960 // This app is persistent, so we need to keep its record around.
10961 // If it is not already on the pending app list, add it there
10962 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10964 mPersistentStartingProcesses.add(app);
10965 restart = true;
10966 }
10967 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010968 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010969 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 mProcessesOnHold.remove(app);
10971
The Android Open Source Project4df24232009-03-05 14:34:35 -080010972 if (app == mHomeProcess) {
10973 mHomeProcess = null;
10974 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010975 if (app == mPreviousProcess) {
10976 mPreviousProcess = null;
10977 }
10978
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010979 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 // We have components that still need to be running in the
10981 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010982 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983 startProcessLocked(app, "restart", app.processName);
10984 } else if (app.pid > 0 && app.pid != MY_PID) {
10985 // Goodbye!
10986 synchronized (mPidsSelfLocked) {
10987 mPidsSelfLocked.remove(app.pid);
10988 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10989 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010990 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 }
10992 }
10993
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010994 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10995 // Look through the content providers we are waiting to have launched,
10996 // and if any run in this process then either schedule a restart of
10997 // the process or kill the client waiting for it if this process has
10998 // gone bad.
10999 int NL = mLaunchingProviders.size();
11000 boolean restart = false;
11001 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011002 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011003 if (cpr.launchingApp == app) {
11004 if (!alwaysBad && !app.bad) {
11005 restart = true;
11006 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011007 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011008 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011009 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011010 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011011 }
11012 }
11013 }
11014 return restart;
11015 }
11016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 // =========================================================
11018 // SERVICES
11019 // =========================================================
11020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11022 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011023 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011025 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 }
11027 }
11028
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011029 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011030 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011031 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011032 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011033 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011034 }
11035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011037 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011038 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 // Refuse possible leaked file descriptors
11040 if (service != null && service.hasFileDescriptors() == true) {
11041 throw new IllegalArgumentException("File descriptors passed in Intent");
11042 }
11043
Amith Yamasani742a6712011-05-04 14:49:28 -070011044 if (DEBUG_SERVICE)
11045 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 synchronized(this) {
11047 final int callingPid = Binder.getCallingPid();
11048 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011049 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011051 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011052 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 Binder.restoreCallingIdentity(origId);
11054 return res;
11055 }
11056 }
11057
11058 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070011059 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011060 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011061 if (DEBUG_SERVICE)
11062 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011064 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070011065 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011066 Binder.restoreCallingIdentity(origId);
11067 return res;
11068 }
11069 }
11070
11071 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011072 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011073 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011074 // Refuse possible leaked file descriptors
11075 if (service != null && service.hasFileDescriptors() == true) {
11076 throw new IllegalArgumentException("File descriptors passed in Intent");
11077 }
11078
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011079 checkValidCaller(Binder.getCallingUid(), userId);
11080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011082 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 }
11085
11086 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011087 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 // Refuse possible leaked file descriptors
11089 if (service != null && service.hasFileDescriptors() == true) {
11090 throw new IllegalArgumentException("File descriptors passed in Intent");
11091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011092 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011093 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 }
11096
11097 public boolean stopServiceToken(ComponentName className, IBinder token,
11098 int startId) {
11099 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011100 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 }
11103
11104 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011105 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011107 mServices.setServiceForegroundLocked(className, token, id, notification,
11108 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011109 }
11110 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011111
Dianne Hackborn41203752012-08-31 14:05:51 -070011112 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11113 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011114 final int callingUserId = UserHandle.getUserId(callingUid);
11115 if (callingUserId != userId) {
11116 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11117 if ((requireFull || checkComponentPermission(
11118 android.Manifest.permission.INTERACT_ACROSS_USERS,
11119 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11120 && checkComponentPermission(
11121 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11122 callingPid, callingUid, -1, true)
11123 != PackageManager.PERMISSION_GRANTED) {
11124 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11125 // In this case, they would like to just execute as their
11126 // owner user instead of failing.
11127 userId = callingUserId;
11128 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011129 StringBuilder builder = new StringBuilder(128);
11130 builder.append("Permission Denial: ");
11131 builder.append(name);
11132 if (callerPackage != null) {
11133 builder.append(" from ");
11134 builder.append(callerPackage);
11135 }
11136 builder.append(" asks to run as user ");
11137 builder.append(userId);
11138 builder.append(" but is calling from user ");
11139 builder.append(UserHandle.getUserId(callingUid));
11140 builder.append("; this requires ");
11141 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11142 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011143 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011144 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11145 }
11146 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011147 Slog.w(TAG, msg);
11148 throw new SecurityException(msg);
11149 }
11150 }
11151 }
11152 if (userId == UserHandle.USER_CURRENT
11153 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011154 // Note that we may be accessing this outside of a lock...
11155 // shouldn't be a big deal, if this is being called outside
11156 // of a locked context there is intrinsically a race with
11157 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011158 userId = mCurrentUserId;
11159 }
11160 if (!allowAll && userId < 0) {
11161 throw new IllegalArgumentException(
11162 "Call does not support special user #" + userId);
11163 }
11164 }
11165 return userId;
11166 }
11167
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011168 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11169 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011170 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011171 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011172 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11173 if (ActivityManager.checkUidPermission(
11174 android.Manifest.permission.INTERACT_ACROSS_USERS,
11175 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11176 ComponentName comp = new ComponentName(aInfo.packageName, className);
11177 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11178 + " requests FLAG_SINGLE_USER, but app does not hold "
11179 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11180 Slog.w(TAG, msg);
11181 throw new SecurityException(msg);
11182 }
11183 result = true;
11184 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011185 } else if (componentProcessName == aInfo.packageName) {
11186 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11187 } else if ("system".equals(componentProcessName)) {
11188 result = true;
11189 }
11190 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011191 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11192 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011193 }
11194 return result;
11195 }
11196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 public int bindService(IApplicationThread caller, IBinder token,
11198 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011199 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011200 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 // Refuse possible leaked file descriptors
11202 if (service != null && service.hasFileDescriptors() == true) {
11203 throw new IllegalArgumentException("File descriptors passed in Intent");
11204 }
11205
11206 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011207 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11208 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 }
11210 }
11211
11212 public boolean unbindService(IServiceConnection connection) {
11213 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011214 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011216 }
11217
11218 public void publishService(IBinder token, Intent intent, IBinder service) {
11219 // Refuse possible leaked file descriptors
11220 if (intent != null && intent.hasFileDescriptors() == true) {
11221 throw new IllegalArgumentException("File descriptors passed in Intent");
11222 }
11223
11224 synchronized(this) {
11225 if (!(token instanceof ServiceRecord)) {
11226 throw new IllegalArgumentException("Invalid service token");
11227 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011228 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011229 }
11230 }
11231
11232 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11233 // Refuse possible leaked file descriptors
11234 if (intent != null && intent.hasFileDescriptors() == true) {
11235 throw new IllegalArgumentException("File descriptors passed in Intent");
11236 }
11237
11238 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011239 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011240 }
11241 }
11242
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011243 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011244 synchronized(this) {
11245 if (!(token instanceof ServiceRecord)) {
11246 throw new IllegalArgumentException("Invalid service token");
11247 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011248 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011250 }
11251
11252 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011253 // BACKUP AND RESTORE
11254 // =========================================================
11255
11256 // Cause the target app to be launched if necessary and its backup agent
11257 // instantiated. The backup agent will invoke backupAgentCreated() on the
11258 // activity manager to announce its creation.
11259 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011260 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11261 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011262
11263 synchronized(this) {
11264 // !!! TODO: currently no check here that we're already bound
11265 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11266 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11267 synchronized (stats) {
11268 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11269 }
11270
Dianne Hackborne7f97212011-02-24 14:40:20 -080011271 // Backup agent is now in use, its package can't be stopped.
11272 try {
11273 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011274 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011275 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011276 } catch (IllegalArgumentException e) {
11277 Slog.w(TAG, "Failed trying to unstop package "
11278 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011279 }
11280
Christopher Tate181fafa2009-05-14 11:12:14 -070011281 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011282 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11283 ? new ComponentName(app.packageName, app.backupAgentName)
11284 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011285 // startProcessLocked() returns existing proc's record if it's already running
11286 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011287 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011288 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011289 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011290 return false;
11291 }
11292
11293 r.app = proc;
11294 mBackupTarget = r;
11295 mBackupAppName = app.packageName;
11296
Christopher Tate6fa95972009-06-05 18:43:55 -070011297 // Try not to kill the process during backup
11298 updateOomAdjLocked(proc);
11299
Christopher Tate181fafa2009-05-14 11:12:14 -070011300 // If the process is already attached, schedule the creation of the backup agent now.
11301 // If it is not yet live, this will be done when it attaches to the framework.
11302 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011303 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011304 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011305 proc.thread.scheduleCreateBackupAgent(app,
11306 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011307 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011308 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011309 }
11310 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011311 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011312 }
11313 // Invariants: at this point, the target app process exists and the application
11314 // is either already running or in the process of coming up. mBackupTarget and
11315 // mBackupAppName describe the app, so that when it binds back to the AM we
11316 // know that it's scheduled for a backup-agent operation.
11317 }
11318
11319 return true;
11320 }
11321
Christopher Tate346acb12012-10-15 19:20:25 -070011322 @Override
11323 public void clearPendingBackup() {
11324 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11325 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11326
11327 synchronized (this) {
11328 mBackupTarget = null;
11329 mBackupAppName = null;
11330 }
11331 }
11332
Christopher Tate181fafa2009-05-14 11:12:14 -070011333 // A backup agent has just come up
11334 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011335 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011336 + " = " + agent);
11337
11338 synchronized(this) {
11339 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011340 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011341 return;
11342 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011343 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011344
Dianne Hackborn06740692010-09-22 22:46:21 -070011345 long oldIdent = Binder.clearCallingIdentity();
11346 try {
11347 IBackupManager bm = IBackupManager.Stub.asInterface(
11348 ServiceManager.getService(Context.BACKUP_SERVICE));
11349 bm.agentConnected(agentPackageName, agent);
11350 } catch (RemoteException e) {
11351 // can't happen; the backup manager service is local
11352 } catch (Exception e) {
11353 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11354 e.printStackTrace();
11355 } finally {
11356 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011357 }
11358 }
11359
11360 // done with this agent
11361 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011362 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011363 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011364 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011365 return;
11366 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011367
11368 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011369 try {
11370 if (mBackupAppName == null) {
11371 Slog.w(TAG, "Unbinding backup agent with no active backup");
11372 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011373 }
Christopher Tate346acb12012-10-15 19:20:25 -070011374
11375 if (!mBackupAppName.equals(appInfo.packageName)) {
11376 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11377 return;
11378 }
11379
11380 // Not backing this app up any more; reset its OOM adjustment
11381 final ProcessRecord proc = mBackupTarget.app;
11382 updateOomAdjLocked(proc);
11383
11384 // If the app crashed during backup, 'thread' will be null here
11385 if (proc.thread != null) {
11386 try {
11387 proc.thread.scheduleDestroyBackupAgent(appInfo,
11388 compatibilityInfoForPackageLocked(appInfo));
11389 } catch (Exception e) {
11390 Slog.e(TAG, "Exception when unbinding backup agent:");
11391 e.printStackTrace();
11392 }
11393 }
11394 } finally {
11395 mBackupTarget = null;
11396 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011397 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011398 }
11399 }
11400 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 // BROADCASTS
11402 // =========================================================
11403
Josh Bartel7f208742010-02-25 11:01:44 -060011404 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011405 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011406 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011407 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11408 if (stickies == null) {
11409 return cur;
11410 }
11411 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 if (list == null) {
11413 return cur;
11414 }
11415 int N = list.size();
11416 for (int i=0; i<N; i++) {
11417 Intent intent = list.get(i);
11418 if (filter.match(resolver, intent, true, TAG) >= 0) {
11419 if (cur == null) {
11420 cur = new ArrayList<Intent>();
11421 }
11422 cur.add(intent);
11423 }
11424 }
11425 return cur;
11426 }
11427
Christopher Tatef46723b2012-01-26 14:19:24 -080011428 boolean isPendingBroadcastProcessLocked(int pid) {
11429 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11430 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11431 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432
Christopher Tatef46723b2012-01-26 14:19:24 -080011433 void skipPendingBroadcastLocked(int pid) {
11434 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11435 for (BroadcastQueue queue : mBroadcastQueues) {
11436 queue.skipPendingBroadcastLocked(pid);
11437 }
11438 }
11439
11440 // The app just attached; send any pending broadcasts that it should receive
11441 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11442 boolean didSomething = false;
11443 for (BroadcastQueue queue : mBroadcastQueues) {
11444 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011446 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 }
11448
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011449 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011450 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011451 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011452 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011453 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 synchronized(this) {
11455 ProcessRecord callerApp = null;
11456 if (caller != null) {
11457 callerApp = getRecordForAppLocked(caller);
11458 if (callerApp == null) {
11459 throw new SecurityException(
11460 "Unable to find app for caller " + caller
11461 + " (pid=" + Binder.getCallingPid()
11462 + ") when registering receiver " + receiver);
11463 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011464 if (callerApp.info.uid != Process.SYSTEM_UID &&
11465 !callerApp.pkgList.contains(callerPackage)) {
11466 throw new SecurityException("Given caller package " + callerPackage
11467 + " is not running in process " + callerApp);
11468 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011469 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011470 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011471 } else {
11472 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011473 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011474 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 }
11476
Dianne Hackborn139748f2012-09-24 11:36:57 -070011477 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011478 true, true, "registerReceiver", callerPackage);
11479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480 List allSticky = null;
11481
11482 // Look for any matching sticky broadcasts...
11483 Iterator actions = filter.actionsIterator();
11484 if (actions != null) {
11485 while (actions.hasNext()) {
11486 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011487 allSticky = getStickiesLocked(action, filter, allSticky,
11488 UserHandle.USER_ALL);
11489 allSticky = getStickiesLocked(action, filter, allSticky,
11490 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011491 }
11492 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011493 allSticky = getStickiesLocked(null, filter, allSticky,
11494 UserHandle.USER_ALL);
11495 allSticky = getStickiesLocked(null, filter, allSticky,
11496 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 }
11498
11499 // The first sticky in the list is returned directly back to
11500 // the client.
11501 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11502
Joe Onorato8a9b2202010-02-26 18:56:32 -080011503 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 + ": " + sticky);
11505
11506 if (receiver == null) {
11507 return sticky;
11508 }
11509
11510 ReceiverList rl
11511 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11512 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011513 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11514 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 if (rl.app != null) {
11516 rl.app.receivers.add(rl);
11517 } else {
11518 try {
11519 receiver.asBinder().linkToDeath(rl, 0);
11520 } catch (RemoteException e) {
11521 return sticky;
11522 }
11523 rl.linkedToDeath = true;
11524 }
11525 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011526 } else if (rl.uid != callingUid) {
11527 throw new IllegalArgumentException(
11528 "Receiver requested to register for uid " + callingUid
11529 + " was previously registered for uid " + rl.uid);
11530 } else if (rl.pid != callingPid) {
11531 throw new IllegalArgumentException(
11532 "Receiver requested to register for pid " + callingPid
11533 + " was previously registered for pid " + rl.pid);
11534 } else if (rl.userId != userId) {
11535 throw new IllegalArgumentException(
11536 "Receiver requested to register for user " + userId
11537 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011539 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011540 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011541 rl.add(bf);
11542 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011543 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 }
11545 mReceiverResolver.addFilter(bf);
11546
11547 // Enqueue broadcasts for all existing stickies that match
11548 // this filter.
11549 if (allSticky != null) {
11550 ArrayList receivers = new ArrayList();
11551 receivers.add(bf);
11552
11553 int N = allSticky.size();
11554 for (int i=0; i<N; i++) {
11555 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011556 BroadcastQueue queue = broadcastQueueForIntent(intent);
11557 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011558 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11559 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011560 queue.enqueueParallelBroadcastLocked(r);
11561 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011562 }
11563 }
11564
11565 return sticky;
11566 }
11567 }
11568
11569 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011570 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571
Christopher Tatef46723b2012-01-26 14:19:24 -080011572 final long origId = Binder.clearCallingIdentity();
11573 try {
11574 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011575
Christopher Tatef46723b2012-01-26 14:19:24 -080011576 synchronized(this) {
11577 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011578 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011579 if (rl != null) {
11580 if (rl.curBroadcast != null) {
11581 BroadcastRecord r = rl.curBroadcast;
11582 final boolean doNext = finishReceiverLocked(
11583 receiver.asBinder(), r.resultCode, r.resultData,
11584 r.resultExtras, r.resultAbort, true);
11585 if (doNext) {
11586 doTrim = true;
11587 r.queue.processNextBroadcast(false);
11588 }
11589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590
Christopher Tatef46723b2012-01-26 14:19:24 -080011591 if (rl.app != null) {
11592 rl.app.receivers.remove(rl);
11593 }
11594 removeReceiverLocked(rl);
11595 if (rl.linkedToDeath) {
11596 rl.linkedToDeath = false;
11597 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 }
11600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011601
Christopher Tatef46723b2012-01-26 14:19:24 -080011602 // If we actually concluded any broadcasts, we might now be able
11603 // to trim the recipients' apps from our working set
11604 if (doTrim) {
11605 trimApplications();
11606 return;
11607 }
11608
11609 } finally {
11610 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 }
11613
11614 void removeReceiverLocked(ReceiverList rl) {
11615 mRegisteredReceivers.remove(rl.receiver.asBinder());
11616 int N = rl.size();
11617 for (int i=0; i<N; i++) {
11618 mReceiverResolver.removeFilter(rl.get(i));
11619 }
11620 }
11621
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011622 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011623 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11624 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011625 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011626 try {
11627 r.thread.dispatchPackageBroadcast(cmd, packages);
11628 } catch (RemoteException ex) {
11629 }
11630 }
11631 }
11632 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011633
11634 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11635 int[] users) {
11636 List<ResolveInfo> receivers = null;
11637 try {
11638 HashSet<ComponentName> singleUserReceivers = null;
11639 boolean scannedFirstReceivers = false;
11640 for (int user : users) {
11641 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11642 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011643 if (user != 0 && newReceivers != null) {
11644 // If this is not the primary user, we need to check for
11645 // any receivers that should be filtered out.
11646 for (int i=0; i<newReceivers.size(); i++) {
11647 ResolveInfo ri = newReceivers.get(i);
11648 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11649 newReceivers.remove(i);
11650 i--;
11651 }
11652 }
11653 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011654 if (newReceivers != null && newReceivers.size() == 0) {
11655 newReceivers = null;
11656 }
11657 if (receivers == null) {
11658 receivers = newReceivers;
11659 } else if (newReceivers != null) {
11660 // We need to concatenate the additional receivers
11661 // found with what we have do far. This would be easy,
11662 // but we also need to de-dup any receivers that are
11663 // singleUser.
11664 if (!scannedFirstReceivers) {
11665 // Collect any single user receivers we had already retrieved.
11666 scannedFirstReceivers = true;
11667 for (int i=0; i<receivers.size(); i++) {
11668 ResolveInfo ri = receivers.get(i);
11669 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11670 ComponentName cn = new ComponentName(
11671 ri.activityInfo.packageName, ri.activityInfo.name);
11672 if (singleUserReceivers == null) {
11673 singleUserReceivers = new HashSet<ComponentName>();
11674 }
11675 singleUserReceivers.add(cn);
11676 }
11677 }
11678 }
11679 // Add the new results to the existing results, tracking
11680 // and de-dupping single user receivers.
11681 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011682 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011683 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11684 ComponentName cn = new ComponentName(
11685 ri.activityInfo.packageName, ri.activityInfo.name);
11686 if (singleUserReceivers == null) {
11687 singleUserReceivers = new HashSet<ComponentName>();
11688 }
11689 if (!singleUserReceivers.contains(cn)) {
11690 singleUserReceivers.add(cn);
11691 receivers.add(ri);
11692 }
11693 } else {
11694 receivers.add(ri);
11695 }
11696 }
11697 }
11698 }
11699 } catch (RemoteException ex) {
11700 // pm is in same process, this will never happen.
11701 }
11702 return receivers;
11703 }
11704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011705 private final int broadcastIntentLocked(ProcessRecord callerApp,
11706 String callerPackage, Intent intent, String resolvedType,
11707 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011708 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011709 boolean ordered, boolean sticky, int callingPid, int callingUid,
11710 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 intent = new Intent(intent);
11712
Dianne Hackborne7f97212011-02-24 14:40:20 -080011713 // By default broadcasts do not go to stopped apps.
11714 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11715
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011718 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011722
Dianne Hackborn139748f2012-09-24 11:36:57 -070011723 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011724 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011725
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011726 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011727 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011728 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011729 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11730 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11731 Slog.w(TAG, "Skipping broadcast of " + intent
11732 + ": user " + userId + " is stopped");
11733 return ActivityManager.BROADCAST_SUCCESS;
11734 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011735 }
11736
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011737 /*
11738 * Prevent non-system code (defined here to be non-persistent
11739 * processes) from sending protected broadcasts.
11740 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011741 int callingAppId = UserHandle.getAppId(callingUid);
11742 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11743 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011744 callingUid == 0) {
11745 // Always okay.
11746 } else if (callerApp == null || !callerApp.persistent) {
11747 try {
11748 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11749 intent.getAction())) {
11750 String msg = "Permission Denial: not allowed to send broadcast "
11751 + intent.getAction() + " from pid="
11752 + callingPid + ", uid=" + callingUid;
11753 Slog.w(TAG, msg);
11754 throw new SecurityException(msg);
11755 }
11756 } catch (RemoteException e) {
11757 Slog.w(TAG, "Remote exception", e);
11758 return ActivityManager.BROADCAST_SUCCESS;
11759 }
11760 }
11761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762 // Handle special intents: if this broadcast is from the package
11763 // manager about a package being removed, we need to remove all of
11764 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011765 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011767 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11768 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011769 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 || uidRemoved) {
11771 if (checkComponentPermission(
11772 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011773 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011774 == PackageManager.PERMISSION_GRANTED) {
11775 if (uidRemoved) {
11776 final Bundle intentExtras = intent.getExtras();
11777 final int uid = intentExtras != null
11778 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11779 if (uid >= 0) {
11780 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11781 synchronized (bs) {
11782 bs.removeUidStatsLocked(uid);
11783 }
11784 }
11785 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011786 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011787 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011788 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011789 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11790 if (list != null && (list.length > 0)) {
11791 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011792 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011793 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011794 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011795 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011796 }
11797 } else {
11798 Uri data = intent.getData();
11799 String ssp;
11800 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11801 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11802 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011803 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11804 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011805 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011806 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011807 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011808 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 }
11811 }
11812 }
11813 } else {
11814 String msg = "Permission Denial: " + intent.getAction()
11815 + " broadcast from " + callerPackage + " (pid=" + callingPid
11816 + ", uid=" + callingUid + ")"
11817 + " requires "
11818 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011819 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 throw new SecurityException(msg);
11821 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011822
11823 // Special case for adding a package: by default turn on compatibility
11824 // mode.
11825 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011826 Uri data = intent.getData();
11827 String ssp;
11828 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11829 mCompatModePackages.handlePackageAddedLocked(ssp,
11830 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 }
11833
11834 /*
11835 * If this is the time zone changed action, queue up a message that will reset the timezone
11836 * of all currently running processes. This message will get queued up before the broadcast
11837 * happens.
11838 */
11839 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11840 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11841 }
11842
Robert Greenwalt03595d02010-11-02 14:08:23 -070011843 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11844 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11845 }
11846
Robert Greenwalt434203a2010-10-11 16:00:27 -070011847 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11848 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11849 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11850 }
11851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011852 // Add to the sticky list if requested.
11853 if (sticky) {
11854 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11855 callingPid, callingUid)
11856 != PackageManager.PERMISSION_GRANTED) {
11857 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11858 + callingPid + ", uid=" + callingUid
11859 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011860 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 throw new SecurityException(msg);
11862 }
11863 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011864 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011866 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 }
11868 if (intent.getComponent() != null) {
11869 throw new SecurityException(
11870 "Sticky broadcasts can't target a specific component");
11871 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011872 // We use userId directly here, since the "all" target is maintained
11873 // as a separate set of sticky broadcasts.
11874 if (userId != UserHandle.USER_ALL) {
11875 // But first, if this is not a broadcast to all users, then
11876 // make sure it doesn't conflict with an existing broadcast to
11877 // all users.
11878 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11879 UserHandle.USER_ALL);
11880 if (stickies != null) {
11881 ArrayList<Intent> list = stickies.get(intent.getAction());
11882 if (list != null) {
11883 int N = list.size();
11884 int i;
11885 for (i=0; i<N; i++) {
11886 if (intent.filterEquals(list.get(i))) {
11887 throw new IllegalArgumentException(
11888 "Sticky broadcast " + intent + " for user "
11889 + userId + " conflicts with existing global broadcast");
11890 }
11891 }
11892 }
11893 }
11894 }
11895 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11896 if (stickies == null) {
11897 stickies = new HashMap<String, ArrayList<Intent>>();
11898 mStickyBroadcasts.put(userId, stickies);
11899 }
11900 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 if (list == null) {
11902 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011903 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011904 }
11905 int N = list.size();
11906 int i;
11907 for (i=0; i<N; i++) {
11908 if (intent.filterEquals(list.get(i))) {
11909 // This sticky already exists, replace it.
11910 list.set(i, new Intent(intent));
11911 break;
11912 }
11913 }
11914 if (i >= N) {
11915 list.add(new Intent(intent));
11916 }
11917 }
11918
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011919 int[] users;
11920 if (userId == UserHandle.USER_ALL) {
11921 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011922 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011923 } else {
11924 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011925 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011926 }
11927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 // Figure out who all will receive this broadcast.
11929 List receivers = null;
11930 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011931 // Need to resolve the intent to interested receivers...
11932 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11933 == 0) {
11934 receivers = collectReceiverComponents(intent, resolvedType, users);
11935 }
11936 if (intent.getComponent() == null) {
11937 registeredReceivers = mReceiverResolver.queryIntent(intent,
11938 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011939 }
11940
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011941 final boolean replacePending =
11942 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11943
Joe Onorato8a9b2202010-02-26 18:56:32 -080011944 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011945 + " replacePending=" + replacePending);
11946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11948 if (!ordered && NR > 0) {
11949 // If we are not serializing this broadcast, then send the
11950 // registered receivers separately so they don't wait for the
11951 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011952 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11953 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011954 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011956 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011957 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011958 TAG, "Enqueueing parallel broadcast " + r);
11959 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011960 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011961 queue.enqueueParallelBroadcastLocked(r);
11962 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011964 registeredReceivers = null;
11965 NR = 0;
11966 }
11967
11968 // Merge into one list.
11969 int ir = 0;
11970 if (receivers != null) {
11971 // A special case for PACKAGE_ADDED: do not allow the package
11972 // being added to see this broadcast. This prevents them from
11973 // using this as a back door to get run as soon as they are
11974 // installed. Maybe in the future we want to have a special install
11975 // broadcast or such for apps, but we'd like to deliberately make
11976 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011977 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011978 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11979 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11980 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011981 Uri data = intent.getData();
11982 if (data != null) {
11983 String pkgName = data.getSchemeSpecificPart();
11984 if (pkgName != null) {
11985 skipPackages = new String[] { pkgName };
11986 }
11987 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011988 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011989 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011990 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011991 if (skipPackages != null && (skipPackages.length > 0)) {
11992 for (String skipPackage : skipPackages) {
11993 if (skipPackage != null) {
11994 int NT = receivers.size();
11995 for (int it=0; it<NT; it++) {
11996 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11997 if (curt.activityInfo.packageName.equals(skipPackage)) {
11998 receivers.remove(it);
11999 it--;
12000 NT--;
12001 }
12002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 }
12004 }
12005 }
12006
12007 int NT = receivers != null ? receivers.size() : 0;
12008 int it = 0;
12009 ResolveInfo curt = null;
12010 BroadcastFilter curr = null;
12011 while (it < NT && ir < NR) {
12012 if (curt == null) {
12013 curt = (ResolveInfo)receivers.get(it);
12014 }
12015 if (curr == null) {
12016 curr = registeredReceivers.get(ir);
12017 }
12018 if (curr.getPriority() >= curt.priority) {
12019 // Insert this broadcast record into the final list.
12020 receivers.add(it, curr);
12021 ir++;
12022 curr = null;
12023 it++;
12024 NT++;
12025 } else {
12026 // Skip to the next ResolveInfo in the final list.
12027 it++;
12028 curt = null;
12029 }
12030 }
12031 }
12032 while (ir < NR) {
12033 if (receivers == null) {
12034 receivers = new ArrayList();
12035 }
12036 receivers.add(registeredReceivers.get(ir));
12037 ir++;
12038 }
12039
12040 if ((receivers != null && receivers.size() > 0)
12041 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012042 BroadcastQueue queue = broadcastQueueForIntent(intent);
12043 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012044 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012045 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012046 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012049 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050 if (DEBUG_BROADCAST) {
12051 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012052 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012054 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012055 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012056 queue.enqueueOrderedBroadcastLocked(r);
12057 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 }
12060
Dianne Hackborna4972e92012-03-14 10:38:05 -070012061 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012062 }
12063
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012064 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012065 // Refuse possible leaked file descriptors
12066 if (intent != null && intent.hasFileDescriptors() == true) {
12067 throw new IllegalArgumentException("File descriptors passed in Intent");
12068 }
12069
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012070 int flags = intent.getFlags();
12071
12072 if (!mProcessesReady) {
12073 // if the caller really truly claims to know what they're doing, go
12074 // ahead and allow the broadcast without launching any receivers
12075 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12076 intent = new Intent(intent);
12077 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12078 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12079 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12080 + " before boot completion");
12081 throw new IllegalStateException("Cannot broadcast before boot completed");
12082 }
12083 }
12084
12085 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12086 throw new IllegalArgumentException(
12087 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12088 }
12089
12090 return intent;
12091 }
12092
12093 public final int broadcastIntent(IApplicationThread caller,
12094 Intent intent, String resolvedType, IIntentReceiver resultTo,
12095 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012096 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012097 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012099 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12102 final int callingPid = Binder.getCallingPid();
12103 final int callingUid = Binder.getCallingUid();
12104 final long origId = Binder.clearCallingIdentity();
12105 int res = broadcastIntentLocked(callerApp,
12106 callerApp != null ? callerApp.info.packageName : null,
12107 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012108 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070012109 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012110 Binder.restoreCallingIdentity(origId);
12111 return res;
12112 }
12113 }
12114
12115 int broadcastIntentInPackage(String packageName, int uid,
12116 Intent intent, String resolvedType, IIntentReceiver resultTo,
12117 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012118 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012119 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012120 intent = verifyBroadcastLocked(intent);
12121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 final long origId = Binder.clearCallingIdentity();
12123 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12124 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012125 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 Binder.restoreCallingIdentity(origId);
12127 return res;
12128 }
12129 }
12130
Amith Yamasani742a6712011-05-04 14:49:28 -070012131 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 // Refuse possible leaked file descriptors
12133 if (intent != null && intent.hasFileDescriptors() == true) {
12134 throw new IllegalArgumentException("File descriptors passed in Intent");
12135 }
12136
Dianne Hackborn139748f2012-09-24 11:36:57 -070012137 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012138 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 synchronized(this) {
12141 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12142 != PackageManager.PERMISSION_GRANTED) {
12143 String msg = "Permission Denial: unbroadcastIntent() from pid="
12144 + Binder.getCallingPid()
12145 + ", uid=" + Binder.getCallingUid()
12146 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012147 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012148 throw new SecurityException(msg);
12149 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012150 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12151 if (stickies != null) {
12152 ArrayList<Intent> list = stickies.get(intent.getAction());
12153 if (list != null) {
12154 int N = list.size();
12155 int i;
12156 for (i=0; i<N; i++) {
12157 if (intent.filterEquals(list.get(i))) {
12158 list.remove(i);
12159 break;
12160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012161 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012162 if (list.size() <= 0) {
12163 stickies.remove(intent.getAction());
12164 }
12165 }
12166 if (stickies.size() <= 0) {
12167 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012168 }
12169 }
12170 }
12171 }
12172
12173 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12174 String resultData, Bundle resultExtras, boolean resultAbort,
12175 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012176 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12177 if (r == null) {
12178 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012179 return false;
12180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181
Christopher Tatef46723b2012-01-26 14:19:24 -080012182 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12183 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184 }
12185
12186 public void finishReceiver(IBinder who, int resultCode, String resultData,
12187 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012188 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189
12190 // Refuse possible leaked file descriptors
12191 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12192 throw new IllegalArgumentException("File descriptors passed in Bundle");
12193 }
12194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012196 try {
12197 boolean doNext = false;
12198 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199
Christopher Tatef46723b2012-01-26 14:19:24 -080012200 synchronized(this) {
12201 r = broadcastRecordForReceiverLocked(who);
12202 if (r != null) {
12203 doNext = r.queue.finishReceiverLocked(r, resultCode,
12204 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012205 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012206 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012207
Christopher Tatef46723b2012-01-26 14:19:24 -080012208 if (doNext) {
12209 r.queue.processNextBroadcast(false);
12210 }
12211 trimApplications();
12212 } finally {
12213 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 // =========================================================
12218 // INSTRUMENTATION
12219 // =========================================================
12220
12221 public boolean startInstrumentation(ComponentName className,
12222 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012223 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
12224 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012225 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012226 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012227 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 // Refuse possible leaked file descriptors
12229 if (arguments != null && arguments.hasFileDescriptors()) {
12230 throw new IllegalArgumentException("File descriptors passed in Bundle");
12231 }
12232
12233 synchronized(this) {
12234 InstrumentationInfo ii = null;
12235 ApplicationInfo ai = null;
12236 try {
12237 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012238 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012239 ai = AppGlobals.getPackageManager().getApplicationInfo(
12240 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012242 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012243 }
12244 if (ii == null) {
12245 reportStartInstrumentationFailure(watcher, className,
12246 "Unable to find instrumentation info for: " + className);
12247 return false;
12248 }
12249 if (ai == null) {
12250 reportStartInstrumentationFailure(watcher, className,
12251 "Unable to find instrumentation target package: " + ii.targetPackage);
12252 return false;
12253 }
12254
12255 int match = mContext.getPackageManager().checkSignatures(
12256 ii.targetPackage, ii.packageName);
12257 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12258 String msg = "Permission Denial: starting instrumentation "
12259 + className + " from pid="
12260 + Binder.getCallingPid()
12261 + ", uid=" + Binder.getCallingPid()
12262 + " not allowed because package " + ii.packageName
12263 + " does not have a signature matching the target "
12264 + ii.targetPackage;
12265 reportStartInstrumentationFailure(watcher, className, msg);
12266 throw new SecurityException(msg);
12267 }
12268
12269 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012270 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012271 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012272 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012273 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012274 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275 app.instrumentationProfileFile = profileFile;
12276 app.instrumentationArguments = arguments;
12277 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012278 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012279 app.instrumentationResultClass = className;
12280 Binder.restoreCallingIdentity(origId);
12281 }
12282
12283 return true;
12284 }
12285
12286 /**
12287 * Report errors that occur while attempting to start Instrumentation. Always writes the
12288 * error to the logs, but if somebody is watching, send the report there too. This enables
12289 * the "am" command to report errors with more information.
12290 *
12291 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12292 * @param cn The component name of the instrumentation.
12293 * @param report The error report.
12294 */
12295 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12296 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012297 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298 try {
12299 if (watcher != null) {
12300 Bundle results = new Bundle();
12301 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12302 results.putString("Error", report);
12303 watcher.instrumentationStatus(cn, -1, results);
12304 }
12305 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012306 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012307 }
12308 }
12309
12310 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12311 if (app.instrumentationWatcher != null) {
12312 try {
12313 // NOTE: IInstrumentationWatcher *must* be oneway here
12314 app.instrumentationWatcher.instrumentationFinished(
12315 app.instrumentationClass,
12316 resultCode,
12317 results);
12318 } catch (RemoteException e) {
12319 }
12320 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012321 if (app.instrumentationUiAutomationConnection != null) {
12322 try {
12323 app.instrumentationUiAutomationConnection.shutdown();
12324 } catch (RemoteException re) {
12325 /* ignore */
12326 }
12327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012328 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012329 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012331 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012332 app.instrumentationProfileFile = null;
12333 app.instrumentationArguments = null;
12334
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012335 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 }
12337
12338 public void finishInstrumentation(IApplicationThread target,
12339 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012340 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 // Refuse possible leaked file descriptors
12342 if (results != null && results.hasFileDescriptors()) {
12343 throw new IllegalArgumentException("File descriptors passed in Intent");
12344 }
12345
12346 synchronized(this) {
12347 ProcessRecord app = getRecordForAppLocked(target);
12348 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012349 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 return;
12351 }
12352 final long origId = Binder.clearCallingIdentity();
12353 finishInstrumentationLocked(app, resultCode, results);
12354 Binder.restoreCallingIdentity(origId);
12355 }
12356 }
12357
12358 // =========================================================
12359 // CONFIGURATION
12360 // =========================================================
12361
12362 public ConfigurationInfo getDeviceConfigurationInfo() {
12363 ConfigurationInfo config = new ConfigurationInfo();
12364 synchronized (this) {
12365 config.reqTouchScreen = mConfiguration.touchscreen;
12366 config.reqKeyboardType = mConfiguration.keyboard;
12367 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012368 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12369 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012370 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12371 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012372 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12373 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012374 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12375 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012376 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 }
12378 return config;
12379 }
12380
12381 public Configuration getConfiguration() {
12382 Configuration ci;
12383 synchronized(this) {
12384 ci = new Configuration(mConfiguration);
12385 }
12386 return ci;
12387 }
12388
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012389 public void updatePersistentConfiguration(Configuration values) {
12390 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12391 "updateConfiguration()");
12392 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12393 "updateConfiguration()");
12394 if (values == null) {
12395 throw new NullPointerException("Configuration must not be null");
12396 }
12397
12398 synchronized(this) {
12399 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012400 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012401 Binder.restoreCallingIdentity(origId);
12402 }
12403 }
12404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 public void updateConfiguration(Configuration values) {
12406 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12407 "updateConfiguration()");
12408
12409 synchronized(this) {
12410 if (values == null && mWindowManager != null) {
12411 // sentinel: fetch the current configuration from the window manager
12412 values = mWindowManager.computeNewConfiguration();
12413 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012414
12415 if (mWindowManager != null) {
12416 mProcessList.applyDisplaySize(mWindowManager);
12417 }
12418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012420 if (values != null) {
12421 Settings.System.clearConfiguration(values);
12422 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012423 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012424 Binder.restoreCallingIdentity(origId);
12425 }
12426 }
12427
12428 /**
12429 * Do either or both things: (1) change the current configuration, and (2)
12430 * make sure the given activity is running with the (now) current
12431 * configuration. Returns true if the activity has been left running, or
12432 * false if <var>starting</var> is being destroyed to match the new
12433 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012434 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012436 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012437 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012438 // do nothing if we are headless
12439 if (mHeadless) return true;
12440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012441 int changes = 0;
12442
12443 boolean kept = true;
12444
12445 if (values != null) {
12446 Configuration newConfig = new Configuration(mConfiguration);
12447 changes = newConfig.updateFrom(values);
12448 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012449 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012450 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012451 }
12452
Doug Zongker2bec3d42009-12-04 12:52:44 -080012453 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012454
Dianne Hackborn813075a62011-11-14 17:45:19 -080012455 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012456 saveLocaleLocked(values.locale,
12457 !values.locale.equals(mConfiguration.locale),
12458 values.userSetLocale);
12459 }
12460
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012461 mConfigurationSeq++;
12462 if (mConfigurationSeq <= 0) {
12463 mConfigurationSeq = 1;
12464 }
12465 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012467 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012468
12469 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012470
12471 // TODO: If our config changes, should we auto dismiss any currently
12472 // showing dialogs?
12473 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012474
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012475 AttributeCache ac = AttributeCache.instance();
12476 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012477 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012480 // Make sure all resources in our process are updated
12481 // right now, so that anyone who is going to retrieve
12482 // resource values after we return will be sure to get
12483 // the new ones. This is especially important during
12484 // boot, where the first config change needs to guarantee
12485 // all resources have that config before following boot
12486 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012487 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012488
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012489 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012490 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012491 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012492 mHandler.sendMessage(msg);
12493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012495 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12496 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012497 try {
12498 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012499 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012500 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012501 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012502 }
12503 } catch (Exception e) {
12504 }
12505 }
12506 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012507 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012508 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12509 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012510 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012511 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12512 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012513 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012514 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12515 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12516 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012517 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12518 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012520 }
12521 }
12522
12523 if (changes != 0 && starting == null) {
12524 // If the configuration changed, and the caller is not already
12525 // in the process of starting an activity, then find the top
12526 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012527 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012528 }
12529
12530 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012531 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012532 // And we need to make sure at this point that all other activities
12533 // are made visible with the correct configuration.
12534 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012535 }
12536
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012537 if (values != null && mWindowManager != null) {
12538 mWindowManager.setNewConfiguration(mConfiguration);
12539 }
12540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012541 return kept;
12542 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012543
12544 /**
12545 * Decide based on the configuration whether we should shouw the ANR,
12546 * crash, etc dialogs. The idea is that if there is no affordnace to
12547 * press the on-screen buttons, we shouldn't show the dialog.
12548 *
12549 * A thought: SystemUI might also want to get told about this, the Power
12550 * dialog / global actions also might want different behaviors.
12551 */
12552 private static final boolean shouldShowDialogs(Configuration config) {
12553 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12554 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012556
12557 /**
12558 * Save the locale. You must be inside a synchronized (this) block.
12559 */
12560 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12561 if(isDiff) {
12562 SystemProperties.set("user.language", l.getLanguage());
12563 SystemProperties.set("user.region", l.getCountry());
12564 }
12565
12566 if(isPersist) {
12567 SystemProperties.set("persist.sys.language", l.getLanguage());
12568 SystemProperties.set("persist.sys.country", l.getCountry());
12569 SystemProperties.set("persist.sys.localevar", l.getVariant());
12570 }
12571 }
12572
Adam Powelldd8fab22012-03-22 17:47:27 -070012573 @Override
12574 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12575 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012576 return srec != null && srec.task.affinity != null &&
12577 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012578 }
12579
12580 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12581 Intent resultData) {
12582 ComponentName dest = destIntent.getComponent();
12583
12584 synchronized (this) {
12585 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012586 if (srec == null) {
12587 return false;
12588 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012589 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12590 final int start = history.indexOf(srec);
12591 if (start < 0) {
12592 // Current activity is not in history stack; do nothing.
12593 return false;
12594 }
12595 int finishTo = start - 1;
12596 ActivityRecord parent = null;
12597 boolean foundParentInTask = false;
12598 if (dest != null) {
12599 TaskRecord tr = srec.task;
12600 for (int i = start - 1; i >= 0; i--) {
12601 ActivityRecord r = history.get(i);
12602 if (tr != r.task) {
12603 // Couldn't find parent in the same task; stop at the one above this.
12604 // (Root of current task; in-app "home" behavior)
12605 // Always at least finish the current activity.
12606 finishTo = Math.min(start - 1, i + 1);
12607 parent = history.get(finishTo);
12608 break;
12609 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12610 r.info.name.equals(dest.getClassName())) {
12611 finishTo = i;
12612 parent = r;
12613 foundParentInTask = true;
12614 break;
12615 }
12616 }
12617 }
12618
12619 if (mController != null) {
12620 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12621 if (next != null) {
12622 // ask watcher if this is allowed
12623 boolean resumeOK = true;
12624 try {
12625 resumeOK = mController.activityResuming(next.packageName);
12626 } catch (RemoteException e) {
12627 mController = null;
12628 }
12629
12630 if (!resumeOK) {
12631 return false;
12632 }
12633 }
12634 }
12635 final long origId = Binder.clearCallingIdentity();
12636 for (int i = start; i > finishTo; i--) {
12637 ActivityRecord r = history.get(i);
12638 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012639 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012640 // Only return the supplied result for the first activity finished
12641 resultCode = Activity.RESULT_CANCELED;
12642 resultData = null;
12643 }
12644
12645 if (parent != null && foundParentInTask) {
12646 final int parentLaunchMode = parent.info.launchMode;
12647 final int destIntentFlags = destIntent.getFlags();
12648 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12649 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12650 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12651 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012652 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012653 } else {
12654 try {
12655 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012656 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012657 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12658 null, aInfo, parent.appToken, null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012659 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
12660 0, null, true, null);
Adam Powelldd8fab22012-03-22 17:47:27 -070012661 foundParentInTask = res == ActivityManager.START_SUCCESS;
12662 } catch (RemoteException e) {
12663 foundParentInTask = false;
12664 }
12665 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012666 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012667 }
12668 }
12669 Binder.restoreCallingIdentity(origId);
12670 return foundParentInTask;
12671 }
12672 }
12673
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012674 public int getLaunchedFromUid(IBinder activityToken) {
12675 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12676 if (srec == null) {
12677 return -1;
12678 }
12679 return srec.launchedFromUid;
12680 }
12681
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012682 public String getLaunchedFromPackage(IBinder activityToken) {
12683 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12684 if (srec == null) {
12685 return null;
12686 }
12687 return srec.launchedFromPackage;
12688 }
12689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012690 // =========================================================
12691 // LIFETIME MANAGEMENT
12692 // =========================================================
12693
Christopher Tatef46723b2012-01-26 14:19:24 -080012694 // Returns which broadcast queue the app is the current [or imminent] receiver
12695 // on, or 'null' if the app is not an active broadcast recipient.
12696 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12697 BroadcastRecord r = app.curReceiver;
12698 if (r != null) {
12699 return r.queue;
12700 }
12701
12702 // It's not the current receiver, but it might be starting up to become one
12703 synchronized (this) {
12704 for (BroadcastQueue queue : mBroadcastQueues) {
12705 r = queue.mPendingBroadcast;
12706 if (r != null && r.curApp == app) {
12707 // found it; report which queue it's in
12708 return queue;
12709 }
12710 }
12711 }
12712
12713 return null;
12714 }
12715
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012716 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012717 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012718 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012719 // This adjustment has already been computed. If we are calling
12720 // from the top, we may have already computed our adjustment with
12721 // an earlier hidden adjustment that isn't really for us... if
12722 // so, use the new hidden adjustment.
12723 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012724 if (app.hasActivities) {
12725 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12726 } else if (app.hasClientActivities) {
12727 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12728 } else {
12729 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12730 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012731 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012732 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 }
12734
12735 if (app.thread == null) {
12736 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012737 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012738 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 }
12740
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012741 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12742 app.adjSource = null;
12743 app.adjTarget = null;
12744 app.empty = false;
12745 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012746 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012747
12748 final int activitiesSize = app.activities.size();
12749
Dianne Hackborn7d608422011-08-07 16:24:18 -070012750 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012751 // The max adjustment doesn't allow this app to be anything
12752 // below foreground, so it is not worth doing work for it.
12753 app.adjType = "fixed";
12754 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012755 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012756 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012757 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012758 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012759 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012760 // System process can do UI, and when they do we want to have
12761 // them trim their memory after the user leaves the UI. To
12762 // facilitate this, here we need to determine whether or not it
12763 // is currently showing UI.
12764 app.systemNoUi = true;
12765 if (app == TOP_APP) {
12766 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012767 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012768 } else if (activitiesSize > 0) {
12769 for (int j = 0; j < activitiesSize; j++) {
12770 final ActivityRecord r = app.activities.get(j);
12771 if (r.visible) {
12772 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012773 }
12774 if (r.app == app) {
12775 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012776 }
12777 }
12778 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012779 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012780 }
12781
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012782 app.keeping = false;
12783 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012784 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785
The Android Open Source Project4df24232009-03-05 14:34:35 -080012786 // Determine the importance of the process, starting with most
12787 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012788 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012789 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012790 boolean foregroundActivities = false;
12791 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012792 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012793 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012794 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012795 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012796 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012797 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012798 foregroundActivities = true;
12799 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012800 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012801 } else if (app.instrumentationClass != null) {
12802 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012803 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012804 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012805 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012806 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012807 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012808 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012809 // counts as being in the foreground for OOM killer purposes.
12810 // It's placed in a sched group based on the nature of the
12811 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012812 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012813 schedGroup = (queue == mFgBroadcastQueue)
12814 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012815 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012816 } else if (app.executingServices.size() > 0) {
12817 // An app that is currently executing a service callback also
12818 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012819 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012820 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012821 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012822 } else {
12823 // Assume process is hidden (has activities); we will correct
12824 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012825 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012826 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012827 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012828 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012830
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012831 boolean hasStoppingActivities = false;
12832
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012833 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012834 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012835 for (int j = 0; j < activitiesSize; j++) {
12836 final ActivityRecord r = app.activities.get(j);
12837 if (r.visible) {
12838 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012839 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12840 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012841 app.adjType = "visible";
12842 }
12843 schedGroup = Process.THREAD_GROUP_DEFAULT;
12844 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012845 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012846 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012847 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012848 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012849 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12850 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012851 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012852 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012853 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012854 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012855 } else if (r.state == ActivityState.STOPPING) {
12856 // We will apply the actual adjustment later, because
12857 // we want to allow this process to immediately go through
12858 // any memory trimming that is in effect.
12859 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012860 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012861 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012862 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012863 if (r.app == app) {
12864 app.hasActivities = true;
12865 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012866 }
12867 }
12868
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012869 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012870 if (app.hasClientActivities) {
12871 adj = clientHiddenAdj;
12872 app.adjType = "bg-client-act";
12873 } else {
12874 // Whoops, this process is completely empty as far as we know
12875 // at this point.
12876 adj = emptyAdj;
12877 app.empty = true;
12878 app.adjType = "bg-empty";
12879 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012880 }
12881
Dianne Hackborn7d608422011-08-07 16:24:18 -070012882 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012883 if (app.foregroundServices) {
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 = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012888 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012889 } else if (app.forcingToForeground != null) {
12890 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012891 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012892 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012893 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012894 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012895 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012896 }
12897 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012898
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012899 if (app.foregroundServices) {
12900 interesting = true;
12901 }
12902
Dianne Hackborn7d608422011-08-07 16:24:18 -070012903 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012904 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012905 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012906 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012907 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012908 app.adjType = "heavy";
12909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012910
Dianne Hackborn7d608422011-08-07 16:24:18 -070012911 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012912 // This process is hosting what we currently consider to be the
12913 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012914 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012915 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012916 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012917 app.adjType = "home";
12918 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012919
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012920 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12921 && app.activities.size() > 0) {
12922 // This was the previous process that showed UI to the user.
12923 // We want to try to keep it around more aggressively, to give
12924 // a good experience around switching between two apps.
12925 adj = ProcessList.PREVIOUS_APP_ADJ;
12926 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12927 app.hidden = false;
12928 app.adjType = "previous";
12929 }
12930
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012931 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12932 + " reason=" + app.adjType);
12933
The Android Open Source Project4df24232009-03-05 14:34:35 -080012934 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 // there are applications dependent on our services or providers, but
12936 // this gives us a baseline and makes sure we don't get into an
12937 // infinite recursion.
12938 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012939 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940
Christopher Tate6fa95972009-06-05 18:43:55 -070012941 if (mBackupTarget != null && app == mBackupTarget.app) {
12942 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012944 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012945 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012946 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012947 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012948 }
12949 }
12950
Dianne Hackborn7d608422011-08-07 16:24:18 -070012951 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012952 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 final long now = SystemClock.uptimeMillis();
12954 // This process is more important if the top activity is
12955 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012956 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012957 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012958 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012960 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012961 // If this process has shown some UI, let it immediately
12962 // go to the LRU list because it may be pretty heavy with
12963 // UI stuff. We'll tag it with a label just to help
12964 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012965 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012966 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012968 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012969 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012970 // This service has seen some activity within
12971 // recent memory, so we will keep its process ahead
12972 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012973 if (adj > ProcessList.SERVICE_ADJ) {
12974 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012975 app.adjType = "started-services";
12976 app.hidden = false;
12977 }
12978 }
12979 // If we have let the service slide into the background
12980 // state, still have some text describing what it is doing
12981 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012982 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012983 app.adjType = "started-bg-services";
12984 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012985 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012986 // Don't kill this process because it is doing work; it
12987 // has said it is doing work.
12988 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012989 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012990 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012991 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012992 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012994 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012995 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012996 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012997 // XXX should compute this based on the max of
12998 // all connected clients.
12999 ConnectionRecord cr = clist.get(i);
13000 if (cr.binding.client == app) {
13001 // Binding to ourself is not interesting.
13002 continue;
13003 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013004 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013005 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013006 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013007 int myHiddenAdj = hiddenAdj;
13008 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013009 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013010 myHiddenAdj = client.hiddenAdj;
13011 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013012 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013013 }
13014 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013015 int myClientHiddenAdj = clientHiddenAdj;
13016 if (myClientHiddenAdj > client.clientHiddenAdj) {
13017 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
13018 myClientHiddenAdj = client.clientHiddenAdj;
13019 } else {
13020 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
13021 }
13022 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013023 int myEmptyAdj = emptyAdj;
13024 if (myEmptyAdj > client.emptyAdj) {
13025 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
13026 myEmptyAdj = client.emptyAdj;
13027 } else {
13028 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
13029 }
13030 }
13031 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013032 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013033 String adjType = null;
13034 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13035 // Not doing bind OOM management, so treat
13036 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013037 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013038 // If this process has shown some UI, let it immediately
13039 // go to the LRU list because it may be pretty heavy with
13040 // UI stuff. We'll tag it with a label just to help
13041 // debug and understand what is going on.
13042 if (adj > clientAdj) {
13043 adjType = "bound-bg-ui-services";
13044 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013045 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013046 clientAdj = adj;
13047 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013048 if (now >= (s.lastActivity
13049 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013050 // This service has not seen activity within
13051 // recent memory, so allow it to drop to the
13052 // LRU list if there is no other reason to keep
13053 // it around. We'll also tag it with a label just
13054 // to help debug and undertand what is going on.
13055 if (adj > clientAdj) {
13056 adjType = "bound-bg-services";
13057 }
13058 clientAdj = adj;
13059 }
13060 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013061 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13062 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
13063 // If this connection is keeping the service
13064 // created, then we want to try to better follow
13065 // its memory management semantics for activities.
13066 // That is, if it is sitting in the background
13067 // LRU list as a hidden process (with activities),
13068 // we don't want the service it is connected to
13069 // to go into the empty LRU and quickly get killed,
13070 // because I'll we'll do is just end up restarting
13071 // the service.
13072 app.hasClientActivities |= client.hasActivities;
13073 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013074 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013075 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013076 // If this process has recently shown UI, and
13077 // the process that is binding to it is less
13078 // important than being visible, then we don't
13079 // care about the binding as much as we care
13080 // about letting this process get into the LRU
13081 // list to be killed and restarted if needed for
13082 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013083 if (app.hasShownUi && app != mHomeProcess
13084 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013085 adjType = "bound-bg-ui-services";
13086 } else {
13087 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13088 |Context.BIND_IMPORTANT)) != 0) {
13089 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013090 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13091 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13092 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13093 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13094 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013095 adj = clientAdj;
13096 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013097 app.pendingUiClean = true;
13098 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13099 adj = ProcessList.VISIBLE_APP_ADJ;
13100 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013101 }
13102 if (!client.hidden) {
13103 app.hidden = false;
13104 }
13105 if (client.keeping) {
13106 app.keeping = true;
13107 }
13108 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013109 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013110 }
13111 if (adjType != null) {
13112 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013113 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13114 .REASON_SERVICE_IN_USE;
13115 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013116 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013117 app.adjTarget = s.name;
13118 }
13119 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13120 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13121 schedGroup = Process.THREAD_GROUP_DEFAULT;
13122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013123 }
13124 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013125 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013126 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013127 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013128 (a.visible || a.state == ActivityState.RESUMED
13129 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013130 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013131 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13132 schedGroup = Process.THREAD_GROUP_DEFAULT;
13133 }
13134 app.hidden = false;
13135 app.adjType = "service";
13136 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13137 .REASON_SERVICE_IN_USE;
13138 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013139 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013140 app.adjTarget = s.name;
13141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013143 }
13144 }
13145 }
13146 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013147
Dianne Hackborn287952c2010-09-22 22:34:31 -070013148 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013149 // would like to avoid killing it unless it would prevent the current
13150 // application from running. By default we put the process in
13151 // with the rest of the background processes; as we scan through
13152 // its services we may bump it up from there.
13153 if (adj > hiddenAdj) {
13154 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013155 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013156 app.adjType = "bg-services";
13157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013158 }
13159
Dianne Hackborn7d608422011-08-07 16:24:18 -070013160 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013161 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013162 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013163 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013164 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013165 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013166 for (int i = cpr.connections.size()-1;
13167 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13168 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13169 i--) {
13170 ContentProviderConnection conn = cpr.connections.get(i);
13171 ProcessRecord client = conn.client;
13172 if (client == app) {
13173 // Being our own client is not interesting.
13174 continue;
13175 }
13176 int myHiddenAdj = hiddenAdj;
13177 if (myHiddenAdj > client.hiddenAdj) {
13178 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13179 myHiddenAdj = client.hiddenAdj;
13180 } else {
13181 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013182 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013183 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013184 int myClientHiddenAdj = clientHiddenAdj;
13185 if (myClientHiddenAdj > client.clientHiddenAdj) {
13186 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13187 myClientHiddenAdj = client.clientHiddenAdj;
13188 } else {
13189 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13190 }
13191 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013192 int myEmptyAdj = emptyAdj;
13193 if (myEmptyAdj > client.emptyAdj) {
13194 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13195 myEmptyAdj = client.emptyAdj;
13196 } else {
13197 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13198 }
13199 }
13200 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013201 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013202 if (adj > clientAdj) {
13203 if (app.hasShownUi && app != mHomeProcess
13204 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13205 app.adjType = "bg-ui-provider";
13206 } else {
13207 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13208 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13209 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013211 if (!client.hidden) {
13212 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013213 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013214 if (client.keeping) {
13215 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013216 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013217 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13218 .REASON_PROVIDER_IN_USE;
13219 app.adjSource = client;
13220 app.adjSourceOom = clientAdj;
13221 app.adjTarget = cpr.name;
13222 }
13223 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13224 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 }
13226 }
13227 // If the provider has external (non-framework) process
13228 // dependencies, ensure that its adjustment is at least
13229 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013230 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013231 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13232 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013233 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013234 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013235 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013236 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013237 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 }
13239 }
13240 }
13241 }
13242
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013243 if (adj == ProcessList.SERVICE_ADJ) {
13244 if (doingAll) {
13245 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13246 mNewNumServiceProcs++;
13247 }
13248 if (app.serviceb) {
13249 adj = ProcessList.SERVICE_B_ADJ;
13250 }
13251 } else {
13252 app.serviceb = false;
13253 }
13254
13255 app.nonStoppingAdj = adj;
13256
13257 if (hasStoppingActivities) {
13258 // Only upgrade adjustment.
13259 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13260 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13261 app.adjType = "stopping";
13262 }
13263 }
13264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265 app.curRawAdj = adj;
13266
Joe Onorato8a9b2202010-02-26 18:56:32 -080013267 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013268 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13269 if (adj > app.maxAdj) {
13270 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013271 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013272 schedGroup = Process.THREAD_GROUP_DEFAULT;
13273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013274 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013275 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013276 app.keeping = true;
13277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013279 if (app.hasAboveClient) {
13280 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13281 // then we need to drop its adjustment to be lower than the service's
13282 // in order to honor the request. We want to drop it by one adjustment
13283 // level... but there is special meaning applied to various levels so
13284 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013285 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013286 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013287 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13288 adj = ProcessList.VISIBLE_APP_ADJ;
13289 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13290 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13291 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13292 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013293 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013294 adj++;
13295 }
13296 }
13297
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013298 int importance = app.memImportance;
13299 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13300 app.curAdj = adj;
13301 app.curSchedGroup = schedGroup;
13302 if (!interesting) {
13303 // For this reporting, if there is not something explicitly
13304 // interesting in this process then we will push it to the
13305 // background importance.
13306 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13307 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13308 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13309 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13310 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13311 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13312 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13313 } else if (adj >= ProcessList.SERVICE_ADJ) {
13314 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13315 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13316 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13317 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13318 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13319 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13320 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13321 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13322 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13323 } else {
13324 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13325 }
13326 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013327
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013328 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13329 if (foregroundActivities != app.foregroundActivities) {
13330 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13331 }
13332 if (changes != 0) {
13333 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13334 app.memImportance = importance;
13335 app.foregroundActivities = foregroundActivities;
13336 int i = mPendingProcessChanges.size()-1;
13337 ProcessChangeItem item = null;
13338 while (i >= 0) {
13339 item = mPendingProcessChanges.get(i);
13340 if (item.pid == app.pid) {
13341 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13342 break;
13343 }
13344 i--;
13345 }
13346 if (i < 0) {
13347 // No existing item in pending changes; need a new one.
13348 final int NA = mAvailProcessChanges.size();
13349 if (NA > 0) {
13350 item = mAvailProcessChanges.remove(NA-1);
13351 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13352 } else {
13353 item = new ProcessChangeItem();
13354 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13355 }
13356 item.changes = 0;
13357 item.pid = app.pid;
13358 item.uid = app.info.uid;
13359 if (mPendingProcessChanges.size() == 0) {
13360 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13361 "*** Enqueueing dispatch processes changed!");
13362 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13363 }
13364 mPendingProcessChanges.add(item);
13365 }
13366 item.changes |= changes;
13367 item.importance = importance;
13368 item.foregroundActivities = foregroundActivities;
13369 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13370 + Integer.toHexString(System.identityHashCode(item))
13371 + " " + app.toShortString() + ": changes=" + item.changes
13372 + " importance=" + item.importance
13373 + " foreground=" + item.foregroundActivities
13374 + " type=" + app.adjType + " source=" + app.adjSource
13375 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013376 }
13377
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013378 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013379 }
13380
13381 /**
13382 * Ask a given process to GC right now.
13383 */
13384 final void performAppGcLocked(ProcessRecord app) {
13385 try {
13386 app.lastRequestedGc = SystemClock.uptimeMillis();
13387 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013388 if (app.reportLowMemory) {
13389 app.reportLowMemory = false;
13390 app.thread.scheduleLowMemory();
13391 } else {
13392 app.thread.processInBackground();
13393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013394 }
13395 } catch (Exception e) {
13396 // whatever.
13397 }
13398 }
13399
13400 /**
13401 * Returns true if things are idle enough to perform GCs.
13402 */
Josh Bartel7f208742010-02-25 11:01:44 -060013403 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013404 boolean processingBroadcasts = false;
13405 for (BroadcastQueue q : mBroadcastQueues) {
13406 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13407 processingBroadcasts = true;
13408 }
13409 }
13410 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013411 && (mSleeping || (mMainStack.mResumedActivity != null &&
13412 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 }
13414
13415 /**
13416 * Perform GCs on all processes that are waiting for it, but only
13417 * if things are idle.
13418 */
13419 final void performAppGcsLocked() {
13420 final int N = mProcessesToGc.size();
13421 if (N <= 0) {
13422 return;
13423 }
Josh Bartel7f208742010-02-25 11:01:44 -060013424 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013425 while (mProcessesToGc.size() > 0) {
13426 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013427 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013428 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13429 <= SystemClock.uptimeMillis()) {
13430 // To avoid spamming the system, we will GC processes one
13431 // at a time, waiting a few seconds between each.
13432 performAppGcLocked(proc);
13433 scheduleAppGcsLocked();
13434 return;
13435 } else {
13436 // It hasn't been long enough since we last GCed this
13437 // process... put it in the list to wait for its time.
13438 addProcessToGcListLocked(proc);
13439 break;
13440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013441 }
13442 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013443
13444 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 }
13446 }
13447
13448 /**
13449 * If all looks good, perform GCs on all processes waiting for them.
13450 */
13451 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013452 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 performAppGcsLocked();
13454 return;
13455 }
13456 // Still not idle, wait some more.
13457 scheduleAppGcsLocked();
13458 }
13459
13460 /**
13461 * Schedule the execution of all pending app GCs.
13462 */
13463 final void scheduleAppGcsLocked() {
13464 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013465
13466 if (mProcessesToGc.size() > 0) {
13467 // Schedule a GC for the time to the next process.
13468 ProcessRecord proc = mProcessesToGc.get(0);
13469 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13470
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013471 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013472 long now = SystemClock.uptimeMillis();
13473 if (when < (now+GC_TIMEOUT)) {
13474 when = now + GC_TIMEOUT;
13475 }
13476 mHandler.sendMessageAtTime(msg, when);
13477 }
13478 }
13479
13480 /**
13481 * Add a process to the array of processes waiting to be GCed. Keeps the
13482 * list in sorted order by the last GC time. The process can't already be
13483 * on the list.
13484 */
13485 final void addProcessToGcListLocked(ProcessRecord proc) {
13486 boolean added = false;
13487 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13488 if (mProcessesToGc.get(i).lastRequestedGc <
13489 proc.lastRequestedGc) {
13490 added = true;
13491 mProcessesToGc.add(i+1, proc);
13492 break;
13493 }
13494 }
13495 if (!added) {
13496 mProcessesToGc.add(0, proc);
13497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 }
13499
13500 /**
13501 * Set up to ask a process to GC itself. This will either do it
13502 * immediately, or put it on the list of processes to gc the next
13503 * time things are idle.
13504 */
13505 final void scheduleAppGcLocked(ProcessRecord app) {
13506 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013507 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013508 return;
13509 }
13510 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013511 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 scheduleAppGcsLocked();
13513 }
13514 }
13515
Dianne Hackborn287952c2010-09-22 22:34:31 -070013516 final void checkExcessivePowerUsageLocked(boolean doKills) {
13517 updateCpuStatsNow();
13518
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013519 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013520 boolean doWakeKills = doKills;
13521 boolean doCpuKills = doKills;
13522 if (mLastPowerCheckRealtime == 0) {
13523 doWakeKills = false;
13524 }
13525 if (mLastPowerCheckUptime == 0) {
13526 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013527 }
13528 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013529 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013530 }
13531 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013532 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13533 final long curUptime = SystemClock.uptimeMillis();
13534 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13535 mLastPowerCheckRealtime = curRealtime;
13536 mLastPowerCheckUptime = curUptime;
13537 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13538 doWakeKills = false;
13539 }
13540 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13541 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013542 }
13543 int i = mLruProcesses.size();
13544 while (i > 0) {
13545 i--;
13546 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013547 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013548 long wtime;
13549 synchronized (stats) {
13550 wtime = stats.getProcessWakeTime(app.info.uid,
13551 app.pid, curRealtime);
13552 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013553 long wtimeUsed = wtime - app.lastWakeTime;
13554 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13555 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013556 StringBuilder sb = new StringBuilder(128);
13557 sb.append("Wake for ");
13558 app.toShortString(sb);
13559 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013560 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013561 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013562 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013563 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013564 sb.append((wtimeUsed*100)/realtimeSince);
13565 sb.append("%)");
13566 Slog.i(TAG, sb.toString());
13567 sb.setLength(0);
13568 sb.append("CPU for ");
13569 app.toShortString(sb);
13570 sb.append(": over ");
13571 TimeUtils.formatDuration(uptimeSince, sb);
13572 sb.append(" used ");
13573 TimeUtils.formatDuration(cputimeUsed, sb);
13574 sb.append(" (");
13575 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013576 sb.append("%)");
13577 Slog.i(TAG, sb.toString());
13578 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013579 // If a process has held a wake lock for more
13580 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013581 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013582 if (doWakeKills && realtimeSince > 0
13583 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13584 synchronized (stats) {
13585 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13586 realtimeSince, wtimeUsed);
13587 }
13588 Slog.w(TAG, "Excessive wake lock in " + app.processName
13589 + " (pid " + app.pid + "): held " + wtimeUsed
13590 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013591 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013592 app.processName, app.setAdj, "excessive wake lock");
13593 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013594 } else if (doCpuKills && uptimeSince > 0
13595 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13596 synchronized (stats) {
13597 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13598 uptimeSince, cputimeUsed);
13599 }
13600 Slog.w(TAG, "Excessive CPU in " + app.processName
13601 + " (pid " + app.pid + "): used " + cputimeUsed
13602 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013603 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013604 app.processName, app.setAdj, "excessive cpu");
13605 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013606 } else {
13607 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013608 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013609 }
13610 }
13611 }
13612 }
13613
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013614 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013615 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013617 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013618 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013619
13620 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013621 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622 }
13623
Dianne Hackborn287952c2010-09-22 22:34:31 -070013624 final boolean wasKeeping = app.keeping;
13625
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013626 boolean success = true;
13627
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013628 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013629
Jeff Brown10e89712011-07-08 18:52:57 -070013630 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013631 if (wasKeeping && !app.keeping) {
13632 // This app is no longer something we want to keep. Note
13633 // its current wake lock time to later know to kill it if
13634 // it is not behaving well.
13635 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13636 synchronized (stats) {
13637 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13638 app.pid, SystemClock.elapsedRealtime());
13639 }
13640 app.lastCpuTime = app.curCpuTime;
13641 }
13642
13643 app.setRawAdj = app.curRawAdj;
13644 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013645
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013646 if (app.curAdj != app.setAdj) {
13647 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013648 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013649 TAG, "Set " + app.pid + " " + app.processName +
13650 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013651 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013652 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013653 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013654 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013655 }
13656 }
13657 if (app.setSchedGroup != app.curSchedGroup) {
13658 app.setSchedGroup = app.curSchedGroup;
13659 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13660 "Setting process group of " + app.processName
13661 + " to " + app.curSchedGroup);
13662 if (app.waitingToKill != null &&
13663 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13664 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013665 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013666 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013667 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013668 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013669 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013670 } else {
13671 if (true) {
13672 long oldId = Binder.clearCallingIdentity();
13673 try {
13674 Process.setProcessGroup(app.pid, app.curSchedGroup);
13675 } catch (Exception e) {
13676 Slog.w(TAG, "Failed setting process group of " + app.pid
13677 + " to " + app.curSchedGroup);
13678 e.printStackTrace();
13679 } finally {
13680 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013681 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013682 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013683 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013684 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013685 app.thread.setSchedulingGroup(app.curSchedGroup);
13686 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013687 }
13688 }
13689 }
13690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013691 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013692 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013693 }
13694
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013695 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013696 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013698 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013699 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013700 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 }
13702 }
13703 return resumedActivity;
13704 }
13705
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013706 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013707 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013708 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13709 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013710 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13711 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712
13713 mAdjSeq++;
13714
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013715 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13716 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013717 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13718 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013719 if (nowHidden != wasHidden) {
13720 // Changed to/from hidden state, so apps after it in the LRU
13721 // list may also be changed.
13722 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013723 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013724 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013725 }
13726
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013727 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013728 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013729 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013730 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013731
13732 if (false) {
13733 RuntimeException e = new RuntimeException();
13734 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013735 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013736 }
13737
13738 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013739 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013740
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013741 final int emptyProcessLimit;
13742 final int hiddenProcessLimit;
13743 if (mProcessLimit <= 0) {
13744 emptyProcessLimit = hiddenProcessLimit = 0;
13745 } else if (mProcessLimit == 1) {
13746 emptyProcessLimit = 1;
13747 hiddenProcessLimit = 0;
13748 } else {
13749 emptyProcessLimit = (mProcessLimit*2)/3;
13750 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13751 }
13752
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013753 // Let's determine how many processes we have running vs.
13754 // how many slots we have for background processes; we may want
13755 // to put multiple processes in a slot of there are enough of
13756 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013757 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13758 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013759 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13760 if (numEmptyProcs > hiddenProcessLimit) {
13761 // If there are more empty processes than our limit on hidden
13762 // processes, then use the hidden process limit for the factor.
13763 // This ensures that the really old empty processes get pushed
13764 // down to the bottom, so if we are running low on memory we will
13765 // have a better chance at keeping around more hidden processes
13766 // instead of a gazillion empty processes.
13767 numEmptyProcs = hiddenProcessLimit;
13768 }
13769 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013770 if (emptyFactor < 1) emptyFactor = 1;
13771 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13772 if (hiddenFactor < 1) hiddenFactor = 1;
13773 int stepHidden = 0;
13774 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013775 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013776 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013777 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013778
13779 mNumNonHiddenProcs = 0;
13780 mNumHiddenProcs = 0;
13781
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013782 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013784 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013785 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013786 int nextHiddenAdj = curHiddenAdj+1;
13787 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13788 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013789 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013790 while (i > 0) {
13791 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013792 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013793 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013794 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013795 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013796 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13797 // This process was assigned as a hidden process... step the
13798 // hidden level.
13799 mNumHiddenProcs++;
13800 if (curHiddenAdj != nextHiddenAdj) {
13801 stepHidden++;
13802 if (stepHidden >= hiddenFactor) {
13803 stepHidden = 0;
13804 curHiddenAdj = nextHiddenAdj;
13805 nextHiddenAdj += 2;
13806 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13807 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13808 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013809 if (curClientHiddenAdj <= curHiddenAdj) {
13810 curClientHiddenAdj = curHiddenAdj + 1;
13811 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13812 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13813 }
13814 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013815 }
13816 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013817 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013818 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013819 Slog.i(TAG, "No longer want " + app.processName
13820 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013821 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013822 app.processName, app.setAdj, "too many background");
13823 app.killedBackground = true;
13824 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013825 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013826 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13827 // This process has a client that has activities. We will have
13828 // given it the current hidden adj; here we will just leave it
13829 // without stepping the hidden adj.
13830 curClientHiddenAdj++;
13831 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13832 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13833 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013834 } else {
13835 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13836 // This process was assigned as an empty process... step the
13837 // empty level.
13838 if (curEmptyAdj != nextEmptyAdj) {
13839 stepEmpty++;
13840 if (stepEmpty >= emptyFactor) {
13841 stepEmpty = 0;
13842 curEmptyAdj = nextEmptyAdj;
13843 nextEmptyAdj += 2;
13844 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13845 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13846 }
13847 }
13848 }
13849 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13850 mNumNonHiddenProcs++;
13851 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013852 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13853 && !app.hasClientActivities) {
13854 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13855 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013856 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013857 + " (pid " + app.pid + "): empty for "
13858 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13859 / 1000) + "s");
13860 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13861 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013862 app.killedBackground = true;
13863 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013864 } else {
13865 numEmpty++;
13866 if (numEmpty > emptyProcessLimit) {
13867 Slog.i(TAG, "No longer want " + app.processName
13868 + " (pid " + app.pid + "): empty #" + numEmpty);
13869 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13870 app.processName, app.setAdj, "too many background");
13871 app.killedBackground = true;
13872 Process.killProcessQuiet(app.pid);
13873 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013874 }
13875 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013876 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013877 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013878 // If this is an isolated process, and there are no
13879 // services running in it, then the process is no longer
13880 // needed. We agressively kill these because we can by
13881 // definition not re-use the same process again, and it is
13882 // good to avoid having whatever code was running in them
13883 // left sitting around after no longer needed.
13884 Slog.i(TAG, "Isolated process " + app.processName
13885 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013886 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013887 app.processName, app.setAdj, "isolated not needed");
13888 app.killedBackground = true;
13889 Process.killProcessQuiet(app.pid);
13890 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013891 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13892 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13893 && !app.killedBackground) {
13894 numTrimming++;
13895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013896 }
13897 }
13898
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013899 mNumServiceProcs = mNewNumServiceProcs;
13900
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013901 // Now determine the memory trimming level of background processes.
13902 // Unfortunately we need to start at the back of the list to do this
13903 // properly. We only do this if the number of background apps we
13904 // are managing to keep around is less than half the maximum we desire;
13905 // if we are keeping a good number around, we'll let them use whatever
13906 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013907 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13908 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013909 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013910 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013911 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013912 int minFactor = 2;
13913 if (mHomeProcess != null) minFactor++;
13914 if (mPreviousProcess != null) minFactor++;
13915 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013916 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013917 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013918 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013919 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013920 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013921 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13922 } else {
13923 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13924 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013925 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013926 for (i=0; i<N; i++) {
13927 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013928 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13929 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013930 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013931 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13932 try {
13933 app.thread.scheduleTrimMemory(curLevel);
13934 } catch (RemoteException e) {
13935 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013936 if (false) {
13937 // For now we won't do this; our memory trimming seems
13938 // to be good enough at this point that destroying
13939 // activities causes more harm than good.
13940 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13941 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013942 // Need to do this on its own message because the stack may not
13943 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013944 // For these apps we will also finish their activities
13945 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013946 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013947 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013948 }
13949 }
13950 app.trimMemoryLevel = curLevel;
13951 step++;
13952 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013953 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013954 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013955 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13956 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013957 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013958 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13959 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013960 break;
13961 }
13962 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013963 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013964 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013965 && app.thread != null) {
13966 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013967 app.thread.scheduleTrimMemory(
13968 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013969 } catch (RemoteException e) {
13970 }
13971 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013972 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013973 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013974 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013975 && app.pendingUiClean) {
13976 // If this application is now in the background and it
13977 // had done UI, then give it the special trim level to
13978 // have it free UI resources.
13979 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13980 if (app.trimMemoryLevel < level && app.thread != null) {
13981 try {
13982 app.thread.scheduleTrimMemory(level);
13983 } catch (RemoteException e) {
13984 }
13985 }
13986 app.pendingUiClean = false;
13987 }
13988 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013989 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013990 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013991 } catch (RemoteException e) {
13992 }
13993 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013994 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013995 }
13996 }
13997 } else {
13998 final int N = mLruProcesses.size();
13999 for (i=0; i<N; i++) {
14000 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014001 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014002 && app.pendingUiClean) {
14003 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14004 && app.thread != null) {
14005 try {
14006 app.thread.scheduleTrimMemory(
14007 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14008 } catch (RemoteException e) {
14009 }
14010 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014011 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014012 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014013 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014014 }
14015 }
14016
14017 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014018 // Need to do this on its own message because the stack may not
14019 // be in a consistent state at this point.
14020 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014022 }
14023
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014024 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014025 synchronized (this) {
14026 int i;
14027
14028 // First remove any unused application processes whose package
14029 // has been removed.
14030 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14031 final ProcessRecord app = mRemovedProcesses.get(i);
14032 if (app.activities.size() == 0
14033 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014034 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014035 TAG, "Exiting empty application process "
14036 + app.processName + " ("
14037 + (app.thread != null ? app.thread.asBinder() : null)
14038 + ")\n");
14039 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014040 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014041 app.processName, app.setAdj, "empty");
14042 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014043 } else {
14044 try {
14045 app.thread.scheduleExit();
14046 } catch (Exception e) {
14047 // Ignore exceptions.
14048 }
14049 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014050 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014051 mRemovedProcesses.remove(i);
14052
14053 if (app.persistent) {
14054 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014055 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014056 }
14057 }
14058 }
14059 }
14060
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014061 // Now update the oom adj for all processes.
14062 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014063 }
14064 }
14065
14066 /** This method sends the specified signal to each of the persistent apps */
14067 public void signalPersistentProcesses(int sig) throws RemoteException {
14068 if (sig != Process.SIGNAL_USR1) {
14069 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14070 }
14071
14072 synchronized (this) {
14073 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14074 != PackageManager.PERMISSION_GRANTED) {
14075 throw new SecurityException("Requires permission "
14076 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14077 }
14078
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014079 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14080 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014081 if (r.thread != null && r.persistent) {
14082 Process.sendSignal(r.pid, sig);
14083 }
14084 }
14085 }
14086 }
14087
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014088 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14089 if (proc == null || proc == mProfileProc) {
14090 proc = mProfileProc;
14091 path = mProfileFile;
14092 profileType = mProfileType;
14093 clearProfilerLocked();
14094 }
14095 if (proc == null) {
14096 return;
14097 }
14098 try {
14099 proc.thread.profilerControl(false, path, null, profileType);
14100 } catch (RemoteException e) {
14101 throw new IllegalStateException("Process disappeared");
14102 }
14103 }
14104
14105 private void clearProfilerLocked() {
14106 if (mProfileFd != null) {
14107 try {
14108 mProfileFd.close();
14109 } catch (IOException e) {
14110 }
14111 }
14112 mProfileApp = null;
14113 mProfileProc = null;
14114 mProfileFile = null;
14115 mProfileType = 0;
14116 mAutoStopProfiler = false;
14117 }
14118
Dianne Hackborn1676c852012-09-10 14:52:30 -070014119 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014120 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014121
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014122 try {
14123 synchronized (this) {
14124 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14125 // its own permission.
14126 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14127 != PackageManager.PERMISSION_GRANTED) {
14128 throw new SecurityException("Requires permission "
14129 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014130 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014131
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014132 if (start && fd == null) {
14133 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014134 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014135
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014136 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014137 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014138 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014139 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014140
14141 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014142 throw new IllegalArgumentException("Unknown process: " + process);
14143 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014144
14145 if (start) {
14146 stopProfilerLocked(null, null, 0);
14147 setProfileApp(proc.info, proc.processName, path, fd, false);
14148 mProfileProc = proc;
14149 mProfileType = profileType;
14150 try {
14151 fd = fd.dup();
14152 } catch (IOException e) {
14153 fd = null;
14154 }
14155 proc.thread.profilerControl(start, path, fd, profileType);
14156 fd = null;
14157 mProfileFd = null;
14158 } else {
14159 stopProfilerLocked(proc, path, profileType);
14160 if (fd != null) {
14161 try {
14162 fd.close();
14163 } catch (IOException e) {
14164 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014165 }
14166 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014167
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014168 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014169 }
14170 } catch (RemoteException e) {
14171 throw new IllegalStateException("Process disappeared");
14172 } finally {
14173 if (fd != null) {
14174 try {
14175 fd.close();
14176 } catch (IOException e) {
14177 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014178 }
14179 }
14180 }
Andy McFadden824c5102010-07-09 16:26:57 -070014181
Dianne Hackborn1676c852012-09-10 14:52:30 -070014182 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014183 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014184 userId, true, true, callName, null);
14185 ProcessRecord proc = null;
14186 try {
14187 int pid = Integer.parseInt(process);
14188 synchronized (mPidsSelfLocked) {
14189 proc = mPidsSelfLocked.get(pid);
14190 }
14191 } catch (NumberFormatException e) {
14192 }
14193
14194 if (proc == null) {
14195 HashMap<String, SparseArray<ProcessRecord>> all
14196 = mProcessNames.getMap();
14197 SparseArray<ProcessRecord> procs = all.get(process);
14198 if (procs != null && procs.size() > 0) {
14199 proc = procs.valueAt(0);
14200 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14201 for (int i=1; i<procs.size(); i++) {
14202 ProcessRecord thisProc = procs.valueAt(i);
14203 if (thisProc.userId == userId) {
14204 proc = thisProc;
14205 break;
14206 }
14207 }
14208 }
14209 }
14210 }
14211
14212 return proc;
14213 }
14214
14215 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014216 String path, ParcelFileDescriptor fd) throws RemoteException {
14217
14218 try {
14219 synchronized (this) {
14220 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14221 // its own permission (same as profileControl).
14222 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14223 != PackageManager.PERMISSION_GRANTED) {
14224 throw new SecurityException("Requires permission "
14225 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14226 }
14227
14228 if (fd == null) {
14229 throw new IllegalArgumentException("null fd");
14230 }
14231
Dianne Hackborn1676c852012-09-10 14:52:30 -070014232 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014233 if (proc == null || proc.thread == null) {
14234 throw new IllegalArgumentException("Unknown process: " + process);
14235 }
14236
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014237 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14238 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014239 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14240 throw new SecurityException("Process not debuggable: " + proc);
14241 }
14242 }
14243
14244 proc.thread.dumpHeap(managed, path, fd);
14245 fd = null;
14246 return true;
14247 }
14248 } catch (RemoteException e) {
14249 throw new IllegalStateException("Process disappeared");
14250 } finally {
14251 if (fd != null) {
14252 try {
14253 fd.close();
14254 } catch (IOException e) {
14255 }
14256 }
14257 }
14258 }
14259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014260 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14261 public void monitor() {
14262 synchronized (this) { }
14263 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014264
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014265 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014266 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14267 ProcessRecord processRecord = mLruProcesses.get(i);
14268 try {
14269 if (processRecord.thread != null) {
14270 processRecord.thread.setCoreSettings(settings);
14271 }
14272 } catch (RemoteException re) {
14273 /* ignore */
14274 }
14275 }
14276 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014277
14278 // Multi-user methods
14279
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014280 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014281 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014282 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14283 != PackageManager.PERMISSION_GRANTED) {
14284 String msg = "Permission Denial: switchUser() from pid="
14285 + Binder.getCallingPid()
14286 + ", uid=" + Binder.getCallingUid()
14287 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14288 Slog.w(TAG, msg);
14289 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014290 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014291
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014292 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014293 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014294 synchronized (this) {
14295 final int oldUserId = mCurrentUserId;
14296 if (oldUserId == userId) {
14297 return true;
14298 }
14299
14300 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14301 if (userInfo == null) {
14302 Slog.w(TAG, "No user info for user #" + userId);
14303 return false;
14304 }
14305
14306 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14307 R.anim.screen_user_enter);
14308
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014309 boolean needStart = false;
14310
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014311 // If the user we are switching to is not currently started, then
14312 // we need to start it now.
14313 if (mStartedUsers.get(userId) == null) {
14314 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014315 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014316 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014317 }
14318
14319 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014320 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014321 final Integer userIdInt = Integer.valueOf(userId);
14322 mUserLru.remove(userIdInt);
14323 mUserLru.add(userIdInt);
14324
Craig Mautnerf1b67412012-09-19 13:18:29 -070014325 mWindowManager.setCurrentUser(userId);
14326
Adam Cohenf7522022012-10-03 20:03:18 -070014327 // Once the internal notion of the active user has switched, we lock the device
14328 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014329 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014330
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014331 final UserStartedState uss = mStartedUsers.get(userId);
14332
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014333 // Make sure user is in the started state. If it is currently
14334 // stopping, we need to knock that off.
14335 if (uss.mState == UserStartedState.STATE_STOPPING) {
14336 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14337 // so we can just fairly silently bring the user back from
14338 // the almost-dead.
14339 uss.mState = UserStartedState.STATE_RUNNING;
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 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14343 // This means ACTION_SHUTDOWN has been sent, so we will
14344 // need to treat this as a new boot of the user.
14345 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014346 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014347 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014348 }
14349
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014350 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14351 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14352 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14353 oldUserId, userId, uss));
14354 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14355 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014356 if (needStart) {
14357 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14358 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14359 | Intent.FLAG_RECEIVER_FOREGROUND);
14360 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14361 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014362 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014363 false, false, MY_PID, Process.SYSTEM_UID, userId);
14364 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014365
14366 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14367 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014368 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014369 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014370 broadcastIntentLocked(null, null, intent, null,
14371 new IIntentReceiver.Stub() {
14372 public void performReceive(Intent intent, int resultCode,
14373 String data, Bundle extras, boolean ordered,
14374 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014375 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014376 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014377 }, 0, null, null, null, AppOpsManager.OP_NONE,
14378 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014379 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014380 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014381 } else {
14382 getUserManagerLocked().makeInitialized(userInfo.id);
14383 }
14384 }
14385
14386 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14387 if (!haveActivities) {
14388 startHomeActivityLocked(userId);
14389 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014390
Jeff Sharkey86597df2012-11-09 15:00:31 -080014391 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014392 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014393 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014394 if (needStart) {
14395 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14396 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14397 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14398 broadcastIntentLocked(null, null, intent,
14399 null, new IIntentReceiver.Stub() {
14400 @Override
14401 public void performReceive(Intent intent, int resultCode, String data,
14402 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14403 throws RemoteException {
14404 }
14405 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014406 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014407 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014408 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014409 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014410 } finally {
14411 Binder.restoreCallingIdentity(ident);
14412 }
Amith Yamasani13593602012-03-22 16:16:17 -070014413
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014414 return true;
14415 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014416
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014417 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14418 long ident = Binder.clearCallingIdentity();
14419 try {
14420 Intent intent;
14421 if (oldUserId >= 0) {
14422 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014423 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14424 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014425 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14426 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014427 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014428 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14429 }
14430 if (newUserId >= 0) {
14431 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
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,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014436 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014437 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14438 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014439 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14440 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014441 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14442 broadcastIntentLocked(null, null, intent,
14443 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014444 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014445 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14446 }
14447 } finally {
14448 Binder.restoreCallingIdentity(ident);
14449 }
14450 }
14451
14452 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14453 final int newUserId) {
14454 final int N = mUserSwitchObservers.beginBroadcast();
14455 if (N > 0) {
14456 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14457 int mCount = 0;
14458 @Override
14459 public void sendResult(Bundle data) throws RemoteException {
14460 synchronized (ActivityManagerService.this) {
14461 if (mCurUserSwitchCallback == this) {
14462 mCount++;
14463 if (mCount == N) {
14464 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14465 }
14466 }
14467 }
14468 }
14469 };
14470 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014471 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014472 mCurUserSwitchCallback = callback;
14473 }
14474 for (int i=0; i<N; i++) {
14475 try {
14476 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14477 newUserId, callback);
14478 } catch (RemoteException e) {
14479 }
14480 }
14481 } else {
14482 synchronized (this) {
14483 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14484 }
14485 }
14486 mUserSwitchObservers.finishBroadcast();
14487 }
14488
14489 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14490 synchronized (this) {
14491 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14492 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14493 }
14494 }
14495
14496 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14497 mCurUserSwitchCallback = null;
14498 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14499 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14500 oldUserId, newUserId, uss));
14501 }
14502
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014503 void userInitialized(UserStartedState uss, int newUserId) {
14504 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014505 }
14506
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014507 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014508 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014509 }
14510
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014511 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14512 boolean clearInitializing, boolean clearSwitching) {
14513 boolean unfrozen = false;
14514 synchronized (this) {
14515 if (clearInitializing) {
14516 uss.initializing = false;
14517 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14518 }
14519 if (clearSwitching) {
14520 uss.switching = false;
14521 }
14522 if (!uss.switching && !uss.initializing) {
14523 mWindowManager.stopFreezingScreen();
14524 unfrozen = true;
14525 }
14526 }
14527 if (unfrozen) {
14528 final int N = mUserSwitchObservers.beginBroadcast();
14529 for (int i=0; i<N; i++) {
14530 try {
14531 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14532 } catch (RemoteException e) {
14533 }
14534 }
14535 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014536 }
14537 }
14538
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014539 void finishUserSwitch(UserStartedState uss) {
14540 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014541 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014542 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14543 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014544 final int userId = uss.mHandle.getIdentifier();
14545 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14546 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14547 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014548 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014549 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014550 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014551 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014552 int num = mUserLru.size();
14553 int i = 0;
14554 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14555 Integer oldUserId = mUserLru.get(i);
14556 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14557 if (oldUss == null) {
14558 // Shouldn't happen, but be sane if it does.
14559 mUserLru.remove(i);
14560 num--;
14561 continue;
14562 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014563 if (oldUss.mState == UserStartedState.STATE_STOPPING
14564 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014565 // This user is already stopping, doesn't count.
14566 num--;
14567 i++;
14568 continue;
14569 }
14570 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14571 // Owner and current can't be stopped, but count as running.
14572 i++;
14573 continue;
14574 }
14575 // This is a user to be stopped.
14576 stopUserLocked(oldUserId, null);
14577 num--;
14578 i++;
14579 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014580 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014581 }
14582
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014583 @Override
14584 public int stopUser(final int userId, final IStopUserCallback callback) {
14585 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14586 != PackageManager.PERMISSION_GRANTED) {
14587 String msg = "Permission Denial: switchUser() from pid="
14588 + Binder.getCallingPid()
14589 + ", uid=" + Binder.getCallingUid()
14590 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14591 Slog.w(TAG, msg);
14592 throw new SecurityException(msg);
14593 }
14594 if (userId <= 0) {
14595 throw new IllegalArgumentException("Can't stop primary user " + userId);
14596 }
Amith Yamasani13593602012-03-22 16:16:17 -070014597 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014598 return stopUserLocked(userId, callback);
14599 }
14600 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014601
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014602 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14603 if (mCurrentUserId == userId) {
14604 return ActivityManager.USER_OP_IS_CURRENT;
14605 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014606
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014607 final UserStartedState uss = mStartedUsers.get(userId);
14608 if (uss == null) {
14609 // User is not started, nothing to do... but we do need to
14610 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014611 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014612 mHandler.post(new Runnable() {
14613 @Override
14614 public void run() {
14615 try {
14616 callback.userStopped(userId);
14617 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014618 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014619 }
14620 });
14621 }
14622 return ActivityManager.USER_OP_SUCCESS;
14623 }
14624
14625 if (callback != null) {
14626 uss.mStopCallbacks.add(callback);
14627 }
14628
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014629 if (uss.mState != UserStartedState.STATE_STOPPING
14630 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014631 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014632 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014633
14634 long ident = Binder.clearCallingIdentity();
14635 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014636 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014637 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014638 // stop the user.
14639 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14640 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14641 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14642 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14643 // This is the result receiver for the final shutdown broadcast.
14644 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014645 @Override
14646 public void performReceive(Intent intent, int resultCode, String data,
14647 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14648 finishUserStop(uss);
14649 }
14650 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014651 // This is the result receiver for the initial stopping broadcast.
14652 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14653 @Override
14654 public void performReceive(Intent intent, int resultCode, String data,
14655 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14656 // On to the next.
14657 synchronized (ActivityManagerService.this) {
14658 if (uss.mState != UserStartedState.STATE_STOPPING) {
14659 // Whoops, we are being started back up. Abort, abort!
14660 return;
14661 }
14662 uss.mState = UserStartedState.STATE_SHUTDOWN;
14663 }
14664 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014665 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014666 true, false, MY_PID, Process.SYSTEM_UID, userId);
14667 }
14668 };
14669 // Kick things off.
14670 broadcastIntentLocked(null, null, stoppingIntent,
14671 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014672 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014673 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014674 } finally {
14675 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014676 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014677 }
Amith Yamasani13593602012-03-22 16:16:17 -070014678
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014679 return ActivityManager.USER_OP_SUCCESS;
14680 }
14681
14682 void finishUserStop(UserStartedState uss) {
14683 final int userId = uss.mHandle.getIdentifier();
14684 boolean stopped;
14685 ArrayList<IStopUserCallback> callbacks;
14686 synchronized (this) {
14687 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014688 if (mStartedUsers.get(userId) != uss) {
14689 stopped = false;
14690 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014691 stopped = false;
14692 } else {
14693 stopped = true;
14694 // User can no longer run.
14695 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014696 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014697 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014698
14699 // Clean up all state and processes associated with the user.
14700 // Kill all the processes for the user.
14701 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014702 }
14703 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014704
14705 for (int i=0; i<callbacks.size(); i++) {
14706 try {
14707 if (stopped) callbacks.get(i).userStopped(userId);
14708 else callbacks.get(i).userStopAborted(userId);
14709 } catch (RemoteException e) {
14710 }
14711 }
14712 }
14713
14714 @Override
14715 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014716 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14717 != PackageManager.PERMISSION_GRANTED) && (
14718 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14719 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014720 String msg = "Permission Denial: getCurrentUser() from pid="
14721 + Binder.getCallingPid()
14722 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014723 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014724 Slog.w(TAG, msg);
14725 throw new SecurityException(msg);
14726 }
14727 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014728 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014729 }
Amith Yamasani13593602012-03-22 16:16:17 -070014730 }
14731
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014732 int getCurrentUserIdLocked() {
14733 return mCurrentUserId;
14734 }
14735
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014736 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014737 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014738 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14739 != PackageManager.PERMISSION_GRANTED) {
14740 String msg = "Permission Denial: isUserRunning() from pid="
14741 + Binder.getCallingPid()
14742 + ", uid=" + Binder.getCallingUid()
14743 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14744 Slog.w(TAG, msg);
14745 throw new SecurityException(msg);
14746 }
14747 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014748 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014749 }
14750 }
14751
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014752 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014753 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014754 if (state == null) {
14755 return false;
14756 }
14757 if (orStopped) {
14758 return true;
14759 }
14760 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014761 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014762 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014763
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014764 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014765 public int[] getRunningUserIds() {
14766 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14767 != PackageManager.PERMISSION_GRANTED) {
14768 String msg = "Permission Denial: isUserRunning() from pid="
14769 + Binder.getCallingPid()
14770 + ", uid=" + Binder.getCallingUid()
14771 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14772 Slog.w(TAG, msg);
14773 throw new SecurityException(msg);
14774 }
14775 synchronized (this) {
14776 return mStartedUserArray;
14777 }
14778 }
14779
14780 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014781 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014782 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014783 UserStartedState uss = mStartedUsers.valueAt(i);
14784 // This list does not include stopping users.
14785 if (uss.mState != UserStartedState.STATE_STOPPING
14786 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14787 num++;
14788 }
14789 }
14790 mStartedUserArray = new int[num];
14791 num = 0;
14792 for (int i=0; i<mStartedUsers.size(); i++) {
14793 UserStartedState uss = mStartedUsers.valueAt(i);
14794 if (uss.mState != UserStartedState.STATE_STOPPING
14795 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14796 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14797 num++;
14798 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014799 }
14800 }
14801
14802 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014803 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14804 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14805 != PackageManager.PERMISSION_GRANTED) {
14806 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14807 + Binder.getCallingPid()
14808 + ", uid=" + Binder.getCallingUid()
14809 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14810 Slog.w(TAG, msg);
14811 throw new SecurityException(msg);
14812 }
14813
14814 mUserSwitchObservers.register(observer);
14815 }
14816
14817 @Override
14818 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14819 mUserSwitchObservers.unregister(observer);
14820 }
14821
Dianne Hackborn1676c852012-09-10 14:52:30 -070014822 private boolean userExists(int userId) {
14823 if (userId == 0) {
14824 return true;
14825 }
14826 UserManagerService ums = getUserManagerLocked();
14827 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14828 }
14829
14830 int[] getUsersLocked() {
14831 UserManagerService ums = getUserManagerLocked();
14832 return ums != null ? ums.getUserIds() : new int[] { 0 };
14833 }
14834
14835 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014836 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014837 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14838 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014839 }
14840 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014841 }
14842
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014843 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014844 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014845
14846 throw new SecurityException("Caller uid=" + uid
14847 + " is not privileged to communicate with user=" + userId);
14848 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014849
14850 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014851 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014852 }
14853
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014854 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014855 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014856 ApplicationInfo newInfo = new ApplicationInfo(info);
14857 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014858 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14859 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014860 return newInfo;
14861 }
14862
14863 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014864 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014865 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014866 return aInfo;
14867 }
14868
14869 ActivityInfo info = new ActivityInfo(aInfo);
14870 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14871 return info;
14872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014873}