blob: 4fbacb891666a4bd7c66323fdab47a018395ba68 [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;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800199 static final boolean VALIDATE_TOKENS = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 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() {
Jeff Sharkeyb9323192013-02-05 13:32:18 -08007418 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport");
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007419 SystemProperties.set("ctl.start", "bugreport");
7420 }
7421
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07007422 public long inputDispatchingTimedOut(int pid, boolean aboveSystem) {
7423 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS)
7424 != PackageManager.PERMISSION_GRANTED) {
7425 throw new SecurityException("Requires permission "
7426 + android.Manifest.permission.FILTER_EVENTS);
7427 }
7428
7429 ProcessRecord proc;
7430
7431 // TODO: Unify this code with ActivityRecord.keyDispatchingTimedOut().
7432 synchronized (this) {
7433 synchronized (mPidsSelfLocked) {
7434 proc = mPidsSelfLocked.get(pid);
7435 }
7436 if (proc != null) {
7437 if (proc.debugging) {
7438 return -1;
7439 }
7440
7441 if (mDidDexOpt) {
7442 // Give more time since we were dexopting.
7443 mDidDexOpt = false;
7444 return -1;
7445 }
7446
7447 if (proc.instrumentationClass != null) {
7448 Bundle info = new Bundle();
7449 info.putString("shortMsg", "keyDispatchingTimedOut");
7450 info.putString("longMsg", "Timed out while dispatching key event");
7451 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info);
7452 proc = null;
7453 }
7454 }
7455 }
7456
7457 if (proc != null) {
7458 appNotResponding(proc, null, null, aboveSystem, "keyDispatchingTimedOut");
7459 if (proc.instrumentationClass != null || proc.usingWrapper) {
7460 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
7461 }
7462 }
7463
7464 return KEY_DISPATCHING_TIMEOUT;
7465 }
7466
Dianne Hackbornf9c5e0f2013-01-23 14:39:13 -08007467 public Bundle getTopActivityExtras(int requestType) {
7468 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO,
7469 "getTopActivityExtras()");
7470 PendingActivityExtras pae;
7471 Bundle extras = new Bundle();
7472 synchronized (this) {
7473 ActivityRecord activity = mMainStack.mResumedActivity;
7474 if (activity == null) {
7475 Slog.w(TAG, "getTopActivityExtras failed: no resumed activity");
7476 return null;
7477 }
7478 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName);
7479 if (activity.app == null || activity.app.thread == null) {
7480 Slog.w(TAG, "getTopActivityExtras failed: no process for " + activity);
7481 return extras;
7482 }
7483 if (activity.app.pid == Binder.getCallingPid()) {
7484 Slog.w(TAG, "getTopActivityExtras failed: request process same as " + activity);
7485 return extras;
7486 }
7487 pae = new PendingActivityExtras(activity);
7488 try {
7489 activity.app.thread.requestActivityExtras(activity.appToken, pae, requestType);
7490 mPendingActivityExtras.add(pae);
7491 mHandler.postDelayed(pae, PENDING_ACTIVITY_RESULT_TIMEOUT);
7492 } catch (RemoteException e) {
7493 Slog.w(TAG, "getTopActivityExtras failed: crash calling " + activity);
7494 return extras;
7495 }
7496 }
7497 synchronized (pae) {
7498 while (!pae.haveResult) {
7499 try {
7500 pae.wait();
7501 } catch (InterruptedException e) {
7502 }
7503 }
7504 if (pae.result != null) {
7505 extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, pae.result);
7506 }
7507 }
7508 synchronized (this) {
7509 mPendingActivityExtras.remove(pae);
7510 mHandler.removeCallbacks(pae);
7511 }
7512 return extras;
7513 }
7514
7515 public void reportTopActivityExtras(IBinder token, Bundle extras) {
7516 PendingActivityExtras pae = (PendingActivityExtras)token;
7517 synchronized (pae) {
7518 pae.result = extras;
7519 pae.haveResult = true;
7520 pae.notifyAll();
7521 }
7522 }
7523
Jeff Sharkeya4620792011-05-20 15:29:23 -07007524 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007525 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7526 "registerProcessObserver()");
7527 synchronized (this) {
7528 mProcessObservers.register(observer);
7529 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007530 }
7531
7532 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007533 synchronized (this) {
7534 mProcessObservers.unregister(observer);
7535 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007536 }
7537
Daniel Sandler69a48172010-06-23 16:29:36 -04007538 public void setImmersive(IBinder token, boolean immersive) {
7539 synchronized(this) {
Christopher Tate73c2aee2012-03-15 16:27:14 -07007540 final ActivityRecord r = mMainStack.isInStackLocked(token);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007541 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007542 throw new IllegalArgumentException();
7543 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007544 r.immersive = immersive;
Christopher Tate73c2aee2012-03-15 16:27:14 -07007545
7546 // update associated state if we're frontmost
7547 if (r == mFocusedActivity) {
7548 if (DEBUG_IMMERSIVE) {
7549 Slog.d(TAG, "Frontmost changed immersion: "+ r);
7550 }
7551 applyUpdateLockStateLocked(r);
7552 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007553 }
7554 }
7555
7556 public boolean isImmersive(IBinder token) {
7557 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007558 ActivityRecord r = mMainStack.isInStackLocked(token);
7559 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007560 throw new IllegalArgumentException();
7561 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007562 return r.immersive;
7563 }
7564 }
7565
7566 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007567 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007568 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007569 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007570 return (r != null) ? r.immersive : false;
7571 }
7572 }
7573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 public final void enterSafeMode() {
7575 synchronized(this) {
7576 // It only makes sense to do this before the system is ready
7577 // and started launching other packages.
7578 if (!mSystemReady) {
7579 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007580 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 } catch (RemoteException e) {
7582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 }
7584 }
7585 }
7586
Jeff Brownb09abc12011-01-13 21:08:27 -08007587 public final void showSafeModeOverlay() {
7588 View v = LayoutInflater.from(mContext).inflate(
7589 com.android.internal.R.layout.safe_mode, null);
7590 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7591 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7592 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7593 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007594 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007595 lp.format = v.getBackground().getOpacity();
7596 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7597 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
Craig Mautner5962b122012-10-05 14:45:52 -07007598 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
Jeff Brownb09abc12011-01-13 21:08:27 -08007599 ((WindowManager)mContext.getSystemService(
7600 Context.WINDOW_SERVICE)).addView(v, lp);
7601 }
7602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 public void noteWakeupAlarm(IIntentSender sender) {
7604 if (!(sender instanceof PendingIntentRecord)) {
7605 return;
7606 }
7607 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7608 synchronized (stats) {
7609 if (mBatteryStatsService.isOnBattery()) {
7610 mBatteryStatsService.enforceCallingPermission();
7611 PendingIntentRecord rec = (PendingIntentRecord)sender;
7612 int MY_UID = Binder.getCallingUid();
7613 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7614 BatteryStatsImpl.Uid.Pkg pkg =
7615 stats.getPackageStatsLocked(uid, rec.key.packageName);
7616 pkg.incWakeupsLocked();
7617 }
7618 }
7619 }
7620
Dianne Hackborn64825172011-03-02 21:32:58 -08007621 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007623 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007625 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007626 // XXX Note: don't acquire main activity lock here, because the window
7627 // manager calls in with its locks held.
7628
7629 boolean killed = false;
7630 synchronized (mPidsSelfLocked) {
7631 int[] types = new int[pids.length];
7632 int worstType = 0;
7633 for (int i=0; i<pids.length; i++) {
7634 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7635 if (proc != null) {
7636 int type = proc.setAdj;
7637 types[i] = type;
7638 if (type > worstType) {
7639 worstType = type;
7640 }
7641 }
7642 }
7643
Dianne Hackborn64825172011-03-02 21:32:58 -08007644 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007646 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7647 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007648 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007650
7651 // If this is not a secure call, don't let it kill processes that
7652 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007653 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7654 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007655 }
7656
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007657 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 for (int i=0; i<pids.length; i++) {
7659 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7660 if (proc == null) {
7661 continue;
7662 }
7663 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007664 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007665 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007666 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId, proc.pid,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007667 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007669 proc.killedBackground = true;
7670 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007671 }
7672 }
7673 }
7674 return killed;
7675 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007676
7677 @Override
7678 public boolean killProcessesBelowForeground(String reason) {
7679 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7680 throw new SecurityException("killProcessesBelowForeground() only available to system");
7681 }
7682
7683 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7684 }
7685
7686 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7687 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7688 throw new SecurityException("killProcessesBelowAdj() only available to system");
7689 }
7690
7691 boolean killed = false;
7692 synchronized (mPidsSelfLocked) {
7693 final int size = mPidsSelfLocked.size();
7694 for (int i = 0; i < size; i++) {
7695 final int pid = mPidsSelfLocked.keyAt(i);
7696 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7697 if (proc == null) continue;
7698
7699 final int adj = proc.setAdj;
7700 if (adj > belowAdj && !proc.killedBackground) {
7701 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07007702 EventLog.writeEvent(EventLogTags.AM_KILL, proc.userId,
7703 proc.pid, proc.processName, adj, reason);
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007704 killed = true;
7705 proc.killedBackground = true;
7706 Process.killProcessQuiet(pid);
7707 }
7708 }
7709 }
7710 return killed;
7711 }
7712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 public final void startRunning(String pkg, String cls, String action,
7714 String data) {
7715 synchronized(this) {
7716 if (mStartRunning) {
7717 return;
7718 }
7719 mStartRunning = true;
7720 mTopComponent = pkg != null && cls != null
7721 ? new ComponentName(pkg, cls) : null;
7722 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7723 mTopData = data;
7724 if (!mSystemReady) {
7725 return;
7726 }
7727 }
7728
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007729 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 }
7731
7732 private void retrieveSettings() {
7733 final ContentResolver resolver = mContext.getContentResolver();
Jeff Sharkey8d9a1f62012-10-18 15:38:14 -07007734 String debugApp = Settings.Global.getString(
7735 resolver, Settings.Global.DEBUG_APP);
7736 boolean waitForDebugger = Settings.Global.getInt(
7737 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0;
7738 boolean alwaysFinishActivities = Settings.Global.getInt(
7739 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740
7741 Configuration configuration = new Configuration();
7742 Settings.System.getConfiguration(resolver, configuration);
7743
7744 synchronized (this) {
7745 mDebugApp = mOrigDebugApp = debugApp;
7746 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7747 mAlwaysFinishActivities = alwaysFinishActivities;
7748 // This happens before any activities are started, so we can
7749 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007750 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007751 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 }
7753 }
7754
7755 public boolean testIsSystemReady() {
7756 // no need to synchronize(this) just to read & return the value
7757 return mSystemReady;
7758 }
7759
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007760 private static File getCalledPreBootReceiversFile() {
7761 File dataDir = Environment.getDataDirectory();
7762 File systemDir = new File(dataDir, "system");
7763 File fname = new File(systemDir, "called_pre_boots.dat");
7764 return fname;
7765 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007766
7767 static final int LAST_DONE_VERSION = 10000;
7768
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007769 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7770 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7771 File file = getCalledPreBootReceiversFile();
7772 FileInputStream fis = null;
7773 try {
7774 fis = new FileInputStream(file);
7775 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007776 int fvers = dis.readInt();
7777 if (fvers == LAST_DONE_VERSION) {
7778 String vers = dis.readUTF();
7779 String codename = dis.readUTF();
7780 String build = dis.readUTF();
7781 if (android.os.Build.VERSION.RELEASE.equals(vers)
7782 && android.os.Build.VERSION.CODENAME.equals(codename)
7783 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7784 int num = dis.readInt();
7785 while (num > 0) {
7786 num--;
7787 String pkg = dis.readUTF();
7788 String cls = dis.readUTF();
7789 lastDoneReceivers.add(new ComponentName(pkg, cls));
7790 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007791 }
7792 }
7793 } catch (FileNotFoundException e) {
7794 } catch (IOException e) {
7795 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7796 } finally {
7797 if (fis != null) {
7798 try {
7799 fis.close();
7800 } catch (IOException e) {
7801 }
7802 }
7803 }
7804 return lastDoneReceivers;
7805 }
7806
7807 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7808 File file = getCalledPreBootReceiversFile();
7809 FileOutputStream fos = null;
7810 DataOutputStream dos = null;
7811 try {
7812 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7813 fos = new FileOutputStream(file);
7814 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007815 dos.writeInt(LAST_DONE_VERSION);
7816 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007817 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007818 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007819 dos.writeInt(list.size());
7820 for (int i=0; i<list.size(); i++) {
7821 dos.writeUTF(list.get(i).getPackageName());
7822 dos.writeUTF(list.get(i).getClassName());
7823 }
7824 } catch (IOException e) {
7825 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7826 file.delete();
7827 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007828 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007829 if (dos != null) {
7830 try {
7831 dos.close();
7832 } catch (IOException e) {
7833 // TODO Auto-generated catch block
7834 e.printStackTrace();
7835 }
7836 }
7837 }
7838 }
7839
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007840 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 synchronized(this) {
7842 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007843 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844 return;
7845 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007846
7847 // Check to see if there are any update receivers to run.
7848 if (!mDidUpdate) {
7849 if (mWaitingUpdate) {
7850 return;
7851 }
7852 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7853 List<ResolveInfo> ris = null;
7854 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007855 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007856 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007857 } catch (RemoteException e) {
7858 }
7859 if (ris != null) {
7860 for (int i=ris.size()-1; i>=0; i--) {
7861 if ((ris.get(i).activityInfo.applicationInfo.flags
7862 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7863 ris.remove(i);
7864 }
7865 }
7866 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007867
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007868 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07007869
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007870 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007871 for (int i=0; i<ris.size(); i++) {
7872 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007873 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7874 if (lastDoneReceivers.contains(comp)) {
7875 ris.remove(i);
7876 i--;
7877 }
7878 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007879
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007880 final int[] users = getUsersLocked();
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007881 for (int i=0; i<ris.size(); i++) {
7882 ActivityInfo ai = ris.get(i).activityInfo;
7883 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7884 doneReceivers.add(comp);
7885 intent.setComponent(comp);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007886 for (int j=0; j<users.length; j++) {
7887 IIntentReceiver finisher = null;
7888 if (i == ris.size()-1 && j == users.length-1) {
7889 finisher = new IIntentReceiver.Stub() {
7890 public void performReceive(Intent intent, int resultCode,
7891 String data, Bundle extras, boolean ordered,
7892 boolean sticky, int sendingUser) {
7893 // The raw IIntentReceiver interface is called
7894 // with the AM lock held, so redispatch to
7895 // execute our code without the lock.
7896 mHandler.post(new Runnable() {
7897 public void run() {
7898 synchronized (ActivityManagerService.this) {
7899 mDidUpdate = true;
7900 }
7901 writeLastDonePreBootReceivers(doneReceivers);
7902 showBootMessage(mContext.getText(
7903 R.string.android_upgrading_complete),
7904 false);
7905 systemReady(goingCallback);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007906 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007907 });
7908 }
7909 };
7910 }
7911 Slog.i(TAG, "Sending system update to " + intent.getComponent()
7912 + " for user " + users[j]);
7913 broadcastIntentLocked(null, null, intent, null, finisher,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08007914 0, null, null, null, AppOpsManager.OP_NONE,
7915 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07007916 users[j]);
7917 if (finisher != null) {
7918 mWaitingUpdate = true;
7919 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007920 }
7921 }
7922 }
7923 if (mWaitingUpdate) {
7924 return;
7925 }
7926 mDidUpdate = true;
7927 }
Dianne Hackborn514074f2013-02-11 10:52:46 -08007928
7929 mAppOpsService.systemReady();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 mSystemReady = true;
7931 if (!mStartRunning) {
7932 return;
7933 }
7934 }
7935
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007936 ArrayList<ProcessRecord> procsToKill = null;
7937 synchronized(mPidsSelfLocked) {
7938 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7939 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7940 if (!isAllowedWhileBooting(proc.info)){
7941 if (procsToKill == null) {
7942 procsToKill = new ArrayList<ProcessRecord>();
7943 }
7944 procsToKill.add(proc);
7945 }
7946 }
7947 }
7948
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007949 synchronized(this) {
7950 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007951 for (int i=procsToKill.size()-1; i>=0; i--) {
7952 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007953 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007954 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007955 }
7956 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007957
7958 // Now that we have cleaned up any update processes, we
7959 // are ready to start launching real processes and know that
7960 // we won't trample on them any more.
7961 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007962 }
7963
Joe Onorato8a9b2202010-02-26 18:56:32 -08007964 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007965 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 SystemClock.uptimeMillis());
7967
7968 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007969 // Make sure we have no pre-ready processes sitting around.
7970
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7972 ResolveInfo ri = mContext.getPackageManager()
7973 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007974 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 CharSequence errorMsg = null;
7976 if (ri != null) {
7977 ActivityInfo ai = ri.activityInfo;
7978 ApplicationInfo app = ai.applicationInfo;
7979 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7980 mTopAction = Intent.ACTION_FACTORY_TEST;
7981 mTopData = null;
7982 mTopComponent = new ComponentName(app.packageName,
7983 ai.name);
7984 } else {
7985 errorMsg = mContext.getResources().getText(
7986 com.android.internal.R.string.factorytest_not_system);
7987 }
7988 } else {
7989 errorMsg = mContext.getResources().getText(
7990 com.android.internal.R.string.factorytest_no_action);
7991 }
7992 if (errorMsg != null) {
7993 mTopAction = null;
7994 mTopData = null;
7995 mTopComponent = null;
7996 Message msg = Message.obtain();
7997 msg.what = SHOW_FACTORY_ERROR_MSG;
7998 msg.getData().putCharSequence("msg", errorMsg);
7999 mHandler.sendMessage(msg);
8000 }
8001 }
8002 }
8003
8004 retrieveSettings();
8005
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07008006 if (goingCallback != null) goingCallback.run();
8007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 synchronized (this) {
8009 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
8010 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008011 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07008012 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 if (apps != null) {
8014 int N = apps.size();
8015 int i;
8016 for (i=0; i<N; i++) {
8017 ApplicationInfo info
8018 = (ApplicationInfo)apps.get(i);
8019 if (info != null &&
8020 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008021 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 }
8023 }
8024 }
8025 } catch (RemoteException ex) {
8026 // pm is in same process, this will never happen.
8027 }
8028 }
8029
Dianne Hackborn9acc0302009-08-25 00:27:12 -07008030 // Start up initial activity.
8031 mBooting = true;
8032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008034 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008035 Message msg = Message.obtain();
8036 msg.what = SHOW_UID_ERROR_MSG;
8037 mHandler.sendMessage(msg);
8038 }
8039 } catch (RemoteException e) {
8040 }
8041
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008042 long ident = Binder.clearCallingIdentity();
8043 try {
8044 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008045 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
8046 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008047 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8048 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008049 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008050 false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07008051 intent = new Intent(Intent.ACTION_USER_STARTING);
8052 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
8053 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId);
8054 broadcastIntentLocked(null, null, intent,
8055 null, new IIntentReceiver.Stub() {
8056 @Override
8057 public void performReceive(Intent intent, int resultCode, String data,
8058 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
8059 throws RemoteException {
8060 }
8061 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -08008062 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -08008063 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008064 } finally {
8065 Binder.restoreCallingIdentity(ident);
8066 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008067 mMainStack.resumeTopActivityLocked(null);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07008068 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 }
8070 }
8071
Dan Egnorb7f03672009-12-09 16:22:32 -08008072 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008073 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008075 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008076 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 startAppProblemLocked(app);
8078 app.stopFreezingAllLocked();
8079 return handleAppCrashLocked(app);
8080 }
8081
Dan Egnorb7f03672009-12-09 16:22:32 -08008082 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008083 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08008085 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08008086 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
8087 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 startAppProblemLocked(app);
8089 app.stopFreezingAllLocked();
8090 }
8091
8092 /**
8093 * Generate a process error record, suitable for attachment to a ProcessRecord.
8094 *
8095 * @param app The ProcessRecord in which the error occurred.
8096 * @param condition Crashing, Application Not Responding, etc. Values are defined in
8097 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08008098 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 * @param shortMsg Short message describing the crash.
8100 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08008101 * @param stackTrace Full crash stack trace, may be null.
8102 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 * @return Returns a fully-formed AppErrorStateInfo record.
8104 */
8105 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08008106 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08008108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008109 report.condition = condition;
8110 report.processName = app.processName;
8111 report.pid = app.pid;
8112 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08008113 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008114 report.shortMsg = shortMsg;
8115 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08008116 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117
8118 return report;
8119 }
8120
Dan Egnor42471dd2010-01-07 17:25:22 -08008121 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 synchronized (this) {
8123 app.crashing = false;
8124 app.crashingReport = null;
8125 app.notResponding = false;
8126 app.notRespondingReport = null;
8127 if (app.anrDialog == fromDialog) {
8128 app.anrDialog = null;
8129 }
8130 if (app.waitDialog == fromDialog) {
8131 app.waitDialog = null;
8132 }
8133 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08008134 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008135 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008136 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn8633e682010-04-22 16:03:41 -07008137 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07008138 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 }
8141 }
Dan Egnor42471dd2010-01-07 17:25:22 -08008142
Dan Egnorb7f03672009-12-09 16:22:32 -08008143 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04008144 if (mHeadless) {
8145 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
8146 return false;
8147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 long now = SystemClock.uptimeMillis();
8149
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008150 Long crashTime;
8151 if (!app.isolated) {
8152 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
8153 } else {
8154 crashTime = null;
8155 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07008156 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008157 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08008158 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08008160 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008161 app.userId, app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008162 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
8163 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008165 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008167 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
8168 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008169 }
8170 }
8171 if (!app.persistent) {
8172 // We don't want to start this process again until the user
8173 // explicitly does so... but for persistent process, we really
8174 // need to keep it running. If a persistent process is actually
8175 // repeatedly crashing, then badness for everyone.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008176 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008177 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008178 if (!app.isolated) {
8179 // XXX We don't have a way to mark isolated processes
8180 // as bad, since they don't have a peristent identity.
8181 mBadProcesses.put(app.info.processName, app.uid, now);
8182 mProcessCrashTimes.remove(app.info.processName, app.uid);
8183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07008186 // Don't let services in this process be restarted and potentially
8187 // annoy the user repeatedly. Unless it is persistent, since those
8188 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08008189 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08008190 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 return false;
8192 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08008193 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008194 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008195 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08008196 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008197 // If the top running activity is from this crashing
8198 // process, then terminate it to avoid getting in a loop.
8199 Slog.w(TAG, " Force finishing activity "
8200 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08008201 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008202 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008203 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08008204 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008205 // stopped, to avoid a situation where one will get
8206 // re-start our crashing activity once it gets resumed again.
8207 index--;
8208 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008209 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008210 if (r.state == ActivityState.RESUMED
8211 || r.state == ActivityState.PAUSING
8212 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08008213 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008214 Slog.w(TAG, " Force finishing activity "
8215 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008216 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07008217 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07008218 }
8219 }
8220 }
8221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 }
8223
8224 // Bump up the crash count of any services currently running in the proc.
8225 if (app.services.size() != 0) {
8226 // Any services running in the application need to be placed
8227 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07008228 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008229 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07008230 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008231 sr.crashCount++;
8232 }
8233 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02008234
8235 // If the crashing process is what we consider to be the "home process" and it has been
8236 // replaced by a third-party app, clear the package preferred activities from packages
8237 // with a home activity running in the process to prevent a repeatedly crashing app
8238 // from blocking the user to manually clear the list.
8239 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
8240 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
8241 Iterator it = mHomeProcess.activities.iterator();
8242 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07008243 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02008244 if (r.isHomeActivity) {
8245 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
8246 try {
8247 ActivityThread.getPackageManager()
8248 .clearPackagePreferredActivities(r.packageName);
8249 } catch (RemoteException c) {
8250 // pm is in same process, this will never happen.
8251 }
8252 }
8253 }
8254 }
8255
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008256 if (!app.isolated) {
8257 // XXX Can't keep track of crash times for isolated processes,
8258 // because they don't have a perisistent identity.
8259 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8260 }
8261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 return true;
8263 }
8264
8265 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008266 if (app.userId == mCurrentUserId) {
8267 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8268 mContext, app.info.packageName, app.info.flags);
8269 } else {
8270 // If this app is not running under the current user, then we
8271 // can't give it a report button because that would require
8272 // launching the report UI under a different user.
8273 app.errorReportReceiver = null;
8274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 skipCurrentReceiverLocked(app);
8276 }
8277
8278 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008279 for (BroadcastQueue queue : mBroadcastQueues) {
8280 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008281 }
8282 }
8283
Dan Egnor60d87622009-12-16 16:32:58 -08008284 /**
8285 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8286 * The application process will exit immediately after this call returns.
8287 * @param app object of the crashing app, null for the system server
8288 * @param crashInfo describing the exception
8289 */
8290 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008291 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008292 final String processName = app == null ? "system_server"
8293 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008294
8295 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008296 UserHandle.getUserId(Binder.getCallingUid()), processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008297 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008298 crashInfo.exceptionClassName,
8299 crashInfo.exceptionMessage,
8300 crashInfo.throwFileName,
8301 crashInfo.throwLineNumber);
8302
Jeff Sharkeya353d262011-10-28 11:12:06 -07008303 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008304
8305 crashApplication(r, crashInfo);
8306 }
8307
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008308 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008309 IBinder app,
8310 int violationMask,
8311 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008312 ProcessRecord r = findAppProcess(app, "StrictMode");
8313 if (r == null) {
8314 return;
8315 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008316
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008317 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008318 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008319 boolean logIt = true;
8320 synchronized (mAlreadyLoggedViolatedStacks) {
8321 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8322 logIt = false;
8323 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008324 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008325 // the relative pain numbers, without logging all
8326 // the stack traces repeatedly. We'd want to do
8327 // likewise in the client code, which also does
8328 // dup suppression, before the Binder call.
8329 } else {
8330 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8331 mAlreadyLoggedViolatedStacks.clear();
8332 }
8333 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8334 }
8335 }
8336 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008337 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008338 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008339 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008340
8341 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8342 AppErrorResult result = new AppErrorResult();
8343 synchronized (this) {
8344 final long origId = Binder.clearCallingIdentity();
8345
8346 Message msg = Message.obtain();
8347 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8348 HashMap<String, Object> data = new HashMap<String, Object>();
8349 data.put("result", result);
8350 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008351 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008352 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008353 msg.obj = data;
8354 mHandler.sendMessage(msg);
8355
8356 Binder.restoreCallingIdentity(origId);
8357 }
8358 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008359 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008360 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008361 }
8362
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008363 // Depending on the policy in effect, there could be a bunch of
8364 // these in quick succession so we try to batch these together to
8365 // minimize disk writes, number of dropbox entries, and maximize
8366 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008367 private void logStrictModeViolationToDropBox(
8368 ProcessRecord process,
8369 StrictMode.ViolationInfo info) {
8370 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008371 return;
8372 }
8373 final boolean isSystemApp = process == null ||
8374 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8375 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008376 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008377 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8378 final DropBoxManager dbox = (DropBoxManager)
8379 mContext.getSystemService(Context.DROPBOX_SERVICE);
8380
8381 // Exit early if the dropbox isn't configured to accept this report type.
8382 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8383
8384 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008385 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008386 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8387 synchronized (sb) {
8388 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008389 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008390 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8391 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008392 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8393 if (info.violationNumThisLoop != 0) {
8394 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8395 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008396 if (info.numAnimationsRunning != 0) {
8397 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8398 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008399 if (info.broadcastIntentAction != null) {
8400 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8401 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008402 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008403 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008404 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008405 if (info.numInstances != -1) {
8406 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8407 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008408 if (info.tags != null) {
8409 for (String tag : info.tags) {
8410 sb.append("Span-Tag: ").append(tag).append("\n");
8411 }
8412 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008413 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008414 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8415 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008416 }
8417 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008418
8419 // Only buffer up to ~64k. Various logging bits truncate
8420 // things at 128k.
8421 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008422 }
8423
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008424 // Flush immediately if the buffer's grown too large, or this
8425 // is a non-system app. Non-system apps are isolated with a
8426 // different tag & policy and not batched.
8427 //
8428 // Batching is useful during internal testing with
8429 // StrictMode settings turned up high. Without batching,
8430 // thousands of separate files could be created on boot.
8431 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008432 new Thread("Error dump: " + dropboxTag) {
8433 @Override
8434 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008435 String report;
8436 synchronized (sb) {
8437 report = sb.toString();
8438 sb.delete(0, sb.length());
8439 sb.trimToSize();
8440 }
8441 if (report.length() != 0) {
8442 dbox.addText(dropboxTag, report);
8443 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008444 }
8445 }.start();
8446 return;
8447 }
8448
8449 // System app batching:
8450 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008451 // An existing dropbox-writing thread is outstanding, so
8452 // we don't need to start it up. The existing thread will
8453 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008454 return;
8455 }
8456
8457 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8458 // (After this point, we shouldn't access AMS internal data structures.)
8459 new Thread("Error dump: " + dropboxTag) {
8460 @Override
8461 public void run() {
8462 // 5 second sleep to let stacks arrive and be batched together
8463 try {
8464 Thread.sleep(5000); // 5 seconds
8465 } catch (InterruptedException e) {}
8466
8467 String errorReport;
8468 synchronized (mStrictModeBuffer) {
8469 errorReport = mStrictModeBuffer.toString();
8470 if (errorReport.length() == 0) {
8471 return;
8472 }
8473 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8474 mStrictModeBuffer.trimToSize();
8475 }
8476 dbox.addText(dropboxTag, errorReport);
8477 }
8478 }.start();
8479 }
8480
Dan Egnor60d87622009-12-16 16:32:58 -08008481 /**
8482 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8483 * @param app object of the crashing app, null for the system server
8484 * @param tag reported by the caller
8485 * @param crashInfo describing the context of the error
8486 * @return true if the process should exit immediately (WTF is fatal)
8487 */
8488 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008489 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008490 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008491 final String processName = app == null ? "system_server"
8492 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008493
Dianne Hackbornb12e1352012-09-26 11:39:20 -07008494 EventLog.writeEvent(EventLogTags.AM_WTF,
8495 UserHandle.getUserId(Binder.getCallingUid()), Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008496 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008497 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008498 tag, crashInfo.exceptionMessage);
8499
Jeff Sharkeya353d262011-10-28 11:12:06 -07008500 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008501
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008502 if (r != null && r.pid != Process.myPid() &&
Jeff Brownbf6f6f92012-09-25 15:03:20 -07008503 Settings.Global.getInt(mContext.getContentResolver(),
8504 Settings.Global.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008505 crashApplication(r, crashInfo);
8506 return true;
8507 } else {
8508 return false;
8509 }
8510 }
8511
8512 /**
8513 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8514 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8515 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008516 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008517 if (app == null) {
8518 return null;
8519 }
8520
8521 synchronized (this) {
8522 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8523 final int NA = apps.size();
8524 for (int ia=0; ia<NA; ia++) {
8525 ProcessRecord p = apps.valueAt(ia);
8526 if (p.thread != null && p.thread.asBinder() == app) {
8527 return p;
8528 }
8529 }
8530 }
8531
Dianne Hackborncb44d962011-03-10 17:02:27 -08008532 Slog.w(TAG, "Can't find mystery application for " + reason
8533 + " from pid=" + Binder.getCallingPid()
8534 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008535 return null;
8536 }
8537 }
8538
8539 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008540 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8541 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008542 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008543 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8544 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008545 // Watchdog thread ends up invoking this function (with
8546 // a null ProcessRecord) to add the stack file to dropbox.
8547 // Do not acquire a lock on this (am) in such cases, as it
8548 // could cause a potential deadlock, if and when watchdog
8549 // is invoked due to unavailability of lock on am and it
8550 // would prevent watchdog from killing system_server.
8551 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008552 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008553 return;
8554 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008555 // Note: ProcessRecord 'process' is guarded by the service
8556 // instance. (notably process.pkgList, which could otherwise change
8557 // concurrently during execution of this method)
8558 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008559 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008560 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008561 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008562 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8563 for (String pkg : process.pkgList) {
8564 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008565 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008566 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008567 if (pi != null) {
8568 sb.append(" v").append(pi.versionCode);
8569 if (pi.versionName != null) {
8570 sb.append(" (").append(pi.versionName).append(")");
8571 }
8572 }
8573 } catch (RemoteException e) {
8574 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008575 }
Dan Egnora455d192010-03-12 08:52:28 -08008576 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008577 }
Dan Egnora455d192010-03-12 08:52:28 -08008578 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008579 }
8580
8581 private static String processClass(ProcessRecord process) {
8582 if (process == null || process.pid == MY_PID) {
8583 return "system_server";
8584 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8585 return "system_app";
8586 } else {
8587 return "data_app";
8588 }
8589 }
8590
8591 /**
8592 * Write a description of an error (crash, WTF, ANR) to the drop box.
8593 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8594 * @param process which caused the error, null means the system server
8595 * @param activity which triggered the error, null if unknown
8596 * @param parent activity related to the error, null if unknown
8597 * @param subject line related to the error, null if absent
8598 * @param report in long form describing the error, null if absent
8599 * @param logFile to include in the report, null if none
8600 * @param crashInfo giving an application stack trace, null if absent
8601 */
8602 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008603 ProcessRecord process, String processName, ActivityRecord activity,
8604 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008605 final String report, final File logFile,
8606 final ApplicationErrorReport.CrashInfo crashInfo) {
8607 // NOTE -- this must never acquire the ActivityManagerService lock,
8608 // otherwise the watchdog may be prevented from resetting the system.
8609
8610 final String dropboxTag = processClass(process) + "_" + eventType;
8611 final DropBoxManager dbox = (DropBoxManager)
8612 mContext.getSystemService(Context.DROPBOX_SERVICE);
8613
8614 // Exit early if the dropbox isn't configured to accept this report type.
8615 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8616
8617 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008618 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008619 if (activity != null) {
8620 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8621 }
8622 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8623 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8624 }
8625 if (parent != null && parent != activity) {
8626 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8627 }
8628 if (subject != null) {
8629 sb.append("Subject: ").append(subject).append("\n");
8630 }
8631 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008632 if (Debug.isDebuggerConnected()) {
8633 sb.append("Debugger: Connected\n");
8634 }
Dan Egnora455d192010-03-12 08:52:28 -08008635 sb.append("\n");
8636
8637 // Do the rest in a worker thread to avoid blocking the caller on I/O
8638 // (After this point, we shouldn't access AMS internal data structures.)
8639 Thread worker = new Thread("Error dump: " + dropboxTag) {
8640 @Override
8641 public void run() {
8642 if (report != null) {
8643 sb.append(report);
8644 }
8645 if (logFile != null) {
8646 try {
8647 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8648 } catch (IOException e) {
8649 Slog.e(TAG, "Error reading " + logFile, e);
8650 }
8651 }
8652 if (crashInfo != null && crashInfo.stackTrace != null) {
8653 sb.append(crashInfo.stackTrace);
8654 }
8655
Jeff Sharkey625239a2012-09-26 22:03:49 -07008656 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag;
8657 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008658 if (lines > 0) {
8659 sb.append("\n");
8660
8661 // Merge several logcat streams, and take the last N lines
8662 InputStreamReader input = null;
8663 try {
8664 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8665 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8666 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8667
8668 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8669 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8670 input = new InputStreamReader(logcat.getInputStream());
8671
8672 int num;
8673 char[] buf = new char[8192];
8674 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8675 } catch (IOException e) {
8676 Slog.e(TAG, "Error running logcat", e);
8677 } finally {
8678 if (input != null) try { input.close(); } catch (IOException e) {}
8679 }
8680 }
8681
8682 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008683 }
Dan Egnora455d192010-03-12 08:52:28 -08008684 };
8685
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008686 if (process == null) {
8687 // If process is null, we are being called from some internal code
8688 // and may be about to die -- run this synchronously.
8689 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008690 } else {
8691 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008692 }
8693 }
8694
8695 /**
8696 * Bring up the "unexpected error" dialog box for a crashing app.
8697 * Deal with edge cases (intercepts from instrumented applications,
8698 * ActivityController, error intent receivers, that sort of thing).
8699 * @param r the application crashing
8700 * @param crashInfo describing the failure
8701 */
8702 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008703 long timeMillis = System.currentTimeMillis();
8704 String shortMsg = crashInfo.exceptionClassName;
8705 String longMsg = crashInfo.exceptionMessage;
8706 String stackTrace = crashInfo.stackTrace;
8707 if (shortMsg != null && longMsg != null) {
8708 longMsg = shortMsg + ": " + longMsg;
8709 } else if (shortMsg != null) {
8710 longMsg = shortMsg;
8711 }
8712
Dan Egnor60d87622009-12-16 16:32:58 -08008713 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008715 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 try {
8717 String name = r != null ? r.processName : null;
8718 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008719 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008720 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008721 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 + " at watcher's request");
8723 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008724 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008725 }
8726 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008727 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 }
8729 }
8730
8731 final long origId = Binder.clearCallingIdentity();
8732
8733 // If this process is running instrumentation, finish it.
8734 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008735 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008737 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8738 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 Bundle info = new Bundle();
8740 info.putString("shortMsg", shortMsg);
8741 info.putString("longMsg", longMsg);
8742 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8743 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008744 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008745 }
8746
Dan Egnor60d87622009-12-16 16:32:58 -08008747 // If we can't identify the process or it's already exceeded its crash quota,
8748 // quit right away without showing a crash dialog.
8749 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008750 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008751 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 }
8753
8754 Message msg = Message.obtain();
8755 msg.what = SHOW_ERROR_MSG;
8756 HashMap data = new HashMap();
8757 data.put("result", result);
8758 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 msg.obj = data;
8760 mHandler.sendMessage(msg);
8761
8762 Binder.restoreCallingIdentity(origId);
8763 }
8764
8765 int res = result.get();
8766
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008767 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008769 if (r != null && !r.isolated) {
8770 // XXX Can't keep track of crash time for isolated processes,
8771 // since they don't have a persistent identity.
8772 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 SystemClock.uptimeMillis());
8774 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008775 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008776 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008777 }
8778 }
8779
8780 if (appErrorIntent != null) {
8781 try {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -07008782 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008783 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008784 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008788
8789 Intent createAppErrorIntentLocked(ProcessRecord r,
8790 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8791 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008792 if (report == null) {
8793 return null;
8794 }
8795 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8796 result.setComponent(r.errorReportReceiver);
8797 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8798 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8799 return result;
8800 }
8801
Dan Egnorb7f03672009-12-09 16:22:32 -08008802 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8803 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008804 if (r.errorReportReceiver == null) {
8805 return null;
8806 }
8807
8808 if (!r.crashing && !r.notResponding) {
8809 return null;
8810 }
8811
Dan Egnorb7f03672009-12-09 16:22:32 -08008812 ApplicationErrorReport report = new ApplicationErrorReport();
8813 report.packageName = r.info.packageName;
8814 report.installerPackageName = r.errorReportReceiver.getPackageName();
8815 report.processName = r.processName;
8816 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008817 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008818
Dan Egnorb7f03672009-12-09 16:22:32 -08008819 if (r.crashing) {
8820 report.type = ApplicationErrorReport.TYPE_CRASH;
8821 report.crashInfo = crashInfo;
8822 } else if (r.notResponding) {
8823 report.type = ApplicationErrorReport.TYPE_ANR;
8824 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008825
Dan Egnorb7f03672009-12-09 16:22:32 -08008826 report.anrInfo.activity = r.notRespondingReport.tag;
8827 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8828 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008829 }
8830
Dan Egnorb7f03672009-12-09 16:22:32 -08008831 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008832 }
8833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008835 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 // assume our apps are happy - lazy create the list
8837 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8838
Dianne Hackborn0c380492012-08-20 17:23:30 -07008839 final boolean allUsers = ActivityManager.checkUidPermission(
8840 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8841 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8842 int userId = UserHandle.getUserId(Binder.getCallingUid());
8843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 synchronized (this) {
8845
8846 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008847 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8848 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008849 if (!allUsers && app.userId != userId) {
8850 continue;
8851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8853 // This one's in trouble, so we'll generate a report for it
8854 // crashes are higher priority (in case there's a crash *and* an anr)
8855 ActivityManager.ProcessErrorStateInfo report = null;
8856 if (app.crashing) {
8857 report = app.crashingReport;
8858 } else if (app.notResponding) {
8859 report = app.notRespondingReport;
8860 }
8861
8862 if (report != null) {
8863 if (errList == null) {
8864 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8865 }
8866 errList.add(report);
8867 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008868 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 " crashing = " + app.crashing +
8870 " notResponding = " + app.notResponding);
8871 }
8872 }
8873 }
8874 }
8875
8876 return errList;
8877 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008878
8879 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008880 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008881 if (currApp != null) {
8882 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8883 }
8884 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008885 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8886 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008887 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8888 if (currApp != null) {
8889 currApp.lru = 0;
8890 }
8891 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008892 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008893 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8894 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8895 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8896 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8897 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8898 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8899 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8900 } else {
8901 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8902 }
8903 }
8904
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008905 private void fillInProcMemInfo(ProcessRecord app,
8906 ActivityManager.RunningAppProcessInfo outInfo) {
8907 outInfo.pid = app.pid;
8908 outInfo.uid = app.info.uid;
8909 if (mHeavyWeightProcess == app) {
8910 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8911 }
8912 if (app.persistent) {
8913 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8914 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008915 if (app.hasActivities) {
8916 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8917 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008918 outInfo.lastTrimLevel = app.trimMemoryLevel;
8919 int adj = app.curAdj;
8920 outInfo.importance = oomAdjToImportance(adj, outInfo);
8921 outInfo.importanceReasonCode = app.adjTypeCode;
8922 }
8923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008925 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 // Lazy instantiation of list
8927 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008928 final boolean allUsers = ActivityManager.checkUidPermission(
8929 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8930 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8931 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 synchronized (this) {
8933 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008934 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8935 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008936 if (!allUsers && app.userId != userId) {
8937 continue;
8938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8940 // Generate process state info for running application
8941 ActivityManager.RunningAppProcessInfo currApp =
8942 new ActivityManager.RunningAppProcessInfo(app.processName,
8943 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008944 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008945 if (app.adjSource instanceof ProcessRecord) {
8946 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008947 currApp.importanceReasonImportance = oomAdjToImportance(
8948 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008949 } else if (app.adjSource instanceof ActivityRecord) {
8950 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008951 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8952 }
8953 if (app.adjTarget instanceof ComponentName) {
8954 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8955 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008956 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 // + " lru=" + currApp.lru);
8958 if (runList == null) {
8959 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8960 }
8961 runList.add(currApp);
8962 }
8963 }
8964 }
8965 return runList;
8966 }
8967
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008968 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008969 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008970 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8971 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8972 if (runningApps != null && runningApps.size() > 0) {
8973 Set<String> extList = new HashSet<String>();
8974 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8975 if (app.pkgList != null) {
8976 for (String pkg : app.pkgList) {
8977 extList.add(pkg);
8978 }
8979 }
8980 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008981 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008982 for (String pkg : extList) {
8983 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008984 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008985 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8986 retList.add(info);
8987 }
8988 } catch (RemoteException e) {
8989 }
8990 }
8991 }
8992 return retList;
8993 }
8994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008996 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8997 enforceNotIsolatedCaller("getMyMemoryState");
8998 synchronized (this) {
8999 ProcessRecord proc;
9000 synchronized (mPidsSelfLocked) {
9001 proc = mPidsSelfLocked.get(Binder.getCallingPid());
9002 }
9003 fillInProcMemInfo(proc, outInfo);
9004 }
9005 }
9006
9007 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009009 if (checkCallingPermission(android.Manifest.permission.DUMP)
9010 != PackageManager.PERMISSION_GRANTED) {
9011 pw.println("Permission Denial: can't dump ActivityManager from from pid="
9012 + Binder.getCallingPid()
9013 + ", uid=" + Binder.getCallingUid()
9014 + " without permission "
9015 + android.Manifest.permission.DUMP);
9016 return;
9017 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009018
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009019 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009020 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009021 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009022
9023 int opti = 0;
9024 while (opti < args.length) {
9025 String opt = args[opti];
9026 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
9027 break;
9028 }
9029 opti++;
9030 if ("-a".equals(opt)) {
9031 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 } else if ("-c".equals(opt)) {
9033 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009034 } else if ("-h".equals(opt)) {
9035 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009037 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009038 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009039 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009040 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
9041 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009042 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009043 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08009044 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009045 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009046 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009048 pw.println(" all: dump all activities");
9049 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009050 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009051 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
9052 pw.println(" a partial substring in a component name, a");
9053 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 pw.println(" -a: include all available server state.");
9055 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 } else {
9058 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009061
9062 long origId = Binder.clearCallingIdentity();
9063 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 // Is the caller requesting to dump a particular piece of data?
9065 if (opti < args.length) {
9066 String cmd = args[opti];
9067 opti++;
9068 if ("activities".equals(cmd) || "a".equals(cmd)) {
9069 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009071 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009073 String[] newArgs;
9074 String name;
9075 if (opti >= args.length) {
9076 name = null;
9077 newArgs = EMPTY_STRING_ARRAY;
9078 } else {
9079 name = args[opti];
9080 opti++;
9081 newArgs = new String[args.length - opti];
9082 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9083 args.length - opti);
9084 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009086 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009087 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009089 String[] newArgs;
9090 String name;
9091 if (opti >= args.length) {
9092 name = null;
9093 newArgs = EMPTY_STRING_ARRAY;
9094 } else {
9095 name = args[opti];
9096 opti++;
9097 newArgs = new String[args.length - opti];
9098 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9099 args.length - opti);
9100 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009103 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009104 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 String[] newArgs;
9106 String name;
9107 if (opti >= args.length) {
9108 name = null;
9109 newArgs = EMPTY_STRING_ARRAY;
9110 } else {
9111 name = args[opti];
9112 opti++;
9113 newArgs = new String[args.length - opti];
9114 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9115 args.length - opti);
9116 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009117 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009118 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009119 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009120 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
9121 synchronized (this) {
9122 dumpOomLocked(fd, pw, args, opti, true);
9123 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08009124 } else if ("provider".equals(cmd)) {
9125 String[] newArgs;
9126 String name;
9127 if (opti >= args.length) {
9128 name = null;
9129 newArgs = EMPTY_STRING_ARRAY;
9130 } else {
9131 name = args[opti];
9132 opti++;
9133 newArgs = new String[args.length - opti];
9134 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9135 }
9136 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
9137 pw.println("No providers match: " + name);
9138 pw.println("Use -h for help.");
9139 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
9141 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009142 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009143 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009144 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 String[] newArgs;
9146 String name;
9147 if (opti >= args.length) {
9148 name = null;
9149 newArgs = EMPTY_STRING_ARRAY;
9150 } else {
9151 name = args[opti];
9152 opti++;
9153 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009154 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9155 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009156 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009157 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009158 pw.println("No services match: " + name);
9159 pw.println("Use -h for help.");
9160 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009161 } else if ("package".equals(cmd)) {
9162 String[] newArgs;
9163 if (opti >= args.length) {
9164 pw.println("package: no package name specified");
9165 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009166 } else {
9167 dumpPackage = args[opti];
9168 opti++;
9169 newArgs = new String[args.length - opti];
9170 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
9171 args.length - opti);
9172 args = newArgs;
9173 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07009174 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009175 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 } else if ("services".equals(cmd) || "s".equals(cmd)) {
9177 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009178 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009179 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009180 } else {
9181 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009182 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
9183 pw.println("Bad activity command, or no activities match: " + cmd);
9184 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009185 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009186 }
9187 if (!more) {
9188 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08009189 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009191 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009192
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009193 // No piece of data specified, dump everything.
9194 synchronized (this) {
9195 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009196 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009197 if (needSep) {
9198 pw.println(" ");
9199 }
9200 if (dumpAll) {
9201 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009203 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009204 if (needSep) {
9205 pw.println(" ");
9206 }
9207 if (dumpAll) {
9208 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009210 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009211 if (needSep) {
9212 pw.println(" ");
9213 }
9214 if (dumpAll) {
9215 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07009217 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009218 if (needSep) {
9219 pw.println(" ");
9220 }
9221 if (dumpAll) {
9222 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009223 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009224 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009225 if (needSep) {
9226 pw.println(" ");
9227 }
9228 if (dumpAll) {
9229 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009230 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009231 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009232 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009233 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009234 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07009235
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009236 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009238 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
9239 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009240 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
9241 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009242 pw.println(" ");
9243 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009244 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
9245 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009246 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009249 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009251 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009252 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009254 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009255 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009256 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009257 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009258 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9259 pw.println(" ");
9260 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009261 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009262 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009263 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009264 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009265 pw.println(" ");
9266 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009267 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009268 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009269 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009271 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009272 if (mMainStack.mPausingActivity != null) {
9273 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009275 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009276 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009277 if (dumpAll) {
9278 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9279 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009280 pw.println(" mDismissKeyguardOnNextActivity: "
9281 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009284 if (mRecentTasks.size() > 0) {
9285 pw.println();
9286 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009287
9288 final int N = mRecentTasks.size();
9289 for (int i=0; i<N; i++) {
9290 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009291 if (dumpPackage != null) {
9292 if (tr.realActivity == null ||
9293 !dumpPackage.equals(tr.realActivity)) {
9294 continue;
9295 }
9296 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009297 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9298 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009299 if (dumpAll) {
9300 mRecentTasks.get(i).dump(pw, " ");
9301 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009302 }
9303 }
9304
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305 if (dumpAll) {
9306 pw.println(" ");
9307 pw.println(" mCurTask: " + mCurTask);
9308 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009309
9310 return true;
9311 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009312
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009313 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009314 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009315 boolean needSep = false;
9316 int numPers = 0;
9317
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009318 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9319
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009320 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9322 final int NA = procs.size();
9323 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009324 ProcessRecord r = procs.valueAt(ia);
9325 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9326 continue;
9327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 if (!needSep) {
9329 pw.println(" All known processes:");
9330 needSep = true;
9331 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009332 pw.print(r.persistent ? " *PERS*" : " *APP*");
9333 pw.print(" UID "); pw.print(procs.keyAt(ia));
9334 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 r.dump(pw, " ");
9336 if (r.persistent) {
9337 numPers++;
9338 }
9339 }
9340 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009341 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009342
9343 if (mIsolatedProcesses.size() > 0) {
9344 if (needSep) pw.println(" ");
9345 needSep = true;
9346 pw.println(" Isolated process list (sorted by uid):");
9347 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9348 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9349 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9350 continue;
9351 }
9352 pw.println(String.format("%sIsolated #%2d: %s",
9353 " ", i, r.toString()));
9354 }
9355 }
9356
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009357 if (mLruProcesses.size() > 0) {
9358 if (needSep) pw.println(" ");
9359 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009360 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009361 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009362 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 needSep = true;
9364 }
9365
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009366 if (dumpAll) {
9367 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009368 boolean printed = false;
9369 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9370 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9371 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9372 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009373 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009374 if (!printed) {
9375 if (needSep) pw.println(" ");
9376 needSep = true;
9377 pw.println(" PID mappings:");
9378 printed = true;
9379 }
9380 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9381 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 }
9383 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009384 }
9385
9386 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009387 synchronized (mPidsSelfLocked) {
9388 boolean printed = false;
9389 for (int i=0; i<mForegroundProcesses.size(); i++) {
9390 ProcessRecord r = mPidsSelfLocked.get(
9391 mForegroundProcesses.valueAt(i).pid);
9392 if (dumpPackage != null && (r == null
9393 || !dumpPackage.equals(r.info.packageName))) {
9394 continue;
9395 }
9396 if (!printed) {
9397 if (needSep) pw.println(" ");
9398 needSep = true;
9399 pw.println(" Foreground Processes:");
9400 printed = true;
9401 }
9402 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9403 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009405 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009406 }
9407
9408 if (mPersistentStartingProcesses.size() > 0) {
9409 if (needSep) pw.println(" ");
9410 needSep = true;
9411 pw.println(" Persisent processes that are starting:");
9412 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009413 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 if (mRemovedProcesses.size() > 0) {
9417 if (needSep) pw.println(" ");
9418 needSep = true;
9419 pw.println(" Processes that are being removed:");
9420 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009421 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009422 }
9423
9424 if (mProcessesOnHold.size() > 0) {
9425 if (needSep) pw.println(" ");
9426 needSep = true;
9427 pw.println(" Processes that are on old until the system is ready:");
9428 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009429 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009432 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009433
9434 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009435 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009436 long now = SystemClock.uptimeMillis();
9437 for (Map.Entry<String, SparseArray<Long>> procs
9438 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009439 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009440 SparseArray<Long> uids = procs.getValue();
9441 final int N = uids.size();
9442 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009443 int puid = uids.keyAt(i);
9444 ProcessRecord r = mProcessNames.get(pname, puid);
9445 if (dumpPackage != null && (r == null
9446 || !dumpPackage.equals(r.info.packageName))) {
9447 continue;
9448 }
9449 if (!printed) {
9450 if (needSep) pw.println(" ");
9451 needSep = true;
9452 pw.println(" Time since processes crashed:");
9453 printed = true;
9454 }
9455 pw.print(" Process "); pw.print(pname);
9456 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009457 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009458 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9459 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009460 }
9461 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009464 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009465 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009466 for (Map.Entry<String, SparseArray<Long>> procs
9467 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009468 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009469 SparseArray<Long> uids = procs.getValue();
9470 final int N = uids.size();
9471 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009472 int puid = uids.keyAt(i);
9473 ProcessRecord r = mProcessNames.get(pname, puid);
9474 if (dumpPackage != null && (r == null
9475 || !dumpPackage.equals(r.info.packageName))) {
9476 continue;
9477 }
9478 if (!printed) {
9479 if (needSep) pw.println(" ");
9480 needSep = true;
9481 pw.println(" Bad processes:");
9482 }
9483 pw.print(" Bad process "); pw.print(pname);
9484 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009485 pw.print(": crashed at time ");
9486 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 }
9488 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009489 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009491 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009492 pw.println(" mStartedUsers:");
9493 for (int i=0; i<mStartedUsers.size(); i++) {
9494 UserStartedState uss = mStartedUsers.valueAt(i);
9495 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009496 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009497 }
Dianne Hackborna8a9bd62012-10-09 15:36:59 -07009498 pw.print(" mStartedUserArray: [");
9499 for (int i=0; i<mStartedUserArray.length; i++) {
9500 if (i > 0) pw.print(", ");
9501 pw.print(mStartedUserArray[i]);
9502 }
9503 pw.println("]");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009504 pw.print(" mUserLru: [");
9505 for (int i=0; i<mUserLru.size(); i++) {
9506 if (i > 0) pw.print(", ");
9507 pw.print(mUserLru.get(i));
9508 }
9509 pw.println("]");
Dianne Hackbornc72fc672012-09-20 13:12:03 -07009510 if (dumpAll) {
9511 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
9512 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009513 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009514 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009515 if (dumpAll) {
9516 StringBuilder sb = new StringBuilder(128);
9517 sb.append(" mPreviousProcessVisibleTime: ");
9518 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9519 pw.println(sb);
9520 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009521 if (mHeavyWeightProcess != null) {
9522 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9523 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009524 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 if (dumpAll) {
9526 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009527 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009528 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009529 for (Map.Entry<String, Integer> entry
9530 : mCompatModePackages.getPackages().entrySet()) {
9531 String pkg = entry.getKey();
9532 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009533 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9534 continue;
9535 }
9536 if (!printed) {
9537 pw.println(" mScreenCompatPackages:");
9538 printed = true;
9539 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009540 pw.print(" "); pw.print(pkg); pw.print(": ");
9541 pw.print(mode); pw.println();
9542 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009543 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009544 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009545 if (mSleeping || mWentToSleep || mLockScreenShown) {
9546 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9547 + " mLockScreenShown " + mLockScreenShown);
9548 }
9549 if (mShuttingDown) {
9550 pw.println(" mShuttingDown=" + mShuttingDown);
9551 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009552 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9553 || mOrigWaitForDebugger) {
9554 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9555 + " mDebugTransient=" + mDebugTransient
9556 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9557 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009558 if (mOpenGlTraceApp != null) {
9559 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9560 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009561 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9562 || mProfileFd != null) {
9563 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9564 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9565 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9566 + mAutoStopProfiler);
9567 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 if (mAlwaysFinishActivities || mController != null) {
9569 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9570 + " mController=" + mController);
9571 }
9572 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009575 + " mProcessesReady=" + mProcessesReady
9576 + " mSystemReady=" + mSystemReady);
9577 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578 + " mBooted=" + mBooted
9579 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009580 pw.print(" mLastPowerCheckRealtime=");
9581 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9582 pw.println("");
9583 pw.print(" mLastPowerCheckUptime=");
9584 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9585 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009586 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9587 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009588 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009589 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9590 + " mNumHiddenProcs=" + mNumHiddenProcs
9591 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009592 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009594
9595 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009596 }
9597
Dianne Hackborn287952c2010-09-22 22:34:31 -07009598 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009599 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009600 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009601 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009602 long now = SystemClock.uptimeMillis();
9603 for (int i=0; i<mProcessesToGc.size(); i++) {
9604 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009605 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9606 continue;
9607 }
9608 if (!printed) {
9609 if (needSep) pw.println(" ");
9610 needSep = true;
9611 pw.println(" Processes that are waiting to GC:");
9612 printed = true;
9613 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009614 pw.print(" Process "); pw.println(proc);
9615 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9616 pw.print(", last gced=");
9617 pw.print(now-proc.lastRequestedGc);
9618 pw.print(" ms ago, last lowMem=");
9619 pw.print(now-proc.lastLowMemory);
9620 pw.println(" ms ago");
9621
9622 }
9623 }
9624 return needSep;
9625 }
9626
9627 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9628 int opti, boolean dumpAll) {
9629 boolean needSep = false;
9630
9631 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009632 if (needSep) pw.println(" ");
9633 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009634 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009635 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009636 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009637 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9638 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9639 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9640 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9641 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009642 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009643 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009644 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009645 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009646 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009647 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009648
9649 if (needSep) pw.println(" ");
9650 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009651 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009652 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009653 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009654 needSep = true;
9655 }
9656
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009657 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009658
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009659 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009660 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009661 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009662 if (mHeavyWeightProcess != null) {
9663 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9664 }
9665
9666 return true;
9667 }
9668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009669 /**
9670 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009671 * - no provider specified: dump all the providers
9672 * - a flattened component name that matched an existing provider was specified as the
9673 * first arg: dump that one provider
9674 * - the first arg isn't the flattened component name of an existing provider:
9675 * dump all providers whose component contains the first arg as a substring
9676 */
9677 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9678 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009679 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009680 }
9681
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009682 static class ItemMatcher {
9683 ArrayList<ComponentName> components;
9684 ArrayList<String> strings;
9685 ArrayList<Integer> objects;
9686 boolean all;
9687
9688 ItemMatcher() {
9689 all = true;
9690 }
9691
9692 void build(String name) {
9693 ComponentName componentName = ComponentName.unflattenFromString(name);
9694 if (componentName != null) {
9695 if (components == null) {
9696 components = new ArrayList<ComponentName>();
9697 }
9698 components.add(componentName);
9699 all = false;
9700 } else {
9701 int objectId = 0;
9702 // Not a '/' separated full component name; maybe an object ID?
9703 try {
9704 objectId = Integer.parseInt(name, 16);
9705 if (objects == null) {
9706 objects = new ArrayList<Integer>();
9707 }
9708 objects.add(objectId);
9709 all = false;
9710 } catch (RuntimeException e) {
9711 // Not an integer; just do string match.
9712 if (strings == null) {
9713 strings = new ArrayList<String>();
9714 }
9715 strings.add(name);
9716 all = false;
9717 }
9718 }
9719 }
9720
9721 int build(String[] args, int opti) {
9722 for (; opti<args.length; opti++) {
9723 String name = args[opti];
9724 if ("--".equals(name)) {
9725 return opti+1;
9726 }
9727 build(name);
9728 }
9729 return opti;
9730 }
9731
9732 boolean match(Object object, ComponentName comp) {
9733 if (all) {
9734 return true;
9735 }
9736 if (components != null) {
9737 for (int i=0; i<components.size(); i++) {
9738 if (components.get(i).equals(comp)) {
9739 return true;
9740 }
9741 }
9742 }
9743 if (objects != null) {
9744 for (int i=0; i<objects.size(); i++) {
9745 if (System.identityHashCode(object) == objects.get(i)) {
9746 return true;
9747 }
9748 }
9749 }
9750 if (strings != null) {
9751 String flat = comp.flattenToString();
9752 for (int i=0; i<strings.size(); i++) {
9753 if (flat.contains(strings.get(i))) {
9754 return true;
9755 }
9756 }
9757 }
9758 return false;
9759 }
9760 }
9761
Dianne Hackborn625ac272010-09-17 18:29:22 -07009762 /**
9763 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009764 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009765 * - the cmd arg isn't the flattened component name of an existing activity:
9766 * dump all activity whose component contains the cmd as a substring
9767 * - A hex number of the ActivityRecord object instance.
9768 */
9769 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9770 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009771 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009772
9773 if ("all".equals(name)) {
9774 synchronized (this) {
9775 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009776 activities.add(r1);
9777 }
9778 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009779 } else if ("top".equals(name)) {
9780 synchronized (this) {
9781 final int N = mMainStack.mHistory.size();
9782 if (N > 0) {
9783 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9784 }
9785 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009786 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009787 ItemMatcher matcher = new ItemMatcher();
9788 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009789
9790 synchronized (this) {
9791 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009792 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009793 activities.add(r1);
9794 }
9795 }
9796 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009797 }
9798
9799 if (activities.size() <= 0) {
9800 return false;
9801 }
9802
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009803 String[] newArgs = new String[args.length - opti];
9804 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9805
Dianne Hackborn30d71892010-12-11 10:37:55 -08009806 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009807 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009808 for (int i=activities.size()-1; i>=0; i--) {
9809 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009810 if (needSep) {
9811 pw.println();
9812 }
9813 needSep = true;
9814 synchronized (this) {
9815 if (lastTask != r.task) {
9816 lastTask = r.task;
9817 pw.print("TASK "); pw.print(lastTask.affinity);
9818 pw.print(" id="); pw.println(lastTask.taskId);
9819 if (dumpAll) {
9820 lastTask.dump(pw, " ");
9821 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009822 }
9823 }
9824 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009825 }
9826 return true;
9827 }
9828
9829 /**
9830 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9831 * there is a thread associated with the activity.
9832 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009833 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 final ActivityRecord r, String[] args, boolean dumpAll) {
9835 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009836 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009837 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9838 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9839 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009840 if (r.app != null) pw.println(r.app.pid);
9841 else pw.println("(not running)");
9842 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009844 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009845 }
9846 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 // flush anything that is already in the PrintWriter since the thread is going
9848 // to write to the file descriptor directly
9849 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009850 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009851 TransferPipe tp = new TransferPipe();
9852 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009853 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9854 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009855 tp.go(fd);
9856 } finally {
9857 tp.kill();
9858 }
9859 } catch (IOException e) {
9860 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009861 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009862 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009863 }
9864 }
9865 }
9866
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009867 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009868 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009869 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009870 boolean onlyHistory = false;
9871
9872 if ("history".equals(dumpPackage)) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -07009873 if (opti < args.length && "-s".equals(args[opti])) {
9874 dumpAll = false;
9875 }
Dianne Hackborn786b4402012-08-27 15:14:02 -07009876 onlyHistory = true;
9877 dumpPackage = null;
9878 }
9879
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009880 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009881 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009882 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009883 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009884 Iterator it = mRegisteredReceivers.values().iterator();
9885 while (it.hasNext()) {
9886 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009887 if (dumpPackage != null && (r.app == null ||
9888 !dumpPackage.equals(r.app.info.packageName))) {
9889 continue;
9890 }
9891 if (!printed) {
9892 pw.println(" Registered Receivers:");
9893 needSep = true;
9894 printed = true;
9895 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009896 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009897 r.dump(pw, " ");
9898 }
9899 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009900
9901 if (mReceiverResolver.dump(pw, needSep ?
9902 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9903 " ", dumpPackage, false)) {
9904 needSep = true;
9905 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009906 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009907
9908 for (BroadcastQueue q : mBroadcastQueues) {
9909 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009911
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009912 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009913
Dianne Hackborn786b4402012-08-27 15:14:02 -07009914 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009915 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9916 if (needSep) {
9917 pw.println();
9918 }
9919 needSep = true;
9920 pw.print(" Sticky broadcasts for user ");
9921 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9922 StringBuilder sb = new StringBuilder(128);
9923 for (Map.Entry<String, ArrayList<Intent>> ent
9924 : mStickyBroadcasts.valueAt(user).entrySet()) {
9925 pw.print(" * Sticky action "); pw.print(ent.getKey());
9926 if (dumpAll) {
9927 pw.println(":");
9928 ArrayList<Intent> intents = ent.getValue();
9929 final int N = intents.size();
9930 for (int i=0; i<N; i++) {
9931 sb.setLength(0);
9932 sb.append(" Intent: ");
9933 intents.get(i).toShortString(sb, false, true, false, false);
9934 pw.println(sb.toString());
9935 Bundle bundle = intents.get(i).getExtras();
9936 if (bundle != null) {
9937 pw.print(" ");
9938 pw.println(bundle.toString());
9939 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009940 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009941 } else {
9942 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009943 }
9944 }
9945 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009946 }
9947
Dianne Hackborn786b4402012-08-27 15:14:02 -07009948 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009949 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009950 for (BroadcastQueue queue : mBroadcastQueues) {
9951 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9952 + queue.mBroadcastsScheduled);
9953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009954 pw.println(" mHandler:");
9955 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009956 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009957 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009958
9959 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009960 }
9961
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009962 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009963 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009964 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009966 ItemMatcher matcher = new ItemMatcher();
9967 matcher.build(args, opti);
9968
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009969 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009970
9971 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009972
9973 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009974 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009975 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009976 ContentProviderRecord r = mLaunchingProviders.get(i);
9977 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9978 continue;
9979 }
9980 if (!printed) {
9981 if (needSep) pw.println(" ");
9982 needSep = true;
9983 pw.println(" Launching content providers:");
9984 printed = true;
9985 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009986 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009987 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009988 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009989 }
9990
9991 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009992 if (needSep) pw.println();
9993 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009994 pw.println("Granted Uri Permissions:");
9995 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9996 int uid = mGrantedUriPermissions.keyAt(i);
9997 HashMap<Uri, UriPermission> perms
9998 = mGrantedUriPermissions.valueAt(i);
9999 pw.print(" * UID "); pw.print(uid);
10000 pw.println(" holds:");
10001 for (UriPermission perm : perms.values()) {
10002 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010003 if (dumpAll) {
10004 perm.dump(pw, " ");
10005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010006 }
10007 }
10008 needSep = true;
10009 }
10010
10011 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010012 }
10013
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010014 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010015 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010016 boolean needSep = false;
10017
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010018 if (mIntentSenderRecords.size() > 0) {
10019 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010020 Iterator<WeakReference<PendingIntentRecord>> it
10021 = mIntentSenderRecords.values().iterator();
10022 while (it.hasNext()) {
10023 WeakReference<PendingIntentRecord> ref = it.next();
10024 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010025 if (dumpPackage != null && (rec == null
10026 || !dumpPackage.equals(rec.key.packageName))) {
10027 continue;
10028 }
10029 if (!printed) {
10030 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
10031 printed = true;
10032 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010033 needSep = true;
10034 if (rec != null) {
10035 pw.print(" * "); pw.println(rec);
10036 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010037 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010038 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010039 } else {
10040 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010041 }
10042 }
10043 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -080010044
10045 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010046 }
10047
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010049 String prefix, String label, boolean complete, boolean brief, boolean client,
10050 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010051 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010052 boolean needNL = false;
10053 final String innerPrefix = prefix + " ";
10054 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010055 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010056 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010057 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
10058 continue;
10059 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -070010060 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010061 if (needNL) {
10062 pw.println(" ");
10063 needNL = false;
10064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010065 if (lastTask != r.task) {
10066 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010067 pw.print(prefix);
10068 pw.print(full ? "* " : " ");
10069 pw.println(lastTask);
10070 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010071 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010072 } else if (complete) {
10073 // Complete + brief == give a summary. Isn't that obvious?!?
10074 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010075 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010076 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010077 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010079 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -070010080 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
10081 pw.print(" #"); pw.print(i); pw.print(": ");
10082 pw.println(r);
10083 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010084 r.dump(pw, innerPrefix);
10085 } else if (complete) {
10086 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -070010087 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010088 if (r.app != null) {
10089 pw.print(innerPrefix); pw.println(r.app);
10090 }
10091 }
10092 if (client && r.app != null && r.app.thread != null) {
10093 // flush anything that is already in the PrintWriter since the thread is going
10094 // to write to the file descriptor directly
10095 pw.flush();
10096 try {
10097 TransferPipe tp = new TransferPipe();
10098 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -080010099 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
10100 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010101 // Short timeout, since blocking here can
10102 // deadlock with the application.
10103 tp.go(fd, 2000);
10104 } finally {
10105 tp.kill();
10106 }
10107 } catch (IOException e) {
10108 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
10109 } catch (RemoteException e) {
10110 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
10111 }
10112 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 }
10115 }
10116
Dianne Hackborn09c916b2009-12-08 14:50:51 -080010117 private static String buildOomTag(String prefix, String space, int val, int base) {
10118 if (val == base) {
10119 if (space == null) return prefix;
10120 return prefix + " ";
10121 }
10122 return prefix + "+" + Integer.toString(val-base);
10123 }
10124
10125 private static final int dumpProcessList(PrintWriter pw,
10126 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010127 String prefix, String normalLabel, String persistentLabel,
10128 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010129 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -070010130 final int N = list.size()-1;
10131 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010132 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010133 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10134 continue;
10135 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010136 pw.println(String.format("%s%s #%2d: %s",
10137 prefix, (r.persistent ? persistentLabel : normalLabel),
10138 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010139 if (r.persistent) {
10140 numPers++;
10141 }
10142 }
10143 return numPers;
10144 }
10145
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010146 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -070010147 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -070010148 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010149 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010150
Dianne Hackborn905577f2011-09-07 18:31:28 -070010151 ArrayList<Pair<ProcessRecord, Integer>> list
10152 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
10153 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010154 ProcessRecord r = origList.get(i);
10155 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
10156 continue;
10157 }
Dianne Hackborn905577f2011-09-07 18:31:28 -070010158 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
10159 }
10160
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010161 if (list.size() <= 0) {
10162 return false;
10163 }
10164
Dianne Hackborn905577f2011-09-07 18:31:28 -070010165 Comparator<Pair<ProcessRecord, Integer>> comparator
10166 = new Comparator<Pair<ProcessRecord, Integer>>() {
10167 @Override
10168 public int compare(Pair<ProcessRecord, Integer> object1,
10169 Pair<ProcessRecord, Integer> object2) {
10170 if (object1.first.setAdj != object2.first.setAdj) {
10171 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10172 }
10173 if (object1.second.intValue() != object2.second.intValue()) {
10174 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10175 }
10176 return 0;
10177 }
10178 };
10179
10180 Collections.sort(list, comparator);
10181
Dianne Hackborn287952c2010-09-22 22:34:31 -070010182 final long curRealtime = SystemClock.elapsedRealtime();
10183 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10184 final long curUptime = SystemClock.uptimeMillis();
10185 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10186
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010187 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010188 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010189 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010190 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010191 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010192 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10193 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010194 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10195 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010196 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10197 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010198 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10199 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010200 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010201 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010202 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10203 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10204 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10205 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10206 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10207 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10208 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10209 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010210 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10211 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010212 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10213 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010214 } else {
10215 oomAdj = Integer.toString(r.setAdj);
10216 }
10217 String schedGroup;
10218 switch (r.setSchedGroup) {
10219 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10220 schedGroup = "B";
10221 break;
10222 case Process.THREAD_GROUP_DEFAULT:
10223 schedGroup = "F";
10224 break;
10225 default:
10226 schedGroup = Integer.toString(r.setSchedGroup);
10227 break;
10228 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010229 String foreground;
10230 if (r.foregroundActivities) {
10231 foreground = "A";
10232 } else if (r.foregroundServices) {
10233 foreground = "S";
10234 } else {
10235 foreground = " ";
10236 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010237 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010238 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010239 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10240 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010241 if (r.adjSource != null || r.adjTarget != null) {
10242 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010243 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010244 if (r.adjTarget instanceof ComponentName) {
10245 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10246 } else if (r.adjTarget != null) {
10247 pw.print(r.adjTarget.toString());
10248 } else {
10249 pw.print("{null}");
10250 }
10251 pw.print("<=");
10252 if (r.adjSource instanceof ProcessRecord) {
10253 pw.print("Proc{");
10254 pw.print(((ProcessRecord)r.adjSource).toShortString());
10255 pw.println("}");
10256 } else if (r.adjSource != null) {
10257 pw.println(r.adjSource.toString());
10258 } else {
10259 pw.println("{null}");
10260 }
10261 }
10262 if (inclDetails) {
10263 pw.print(prefix);
10264 pw.print(" ");
10265 pw.print("oom: max="); pw.print(r.maxAdj);
10266 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010267 pw.print(" client="); pw.print(r.clientHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070010268 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010269 pw.print(" curRaw="); pw.print(r.curRawAdj);
10270 pw.print(" setRaw="); pw.print(r.setRawAdj);
10271 pw.print(" cur="); pw.print(r.curAdj);
10272 pw.print(" set="); pw.println(r.setAdj);
10273 pw.print(prefix);
10274 pw.print(" ");
10275 pw.print("keeping="); pw.print(r.keeping);
10276 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010277 pw.print(" empty="); pw.print(r.empty);
10278 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010279
10280 if (!r.keeping) {
10281 if (r.lastWakeTime != 0) {
10282 long wtime;
10283 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10284 synchronized (stats) {
10285 wtime = stats.getProcessWakeTime(r.info.uid,
10286 r.pid, curRealtime);
10287 }
10288 long timeUsed = wtime - r.lastWakeTime;
10289 pw.print(prefix);
10290 pw.print(" ");
10291 pw.print("keep awake over ");
10292 TimeUtils.formatDuration(realtimeSince, pw);
10293 pw.print(" used ");
10294 TimeUtils.formatDuration(timeUsed, pw);
10295 pw.print(" (");
10296 pw.print((timeUsed*100)/realtimeSince);
10297 pw.println("%)");
10298 }
10299 if (r.lastCpuTime != 0) {
10300 long timeUsed = r.curCpuTime - r.lastCpuTime;
10301 pw.print(prefix);
10302 pw.print(" ");
10303 pw.print("run cpu over ");
10304 TimeUtils.formatDuration(uptimeSince, pw);
10305 pw.print(" used ");
10306 TimeUtils.formatDuration(timeUsed, pw);
10307 pw.print(" (");
10308 pw.print((timeUsed*100)/uptimeSince);
10309 pw.println("%)");
10310 }
10311 }
10312 }
10313 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010314 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010315 }
10316
Dianne Hackbornb437e092011-08-05 17:50:29 -070010317 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010318 ArrayList<ProcessRecord> procs;
10319 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 if (args != null && args.length > start
10321 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010322 procs = new ArrayList<ProcessRecord>();
10323 int pid = -1;
10324 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010325 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010326 } catch (NumberFormatException e) {
10327
10328 }
10329 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10330 ProcessRecord proc = mLruProcesses.get(i);
10331 if (proc.pid == pid) {
10332 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010333 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010334 procs.add(proc);
10335 }
10336 }
10337 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010339 return null;
10340 }
10341 } else {
10342 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10343 }
10344 }
10345 return procs;
10346 }
10347
10348 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10349 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010351 if (procs == null) {
10352 return;
10353 }
10354
10355 long uptime = SystemClock.uptimeMillis();
10356 long realtime = SystemClock.elapsedRealtime();
10357 pw.println("Applications Graphics Acceleration Info:");
10358 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10359
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010360 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10361 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010362 if (r.thread != null) {
10363 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10364 pw.flush();
10365 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010366 TransferPipe tp = new TransferPipe();
10367 try {
10368 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10369 tp.go(fd);
10370 } finally {
10371 tp.kill();
10372 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010373 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010374 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010375 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010376 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010377 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010378 pw.flush();
10379 }
10380 }
10381 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010382 }
10383
Jeff Brown6754ba22011-12-14 20:20:01 -080010384 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10385 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10386 if (procs == null) {
10387 return;
10388 }
10389
10390 pw.println("Applications Database Info:");
10391
10392 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10393 ProcessRecord r = procs.get(i);
10394 if (r.thread != null) {
10395 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10396 pw.flush();
10397 try {
10398 TransferPipe tp = new TransferPipe();
10399 try {
10400 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10401 tp.go(fd);
10402 } finally {
10403 tp.kill();
10404 }
10405 } catch (IOException e) {
10406 pw.println("Failure while dumping the app: " + r);
10407 pw.flush();
10408 } catch (RemoteException e) {
10409 pw.println("Got a RemoteException while dumping the app " + r);
10410 pw.flush();
10411 }
10412 }
10413 }
10414 }
10415
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010416 final static class MemItem {
10417 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010418 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010419 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010420 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010421 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010422
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010423 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010424 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010425 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010426 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010427 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010428 }
10429 }
10430
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010431 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010432 boolean sort) {
10433 if (sort) {
10434 Collections.sort(items, new Comparator<MemItem>() {
10435 @Override
10436 public int compare(MemItem lhs, MemItem rhs) {
10437 if (lhs.pss < rhs.pss) {
10438 return 1;
10439 } else if (lhs.pss > rhs.pss) {
10440 return -1;
10441 }
10442 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010443 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010444 });
10445 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010446
10447 for (int i=0; i<items.size(); i++) {
10448 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010449 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010450 if (mi.subitems != null) {
10451 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10452 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010453 }
10454 }
10455
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010456 // These are in KB.
10457 static final long[] DUMP_MEM_BUCKETS = new long[] {
10458 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10459 120*1024, 160*1024, 200*1024,
10460 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10461 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10462 };
10463
Dianne Hackborn672342c2011-11-29 11:29:02 -080010464 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10465 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010466 int start = label.lastIndexOf('.');
10467 if (start >= 0) start++;
10468 else start = 0;
10469 int end = label.length();
10470 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10471 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10472 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10473 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010474 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010475 out.append(label, start, end);
10476 return;
10477 }
10478 }
10479 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010480 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010481 out.append(label, start, end);
10482 }
10483
10484 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10485 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10486 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10487 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10488 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10489 };
10490 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10491 "System", "Persistent", "Foreground",
10492 "Visible", "Perceptible", "Heavy Weight",
10493 "Backup", "A Services", "Home", "Previous",
10494 "B Services", "Background"
10495 };
10496
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010497 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010498 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010499 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010500 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010501 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010502
10503 int opti = 0;
10504 while (opti < args.length) {
10505 String opt = args[opti];
10506 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10507 break;
10508 }
10509 opti++;
10510 if ("-a".equals(opt)) {
10511 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010512 } else if ("--oom".equals(opt)) {
10513 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010514 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010515 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010516 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010517 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010518 pw.println("If [process] is specified it can be the name or ");
10519 pw.println("pid of a specific process to dump.");
10520 return;
10521 } else {
10522 pw.println("Unknown argument: " + opt + "; use -h for help");
10523 }
10524 }
10525
10526 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010527 if (procs == null) {
10528 return;
10529 }
10530
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010531 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010532 long uptime = SystemClock.uptimeMillis();
10533 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010534
10535 if (procs.size() == 1 || isCheckinRequest) {
10536 dumpAll = true;
10537 }
10538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 if (isCheckinRequest) {
10540 // short checkin version
10541 pw.println(uptime + "," + realtime);
10542 pw.flush();
10543 } else {
10544 pw.println("Applications Memory Usage (kB):");
10545 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10546 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010547
Dianne Hackbornb437e092011-08-05 17:50:29 -070010548 String[] innerArgs = new String[args.length-opti];
10549 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10550
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010551 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10552 long nativePss=0, dalvikPss=0, otherPss=0;
10553 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10554
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010555 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10556 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10557 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010558
10559 long totalPss = 0;
10560
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010561 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10562 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010564 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10566 pw.flush();
10567 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010568 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010569 if (dumpAll) {
10570 try {
10571 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10572 } catch (RemoteException e) {
10573 if (!isCheckinRequest) {
10574 pw.println("Got RemoteException!");
10575 pw.flush();
10576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010578 } else {
10579 mi = new Debug.MemoryInfo();
10580 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010582
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010583 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010584 long myTotalPss = mi.getTotalPss();
10585 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010586 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010587 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010588 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010589
10590 nativePss += mi.nativePss;
10591 dalvikPss += mi.dalvikPss;
10592 otherPss += mi.otherPss;
10593 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10594 long mem = mi.getOtherPss(j);
10595 miscPss[j] += mem;
10596 otherPss -= mem;
10597 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010598
10599 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010600 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10601 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010602 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010603 if (oomProcs[oomIndex] == null) {
10604 oomProcs[oomIndex] = new ArrayList<MemItem>();
10605 }
10606 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010607 break;
10608 }
10609 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 }
10612 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010613
10614 if (!isCheckinRequest && procs.size() > 1) {
10615 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10616
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010617 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10618 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10619 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010620 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010621 String label = Debug.MemoryInfo.getOtherLabel(j);
10622 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010623 }
10624
Dianne Hackbornb437e092011-08-05 17:50:29 -070010625 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10626 for (int j=0; j<oomPss.length; j++) {
10627 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010628 String label = DUMP_MEM_OOM_LABEL[j];
10629 MemItem item = new MemItem(label, label, oomPss[j],
10630 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010631 item.subitems = oomProcs[j];
10632 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010633 }
10634 }
10635
Dianne Hackborn672342c2011-11-29 11:29:02 -080010636 if (outTag != null || outStack != null) {
10637 if (outTag != null) {
10638 appendMemBucket(outTag, totalPss, "total", false);
10639 }
10640 if (outStack != null) {
10641 appendMemBucket(outStack, totalPss, "total", true);
10642 }
10643 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010644 for (int i=0; i<oomMems.size(); i++) {
10645 MemItem miCat = oomMems.get(i);
10646 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10647 continue;
10648 }
10649 if (miCat.id < ProcessList.SERVICE_ADJ
10650 || miCat.id == ProcessList.HOME_APP_ADJ
10651 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010652 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10653 outTag.append(" / ");
10654 }
10655 if (outStack != null) {
10656 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10657 if (firstLine) {
10658 outStack.append(":");
10659 firstLine = false;
10660 }
10661 outStack.append("\n\t at ");
10662 } else {
10663 outStack.append("$");
10664 }
10665 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010666 for (int j=0; j<miCat.subitems.size(); j++) {
10667 MemItem mi = miCat.subitems.get(j);
10668 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010669 if (outTag != null) {
10670 outTag.append(" ");
10671 }
10672 if (outStack != null) {
10673 outStack.append("$");
10674 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010675 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010676 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10677 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10678 }
10679 if (outStack != null) {
10680 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10681 }
10682 }
10683 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10684 outStack.append("(");
10685 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10686 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10687 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10688 outStack.append(":");
10689 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10690 }
10691 }
10692 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010693 }
10694 }
10695 }
10696 }
10697
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010698 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010699 pw.println();
10700 pw.println("Total PSS by process:");
10701 dumpMemItems(pw, " ", procMems, true);
10702 pw.println();
10703 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010704 pw.println("Total PSS by OOM adjustment:");
10705 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010706 if (!oomOnly) {
10707 PrintWriter out = categoryPw != null ? categoryPw : pw;
10708 out.println();
10709 out.println("Total PSS by category:");
10710 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010711 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010712 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010713 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010714 final int[] SINGLE_LONG_FORMAT = new int[] {
10715 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10716 };
10717 long[] longOut = new long[1];
10718 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10719 SINGLE_LONG_FORMAT, null, longOut, null);
10720 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10721 longOut[0] = 0;
10722 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10723 SINGLE_LONG_FORMAT, null, longOut, null);
10724 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10725 longOut[0] = 0;
10726 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10727 SINGLE_LONG_FORMAT, null, longOut, null);
10728 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10729 longOut[0] = 0;
10730 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10731 SINGLE_LONG_FORMAT, null, longOut, null);
10732 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10733 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10734 pw.print(shared); pw.println(" kB");
10735 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10736 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 }
10739
10740 /**
10741 * Searches array of arguments for the specified string
10742 * @param args array of argument strings
10743 * @param value value to search for
10744 * @return true if the value is contained in the array
10745 */
10746 private static boolean scanArgs(String[] args, String value) {
10747 if (args != null) {
10748 for (String arg : args) {
10749 if (value.equals(arg)) {
10750 return true;
10751 }
10752 }
10753 }
10754 return false;
10755 }
10756
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010757 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10758 ContentProviderRecord cpr, boolean always) {
10759 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10760
10761 if (!inLaunching || always) {
10762 synchronized (cpr) {
10763 cpr.launchingApp = null;
10764 cpr.notifyAll();
10765 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010766 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010767 String names[] = cpr.info.authority.split(";");
10768 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010769 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010770 }
10771 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010772
10773 for (int i=0; i<cpr.connections.size(); i++) {
10774 ContentProviderConnection conn = cpr.connections.get(i);
10775 if (conn.waiting) {
10776 // If this connection is waiting for the provider, then we don't
10777 // need to mess with its process unless we are always removing
10778 // or for some reason the provider is not currently launching.
10779 if (inLaunching && !always) {
10780 continue;
10781 }
10782 }
10783 ProcessRecord capp = conn.client;
10784 conn.dead = true;
10785 if (conn.stableCount > 0) {
10786 if (!capp.persistent && capp.thread != null
10787 && capp.pid != 0
10788 && capp.pid != MY_PID) {
10789 Slog.i(TAG, "Kill " + capp.processName
10790 + " (pid " + capp.pid + "): provider " + cpr.info.name
10791 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackbornb12e1352012-09-26 11:39:20 -070010792 EventLog.writeEvent(EventLogTags.AM_KILL, capp.userId, capp.pid,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010793 capp.processName, capp.setAdj, "dying provider "
10794 + cpr.name.toShortString());
10795 Process.killProcessQuiet(capp.pid);
10796 }
10797 } else if (capp.thread != null && conn.provider.provider != null) {
10798 try {
10799 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10800 } catch (RemoteException e) {
10801 }
10802 // In the protocol here, we don't expect the client to correctly
10803 // clean up this connection, we'll just remove it.
10804 cpr.connections.remove(i);
10805 conn.client.conProviders.remove(conn);
10806 }
10807 }
10808
10809 if (inLaunching && always) {
10810 mLaunchingProviders.remove(cpr);
10811 }
10812 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 }
10814
10815 /**
10816 * Main code for cleaning up a process when it has gone away. This is
10817 * called both as a result of the process dying, or directly when stopping
10818 * a process when running in single process mode.
10819 */
10820 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010821 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010823 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 }
10825
Dianne Hackborn36124872009-10-08 16:22:03 -070010826 mProcessesToGc.remove(app);
10827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010828 // Dismiss any open dialogs.
10829 if (app.crashDialog != null) {
10830 app.crashDialog.dismiss();
10831 app.crashDialog = null;
10832 }
10833 if (app.anrDialog != null) {
10834 app.anrDialog.dismiss();
10835 app.anrDialog = null;
10836 }
10837 if (app.waitDialog != null) {
10838 app.waitDialog.dismiss();
10839 app.waitDialog = null;
10840 }
10841
10842 app.crashing = false;
10843 app.notResponding = false;
10844
10845 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010846 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 app.thread = null;
10848 app.forcingToForeground = null;
10849 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010850 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010851 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010852 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010853
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010854 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010855
10856 boolean restart = false;
10857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010858 // Remove published content providers.
10859 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010860 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010862 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010863
10864 final boolean always = app.bad || !allowRestart;
10865 if (removeDyingProviderLocked(app, cpr, always) || always) {
10866 // We left the provider in the launching list, need to
10867 // restart it.
10868 restart = true;
10869 }
10870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010872 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 }
10874 app.pubProviders.clear();
10875 }
10876
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010877 // Take care of any launching providers waiting for this process.
10878 if (checkAppInLaunchingProvidersLocked(app, false)) {
10879 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010880 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 // Unregister from connected content providers.
10883 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010884 for (int i=0; i<app.conProviders.size(); i++) {
10885 ContentProviderConnection conn = app.conProviders.get(i);
10886 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
10888 app.conProviders.clear();
10889 }
10890
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010891 // At this point there may be remaining entries in mLaunchingProviders
10892 // where we were the only one waiting, so they are no longer of use.
10893 // Look for these and clean up if found.
10894 // XXX Commented out for now. Trying to figure out a way to reproduce
10895 // the actual situation to identify what is actually going on.
10896 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010897 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010898 ContentProviderRecord cpr = (ContentProviderRecord)
10899 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010900 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010901 synchronized (cpr) {
10902 cpr.launchingApp = null;
10903 cpr.notifyAll();
10904 }
10905 }
10906 }
10907 }
10908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 skipCurrentReceiverLocked(app);
10910
10911 // Unregister any receivers.
10912 if (app.receivers.size() > 0) {
10913 Iterator<ReceiverList> it = app.receivers.iterator();
10914 while (it.hasNext()) {
10915 removeReceiverLocked(it.next());
10916 }
10917 app.receivers.clear();
10918 }
10919
Christopher Tate181fafa2009-05-14 11:12:14 -070010920 // If the app is undergoing backup, tell the backup manager about it
10921 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010922 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG, "App "
10923 + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010924 try {
10925 IBackupManager bm = IBackupManager.Stub.asInterface(
10926 ServiceManager.getService(Context.BACKUP_SERVICE));
10927 bm.agentDisconnected(app.info.packageName);
10928 } catch (RemoteException e) {
10929 // can't happen; backup manager is local
10930 }
10931 }
10932
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010933 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10934 ProcessChangeItem item = mPendingProcessChanges.get(i);
10935 if (item.pid == app.pid) {
10936 mPendingProcessChanges.remove(i);
10937 mAvailProcessChanges.add(item);
10938 }
10939 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010940 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010942 // If the caller is restarting this app, then leave it in its
10943 // current lists and let the caller take care of it.
10944 if (restarting) {
10945 return;
10946 }
10947
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010948 if (!app.persistent || app.isolated) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010949 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010951 mProcessNames.remove(app.processName, app.uid);
10952 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010953 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010954 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10955 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010956 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958 } else if (!app.removed) {
10959 // This app is persistent, so we need to keep its record around.
10960 // If it is not already on the pending app list, add it there
10961 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10963 mPersistentStartingProcesses.add(app);
10964 restart = true;
10965 }
10966 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -070010967 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v(TAG,
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010968 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 mProcessesOnHold.remove(app);
10970
The Android Open Source Project4df24232009-03-05 14:34:35 -080010971 if (app == mHomeProcess) {
10972 mHomeProcess = null;
10973 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010974 if (app == mPreviousProcess) {
10975 mPreviousProcess = null;
10976 }
10977
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010978 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 // We have components that still need to be running in the
10980 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010981 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 startProcessLocked(app, "restart", app.processName);
10983 } else if (app.pid > 0 && app.pid != MY_PID) {
10984 // Goodbye!
10985 synchronized (mPidsSelfLocked) {
10986 mPidsSelfLocked.remove(app.pid);
10987 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10988 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010989 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990 }
10991 }
10992
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010993 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10994 // Look through the content providers we are waiting to have launched,
10995 // and if any run in this process then either schedule a restart of
10996 // the process or kill the client waiting for it if this process has
10997 // gone bad.
10998 int NL = mLaunchingProviders.size();
10999 boolean restart = false;
11000 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070011001 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011002 if (cpr.launchingApp == app) {
11003 if (!alwaysBad && !app.bad) {
11004 restart = true;
11005 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070011006 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011007 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011008 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070011009 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080011010 }
11011 }
11012 }
11013 return restart;
11014 }
11015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011016 // =========================================================
11017 // SERVICES
11018 // =========================================================
11019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11021 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011022 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011024 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 }
11026 }
11027
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011028 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011029 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011030 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011031 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011032 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011033 }
11034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011036 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011037 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011038 // Refuse possible leaked file descriptors
11039 if (service != null && service.hasFileDescriptors() == true) {
11040 throw new IllegalArgumentException("File descriptors passed in Intent");
11041 }
11042
Amith Yamasani742a6712011-05-04 14:49:28 -070011043 if (DEBUG_SERVICE)
11044 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011045 synchronized(this) {
11046 final int callingPid = Binder.getCallingPid();
11047 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011048 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011050 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011051 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011052 Binder.restoreCallingIdentity(origId);
11053 return res;
11054 }
11055 }
11056
11057 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070011058 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011060 if (DEBUG_SERVICE)
11061 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011062 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011063 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070011064 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 Binder.restoreCallingIdentity(origId);
11066 return res;
11067 }
11068 }
11069
11070 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011071 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011072 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011073 // Refuse possible leaked file descriptors
11074 if (service != null && service.hasFileDescriptors() == true) {
11075 throw new IllegalArgumentException("File descriptors passed in Intent");
11076 }
11077
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011078 checkValidCaller(Binder.getCallingUid(), userId);
11079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070011081 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 }
11084
11085 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011086 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 // Refuse possible leaked file descriptors
11088 if (service != null && service.hasFileDescriptors() == true) {
11089 throw new IllegalArgumentException("File descriptors passed in Intent");
11090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011092 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011094 }
11095
11096 public boolean stopServiceToken(ComponentName className, IBinder token,
11097 int startId) {
11098 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011099 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011101 }
11102
11103 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011104 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011106 mServices.setServiceForegroundLocked(className, token, id, notification,
11107 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108 }
11109 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011110
Dianne Hackborn41203752012-08-31 14:05:51 -070011111 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
11112 boolean requireFull, String name, String callerPackage) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011113 final int callingUserId = UserHandle.getUserId(callingUid);
11114 if (callingUserId != userId) {
11115 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
11116 if ((requireFull || checkComponentPermission(
11117 android.Manifest.permission.INTERACT_ACROSS_USERS,
11118 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
11119 && checkComponentPermission(
11120 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11121 callingPid, callingUid, -1, true)
11122 != PackageManager.PERMISSION_GRANTED) {
11123 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
11124 // In this case, they would like to just execute as their
11125 // owner user instead of failing.
11126 userId = callingUserId;
11127 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070011128 StringBuilder builder = new StringBuilder(128);
11129 builder.append("Permission Denial: ");
11130 builder.append(name);
11131 if (callerPackage != null) {
11132 builder.append(" from ");
11133 builder.append(callerPackage);
11134 }
11135 builder.append(" asks to run as user ");
11136 builder.append(userId);
11137 builder.append(" but is calling from user ");
11138 builder.append(UserHandle.getUserId(callingUid));
11139 builder.append("; this requires ");
11140 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
11141 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070011142 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070011143 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
11144 }
11145 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011146 Slog.w(TAG, msg);
11147 throw new SecurityException(msg);
11148 }
11149 }
11150 }
11151 if (userId == UserHandle.USER_CURRENT
11152 || userId == UserHandle.USER_CURRENT_OR_SELF) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070011153 // Note that we may be accessing this outside of a lock...
11154 // shouldn't be a big deal, if this is being called outside
11155 // of a locked context there is intrinsically a race with
11156 // the value the caller will receive and someone else changing it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011157 userId = mCurrentUserId;
11158 }
11159 if (!allowAll && userId < 0) {
11160 throw new IllegalArgumentException(
11161 "Call does not support special user #" + userId);
11162 }
11163 }
11164 return userId;
11165 }
11166
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011167 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
11168 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011169 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011170 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011171 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11172 if (ActivityManager.checkUidPermission(
11173 android.Manifest.permission.INTERACT_ACROSS_USERS,
11174 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
11175 ComponentName comp = new ComponentName(aInfo.packageName, className);
11176 String msg = "Permission Denial: Component " + comp.flattenToShortString()
11177 + " requests FLAG_SINGLE_USER, but app does not hold "
11178 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11179 Slog.w(TAG, msg);
11180 throw new SecurityException(msg);
11181 }
11182 result = true;
11183 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011184 } else if (componentProcessName == aInfo.packageName) {
11185 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11186 } else if ("system".equals(componentProcessName)) {
11187 result = true;
11188 }
11189 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011190 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
11191 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070011192 }
11193 return result;
11194 }
11195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 public int bindService(IApplicationThread caller, IBinder token,
11197 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011198 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011199 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 // Refuse possible leaked file descriptors
11201 if (service != null && service.hasFileDescriptors() == true) {
11202 throw new IllegalArgumentException("File descriptors passed in Intent");
11203 }
11204
11205 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011206 return mServices.bindServiceLocked(caller, token, service, resolvedType,
11207 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 }
11209 }
11210
11211 public boolean unbindService(IServiceConnection connection) {
11212 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011213 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
11216
11217 public void publishService(IBinder token, Intent intent, IBinder service) {
11218 // Refuse possible leaked file descriptors
11219 if (intent != null && intent.hasFileDescriptors() == true) {
11220 throw new IllegalArgumentException("File descriptors passed in Intent");
11221 }
11222
11223 synchronized(this) {
11224 if (!(token instanceof ServiceRecord)) {
11225 throw new IllegalArgumentException("Invalid service token");
11226 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011227 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011228 }
11229 }
11230
11231 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11232 // Refuse possible leaked file descriptors
11233 if (intent != null && intent.hasFileDescriptors() == true) {
11234 throw new IllegalArgumentException("File descriptors passed in Intent");
11235 }
11236
11237 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011238 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 }
11240 }
11241
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011242 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 synchronized(this) {
11244 if (!(token instanceof ServiceRecord)) {
11245 throw new IllegalArgumentException("Invalid service token");
11246 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070011247 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011248 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 }
11250
11251 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070011252 // BACKUP AND RESTORE
11253 // =========================================================
11254
11255 // Cause the target app to be launched if necessary and its backup agent
11256 // instantiated. The backup agent will invoke backupAgentCreated() on the
11257 // activity manager to announce its creation.
11258 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Christopher Tate346acb12012-10-15 19:20:25 -070011259 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + app + " mode=" + backupMode);
11260 enforceCallingPermission("android.permission.BACKUP", "bindBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011261
11262 synchronized(this) {
11263 // !!! TODO: currently no check here that we're already bound
11264 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11265 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11266 synchronized (stats) {
11267 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11268 }
11269
Dianne Hackborne7f97212011-02-24 14:40:20 -080011270 // Backup agent is now in use, its package can't be stopped.
11271 try {
11272 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011273 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011274 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011275 } catch (IllegalArgumentException e) {
11276 Slog.w(TAG, "Failed trying to unstop package "
11277 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011278 }
11279
Christopher Tate181fafa2009-05-14 11:12:14 -070011280 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011281 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11282 ? new ComponentName(app.packageName, app.backupAgentName)
11283 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011284 // startProcessLocked() returns existing proc's record if it's already running
11285 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011286 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011287 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011288 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011289 return false;
11290 }
11291
11292 r.app = proc;
11293 mBackupTarget = r;
11294 mBackupAppName = app.packageName;
11295
Christopher Tate6fa95972009-06-05 18:43:55 -070011296 // Try not to kill the process during backup
11297 updateOomAdjLocked(proc);
11298
Christopher Tate181fafa2009-05-14 11:12:14 -070011299 // If the process is already attached, schedule the creation of the backup agent now.
11300 // If it is not yet live, this will be done when it attaches to the framework.
11301 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011302 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011303 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011304 proc.thread.scheduleCreateBackupAgent(app,
11305 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011306 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011307 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011308 }
11309 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011310 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011311 }
11312 // Invariants: at this point, the target app process exists and the application
11313 // is either already running or in the process of coming up. mBackupTarget and
11314 // mBackupAppName describe the app, so that when it binds back to the AM we
11315 // know that it's scheduled for a backup-agent operation.
11316 }
11317
11318 return true;
11319 }
11320
Christopher Tate346acb12012-10-15 19:20:25 -070011321 @Override
11322 public void clearPendingBackup() {
11323 if (DEBUG_BACKUP) Slog.v(TAG, "clearPendingBackup");
11324 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup");
11325
11326 synchronized (this) {
11327 mBackupTarget = null;
11328 mBackupAppName = null;
11329 }
11330 }
11331
Christopher Tate181fafa2009-05-14 11:12:14 -070011332 // A backup agent has just come up
11333 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011334 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011335 + " = " + agent);
11336
11337 synchronized(this) {
11338 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011339 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011340 return;
11341 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011342 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011343
Dianne Hackborn06740692010-09-22 22:46:21 -070011344 long oldIdent = Binder.clearCallingIdentity();
11345 try {
11346 IBackupManager bm = IBackupManager.Stub.asInterface(
11347 ServiceManager.getService(Context.BACKUP_SERVICE));
11348 bm.agentConnected(agentPackageName, agent);
11349 } catch (RemoteException e) {
11350 // can't happen; the backup manager service is local
11351 } catch (Exception e) {
11352 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11353 e.printStackTrace();
11354 } finally {
11355 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011356 }
11357 }
11358
11359 // done with this agent
11360 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011361 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011362 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011363 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011364 return;
11365 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011366
11367 synchronized(this) {
Christopher Tate346acb12012-10-15 19:20:25 -070011368 try {
11369 if (mBackupAppName == null) {
11370 Slog.w(TAG, "Unbinding backup agent with no active backup");
11371 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -070011372 }
Christopher Tate346acb12012-10-15 19:20:25 -070011373
11374 if (!mBackupAppName.equals(appInfo.packageName)) {
11375 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
11376 return;
11377 }
11378
11379 // Not backing this app up any more; reset its OOM adjustment
11380 final ProcessRecord proc = mBackupTarget.app;
11381 updateOomAdjLocked(proc);
11382
11383 // If the app crashed during backup, 'thread' will be null here
11384 if (proc.thread != null) {
11385 try {
11386 proc.thread.scheduleDestroyBackupAgent(appInfo,
11387 compatibilityInfoForPackageLocked(appInfo));
11388 } catch (Exception e) {
11389 Slog.e(TAG, "Exception when unbinding backup agent:");
11390 e.printStackTrace();
11391 }
11392 }
11393 } finally {
11394 mBackupTarget = null;
11395 mBackupAppName = null;
Christopher Tate181fafa2009-05-14 11:12:14 -070011396 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011397 }
11398 }
11399 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 // BROADCASTS
11401 // =========================================================
11402
Josh Bartel7f208742010-02-25 11:01:44 -060011403 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011404 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011405 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011406 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11407 if (stickies == null) {
11408 return cur;
11409 }
11410 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 if (list == null) {
11412 return cur;
11413 }
11414 int N = list.size();
11415 for (int i=0; i<N; i++) {
11416 Intent intent = list.get(i);
11417 if (filter.match(resolver, intent, true, TAG) >= 0) {
11418 if (cur == null) {
11419 cur = new ArrayList<Intent>();
11420 }
11421 cur.add(intent);
11422 }
11423 }
11424 return cur;
11425 }
11426
Christopher Tatef46723b2012-01-26 14:19:24 -080011427 boolean isPendingBroadcastProcessLocked(int pid) {
11428 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11429 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11430 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431
Christopher Tatef46723b2012-01-26 14:19:24 -080011432 void skipPendingBroadcastLocked(int pid) {
11433 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11434 for (BroadcastQueue queue : mBroadcastQueues) {
11435 queue.skipPendingBroadcastLocked(pid);
11436 }
11437 }
11438
11439 // The app just attached; send any pending broadcasts that it should receive
11440 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11441 boolean didSomething = false;
11442 for (BroadcastQueue queue : mBroadcastQueues) {
11443 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011445 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 }
11447
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011448 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011449 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011450 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011451 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011452 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 synchronized(this) {
11454 ProcessRecord callerApp = null;
11455 if (caller != null) {
11456 callerApp = getRecordForAppLocked(caller);
11457 if (callerApp == null) {
11458 throw new SecurityException(
11459 "Unable to find app for caller " + caller
11460 + " (pid=" + Binder.getCallingPid()
11461 + ") when registering receiver " + receiver);
11462 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011463 if (callerApp.info.uid != Process.SYSTEM_UID &&
11464 !callerApp.pkgList.contains(callerPackage)) {
11465 throw new SecurityException("Given caller package " + callerPackage
11466 + " is not running in process " + callerApp);
11467 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011468 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011469 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011470 } else {
11471 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011472 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011473 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 }
11475
Dianne Hackborn139748f2012-09-24 11:36:57 -070011476 userId = this.handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011477 true, true, "registerReceiver", callerPackage);
11478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 List allSticky = null;
11480
11481 // Look for any matching sticky broadcasts...
11482 Iterator actions = filter.actionsIterator();
11483 if (actions != null) {
11484 while (actions.hasNext()) {
11485 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011486 allSticky = getStickiesLocked(action, filter, allSticky,
11487 UserHandle.USER_ALL);
11488 allSticky = getStickiesLocked(action, filter, allSticky,
11489 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 }
11491 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011492 allSticky = getStickiesLocked(null, filter, allSticky,
11493 UserHandle.USER_ALL);
11494 allSticky = getStickiesLocked(null, filter, allSticky,
11495 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 }
11497
11498 // The first sticky in the list is returned directly back to
11499 // the client.
11500 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11501
Joe Onorato8a9b2202010-02-26 18:56:32 -080011502 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 + ": " + sticky);
11504
11505 if (receiver == null) {
11506 return sticky;
11507 }
11508
11509 ReceiverList rl
11510 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11511 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011512 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11513 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 if (rl.app != null) {
11515 rl.app.receivers.add(rl);
11516 } else {
11517 try {
11518 receiver.asBinder().linkToDeath(rl, 0);
11519 } catch (RemoteException e) {
11520 return sticky;
11521 }
11522 rl.linkedToDeath = true;
11523 }
11524 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011525 } else if (rl.uid != callingUid) {
11526 throw new IllegalArgumentException(
11527 "Receiver requested to register for uid " + callingUid
11528 + " was previously registered for uid " + rl.uid);
11529 } else if (rl.pid != callingPid) {
11530 throw new IllegalArgumentException(
11531 "Receiver requested to register for pid " + callingPid
11532 + " was previously registered for pid " + rl.pid);
11533 } else if (rl.userId != userId) {
11534 throw new IllegalArgumentException(
11535 "Receiver requested to register for user " + userId
11536 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011538 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011539 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 rl.add(bf);
11541 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011542 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 }
11544 mReceiverResolver.addFilter(bf);
11545
11546 // Enqueue broadcasts for all existing stickies that match
11547 // this filter.
11548 if (allSticky != null) {
11549 ArrayList receivers = new ArrayList();
11550 receivers.add(bf);
11551
11552 int N = allSticky.size();
11553 for (int i=0; i<N; i++) {
11554 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011555 BroadcastQueue queue = broadcastQueueForIntent(intent);
11556 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011557 null, -1, -1, null, AppOpsManager.OP_NONE, receivers, null, 0,
11558 null, null, false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011559 queue.enqueueParallelBroadcastLocked(r);
11560 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 }
11562 }
11563
11564 return sticky;
11565 }
11566 }
11567
11568 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011569 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570
Christopher Tatef46723b2012-01-26 14:19:24 -080011571 final long origId = Binder.clearCallingIdentity();
11572 try {
11573 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011574
Christopher Tatef46723b2012-01-26 14:19:24 -080011575 synchronized(this) {
11576 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011577 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011578 if (rl != null) {
11579 if (rl.curBroadcast != null) {
11580 BroadcastRecord r = rl.curBroadcast;
11581 final boolean doNext = finishReceiverLocked(
11582 receiver.asBinder(), r.resultCode, r.resultData,
11583 r.resultExtras, r.resultAbort, true);
11584 if (doNext) {
11585 doTrim = true;
11586 r.queue.processNextBroadcast(false);
11587 }
11588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589
Christopher Tatef46723b2012-01-26 14:19:24 -080011590 if (rl.app != null) {
11591 rl.app.receivers.remove(rl);
11592 }
11593 removeReceiverLocked(rl);
11594 if (rl.linkedToDeath) {
11595 rl.linkedToDeath = false;
11596 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 }
11599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600
Christopher Tatef46723b2012-01-26 14:19:24 -080011601 // If we actually concluded any broadcasts, we might now be able
11602 // to trim the recipients' apps from our working set
11603 if (doTrim) {
11604 trimApplications();
11605 return;
11606 }
11607
11608 } finally {
11609 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 }
11612
11613 void removeReceiverLocked(ReceiverList rl) {
11614 mRegisteredReceivers.remove(rl.receiver.asBinder());
11615 int N = rl.size();
11616 for (int i=0; i<N; i++) {
11617 mReceiverResolver.removeFilter(rl.get(i));
11618 }
11619 }
11620
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011621 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011622 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11623 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011624 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011625 try {
11626 r.thread.dispatchPackageBroadcast(cmd, packages);
11627 } catch (RemoteException ex) {
11628 }
11629 }
11630 }
11631 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011632
11633 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11634 int[] users) {
11635 List<ResolveInfo> receivers = null;
11636 try {
11637 HashSet<ComponentName> singleUserReceivers = null;
11638 boolean scannedFirstReceivers = false;
11639 for (int user : users) {
11640 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11641 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070011642 if (user != 0 && newReceivers != null) {
11643 // If this is not the primary user, we need to check for
11644 // any receivers that should be filtered out.
11645 for (int i=0; i<newReceivers.size(); i++) {
11646 ResolveInfo ri = newReceivers.get(i);
11647 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
11648 newReceivers.remove(i);
11649 i--;
11650 }
11651 }
11652 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011653 if (newReceivers != null && newReceivers.size() == 0) {
11654 newReceivers = null;
11655 }
11656 if (receivers == null) {
11657 receivers = newReceivers;
11658 } else if (newReceivers != null) {
11659 // We need to concatenate the additional receivers
11660 // found with what we have do far. This would be easy,
11661 // but we also need to de-dup any receivers that are
11662 // singleUser.
11663 if (!scannedFirstReceivers) {
11664 // Collect any single user receivers we had already retrieved.
11665 scannedFirstReceivers = true;
11666 for (int i=0; i<receivers.size(); i++) {
11667 ResolveInfo ri = receivers.get(i);
11668 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11669 ComponentName cn = new ComponentName(
11670 ri.activityInfo.packageName, ri.activityInfo.name);
11671 if (singleUserReceivers == null) {
11672 singleUserReceivers = new HashSet<ComponentName>();
11673 }
11674 singleUserReceivers.add(cn);
11675 }
11676 }
11677 }
11678 // Add the new results to the existing results, tracking
11679 // and de-dupping single user receivers.
11680 for (int i=0; i<newReceivers.size(); i++) {
Dianne Hackborn6cbd33f2012-09-17 18:28:24 -070011681 ResolveInfo ri = newReceivers.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011682 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11683 ComponentName cn = new ComponentName(
11684 ri.activityInfo.packageName, ri.activityInfo.name);
11685 if (singleUserReceivers == null) {
11686 singleUserReceivers = new HashSet<ComponentName>();
11687 }
11688 if (!singleUserReceivers.contains(cn)) {
11689 singleUserReceivers.add(cn);
11690 receivers.add(ri);
11691 }
11692 } else {
11693 receivers.add(ri);
11694 }
11695 }
11696 }
11697 }
11698 } catch (RemoteException ex) {
11699 // pm is in same process, this will never happen.
11700 }
11701 return receivers;
11702 }
11703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 private final int broadcastIntentLocked(ProcessRecord callerApp,
11705 String callerPackage, Intent intent, String resolvedType,
11706 IIntentReceiver resultTo, int resultCode, String resultData,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011707 Bundle map, String requiredPermission, int appOp,
Amith Yamasani742a6712011-05-04 14:49:28 -070011708 boolean ordered, boolean sticky, int callingPid, int callingUid,
11709 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 intent = new Intent(intent);
11711
Dianne Hackborne7f97212011-02-24 14:40:20 -080011712 // By default broadcasts do not go to stopped apps.
11713 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11714
Joe Onorato8a9b2202010-02-26 18:56:32 -080011715 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011717 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011719 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011721
Dianne Hackborn139748f2012-09-24 11:36:57 -070011722 userId = handleIncomingUser(callingPid, callingUid, userId,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011723 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011724
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011725 // Make sure that the user who is receiving this broadcast is started.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011726 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011727 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070011728 if (callingUid != Process.SYSTEM_UID || (intent.getFlags()
11729 & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) {
11730 Slog.w(TAG, "Skipping broadcast of " + intent
11731 + ": user " + userId + " is stopped");
11732 return ActivityManager.BROADCAST_SUCCESS;
11733 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011734 }
11735
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011736 /*
11737 * Prevent non-system code (defined here to be non-persistent
11738 * processes) from sending protected broadcasts.
11739 */
Dianne Hackbornc7ba7712012-09-26 23:22:59 -070011740 int callingAppId = UserHandle.getAppId(callingUid);
11741 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID
11742 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID ||
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011743 callingUid == 0) {
11744 // Always okay.
11745 } else if (callerApp == null || !callerApp.persistent) {
11746 try {
11747 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11748 intent.getAction())) {
11749 String msg = "Permission Denial: not allowed to send broadcast "
11750 + intent.getAction() + " from pid="
11751 + callingPid + ", uid=" + callingUid;
11752 Slog.w(TAG, msg);
11753 throw new SecurityException(msg);
11754 }
11755 } catch (RemoteException e) {
11756 Slog.w(TAG, "Remote exception", e);
11757 return ActivityManager.BROADCAST_SUCCESS;
11758 }
11759 }
11760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 // Handle special intents: if this broadcast is from the package
11762 // manager about a package being removed, we need to remove all of
11763 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011764 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011766 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11767 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011768 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011769 || uidRemoved) {
11770 if (checkComponentPermission(
11771 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011772 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773 == PackageManager.PERMISSION_GRANTED) {
11774 if (uidRemoved) {
11775 final Bundle intentExtras = intent.getExtras();
11776 final int uid = intentExtras != null
11777 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11778 if (uid >= 0) {
11779 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11780 synchronized (bs) {
11781 bs.removeUidStatsLocked(uid);
11782 }
Dianne Hackborn514074f2013-02-11 10:52:46 -080011783 mAppOpsService.uidRemoved(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 }
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 Hackborn514074f2013-02-11 10:52:46 -080011809 if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
11810 mAppOpsService.packageRemoved(
11811 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp);
11812 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 }
11815 }
11816 }
11817 } else {
11818 String msg = "Permission Denial: " + intent.getAction()
11819 + " broadcast from " + callerPackage + " (pid=" + callingPid
11820 + ", uid=" + callingUid + ")"
11821 + " requires "
11822 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011823 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 throw new SecurityException(msg);
11825 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011826
11827 // Special case for adding a package: by default turn on compatibility
11828 // mode.
11829 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011830 Uri data = intent.getData();
11831 String ssp;
11832 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11833 mCompatModePackages.handlePackageAddedLocked(ssp,
11834 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 }
11837
11838 /*
11839 * If this is the time zone changed action, queue up a message that will reset the timezone
11840 * of all currently running processes. This message will get queued up before the broadcast
11841 * happens.
11842 */
11843 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11844 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11845 }
11846
Robert Greenwalt03595d02010-11-02 14:08:23 -070011847 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11848 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11849 }
11850
Robert Greenwalt434203a2010-10-11 16:00:27 -070011851 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11852 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11853 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11854 }
11855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 // Add to the sticky list if requested.
11857 if (sticky) {
11858 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11859 callingPid, callingUid)
11860 != PackageManager.PERMISSION_GRANTED) {
11861 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11862 + callingPid + ", uid=" + callingUid
11863 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011864 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 throw new SecurityException(msg);
11866 }
11867 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011868 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011869 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011870 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871 }
11872 if (intent.getComponent() != null) {
11873 throw new SecurityException(
11874 "Sticky broadcasts can't target a specific component");
11875 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011876 // We use userId directly here, since the "all" target is maintained
11877 // as a separate set of sticky broadcasts.
11878 if (userId != UserHandle.USER_ALL) {
11879 // But first, if this is not a broadcast to all users, then
11880 // make sure it doesn't conflict with an existing broadcast to
11881 // all users.
11882 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11883 UserHandle.USER_ALL);
11884 if (stickies != null) {
11885 ArrayList<Intent> list = stickies.get(intent.getAction());
11886 if (list != null) {
11887 int N = list.size();
11888 int i;
11889 for (i=0; i<N; i++) {
11890 if (intent.filterEquals(list.get(i))) {
11891 throw new IllegalArgumentException(
11892 "Sticky broadcast " + intent + " for user "
11893 + userId + " conflicts with existing global broadcast");
11894 }
11895 }
11896 }
11897 }
11898 }
11899 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11900 if (stickies == null) {
11901 stickies = new HashMap<String, ArrayList<Intent>>();
11902 mStickyBroadcasts.put(userId, stickies);
11903 }
11904 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011905 if (list == null) {
11906 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011907 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 }
11909 int N = list.size();
11910 int i;
11911 for (i=0; i<N; i++) {
11912 if (intent.filterEquals(list.get(i))) {
11913 // This sticky already exists, replace it.
11914 list.set(i, new Intent(intent));
11915 break;
11916 }
11917 }
11918 if (i >= N) {
11919 list.add(new Intent(intent));
11920 }
11921 }
11922
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011923 int[] users;
11924 if (userId == UserHandle.USER_ALL) {
11925 // Caller wants broadcast to go to all started users.
Dianne Hackbornc72fc672012-09-20 13:12:03 -070011926 users = mStartedUserArray;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011927 } else {
11928 // Caller wants broadcast to go to one specific user.
Amith Yamasanie98bde02012-10-01 11:30:47 -070011929 users = new int[] {userId};
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011930 }
11931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011932 // Figure out who all will receive this broadcast.
11933 List receivers = null;
11934 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011935 // Need to resolve the intent to interested receivers...
11936 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11937 == 0) {
11938 receivers = collectReceiverComponents(intent, resolvedType, users);
11939 }
11940 if (intent.getComponent() == null) {
11941 registeredReceivers = mReceiverResolver.queryIntent(intent,
11942 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 }
11944
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011945 final boolean replacePending =
11946 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11947
Joe Onorato8a9b2202010-02-26 18:56:32 -080011948 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011949 + " replacePending=" + replacePending);
11950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011951 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11952 if (!ordered && NR > 0) {
11953 // If we are not serializing this broadcast, then send the
11954 // registered receivers separately so they don't wait for the
11955 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011956 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11957 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080011958 callerPackage, callingPid, callingUid, requiredPermission, appOp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011959 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011960 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011961 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011962 TAG, "Enqueueing parallel broadcast " + r);
11963 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011964 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011965 queue.enqueueParallelBroadcastLocked(r);
11966 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011968 registeredReceivers = null;
11969 NR = 0;
11970 }
11971
11972 // Merge into one list.
11973 int ir = 0;
11974 if (receivers != null) {
11975 // A special case for PACKAGE_ADDED: do not allow the package
11976 // being added to see this broadcast. This prevents them from
11977 // using this as a back door to get run as soon as they are
11978 // installed. Maybe in the future we want to have a special install
11979 // broadcast or such for apps, but we'd like to deliberately make
11980 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011981 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011982 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11983 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11984 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011985 Uri data = intent.getData();
11986 if (data != null) {
11987 String pkgName = data.getSchemeSpecificPart();
11988 if (pkgName != null) {
11989 skipPackages = new String[] { pkgName };
11990 }
11991 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011992 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011993 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011994 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011995 if (skipPackages != null && (skipPackages.length > 0)) {
11996 for (String skipPackage : skipPackages) {
11997 if (skipPackage != null) {
11998 int NT = receivers.size();
11999 for (int it=0; it<NT; it++) {
12000 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12001 if (curt.activityInfo.packageName.equals(skipPackage)) {
12002 receivers.remove(it);
12003 it--;
12004 NT--;
12005 }
12006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 }
12008 }
12009 }
12010
12011 int NT = receivers != null ? receivers.size() : 0;
12012 int it = 0;
12013 ResolveInfo curt = null;
12014 BroadcastFilter curr = null;
12015 while (it < NT && ir < NR) {
12016 if (curt == null) {
12017 curt = (ResolveInfo)receivers.get(it);
12018 }
12019 if (curr == null) {
12020 curr = registeredReceivers.get(ir);
12021 }
12022 if (curr.getPriority() >= curt.priority) {
12023 // Insert this broadcast record into the final list.
12024 receivers.add(it, curr);
12025 ir++;
12026 curr = null;
12027 it++;
12028 NT++;
12029 } else {
12030 // Skip to the next ResolveInfo in the final list.
12031 it++;
12032 curt = null;
12033 }
12034 }
12035 }
12036 while (ir < NR) {
12037 if (receivers == null) {
12038 receivers = new ArrayList();
12039 }
12040 receivers.add(registeredReceivers.get(ir));
12041 ir++;
12042 }
12043
12044 if ((receivers != null && receivers.size() > 0)
12045 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012046 BroadcastQueue queue = broadcastQueueForIntent(intent);
12047 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012048 callerPackage, callingPid, callingUid, requiredPermission, appOp,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012049 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070012050 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012051 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012053 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012054 if (DEBUG_BROADCAST) {
12055 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012056 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012057 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012058 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012059 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012060 queue.enqueueOrderedBroadcastLocked(r);
12061 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 }
12064
Dianne Hackborna4972e92012-03-14 10:38:05 -070012065 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012066 }
12067
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012068 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 // Refuse possible leaked file descriptors
12070 if (intent != null && intent.hasFileDescriptors() == true) {
12071 throw new IllegalArgumentException("File descriptors passed in Intent");
12072 }
12073
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012074 int flags = intent.getFlags();
12075
12076 if (!mProcessesReady) {
12077 // if the caller really truly claims to know what they're doing, go
12078 // ahead and allow the broadcast without launching any receivers
12079 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12080 intent = new Intent(intent);
12081 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12082 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12083 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12084 + " before boot completion");
12085 throw new IllegalStateException("Cannot broadcast before boot completed");
12086 }
12087 }
12088
12089 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12090 throw new IllegalArgumentException(
12091 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12092 }
12093
12094 return intent;
12095 }
12096
12097 public final int broadcastIntent(IApplicationThread caller,
12098 Intent intent, String resolvedType, IIntentReceiver resultTo,
12099 int resultCode, String resultData, Bundle map,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012100 String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012101 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012102 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012103 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012105 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12106 final int callingPid = Binder.getCallingPid();
12107 final int callingUid = Binder.getCallingUid();
12108 final long origId = Binder.clearCallingIdentity();
12109 int res = broadcastIntentLocked(callerApp,
12110 callerApp != null ? callerApp.info.packageName : null,
12111 intent, resolvedType, resultTo,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012112 resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
Amith Yamasani742a6712011-05-04 14:49:28 -070012113 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012114 Binder.restoreCallingIdentity(origId);
12115 return res;
12116 }
12117 }
12118
12119 int broadcastIntentInPackage(String packageName, int uid,
12120 Intent intent, String resolvedType, IIntentReceiver resultTo,
12121 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012122 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012124 intent = verifyBroadcastLocked(intent);
12125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 final long origId = Binder.clearCallingIdentity();
12127 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12128 resultTo, resultCode, resultData, map, requiredPermission,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012129 AppOpsManager.OP_NONE, serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 Binder.restoreCallingIdentity(origId);
12131 return res;
12132 }
12133 }
12134
Amith Yamasani742a6712011-05-04 14:49:28 -070012135 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 // Refuse possible leaked file descriptors
12137 if (intent != null && intent.hasFileDescriptors() == true) {
12138 throw new IllegalArgumentException("File descriptors passed in Intent");
12139 }
12140
Dianne Hackborn139748f2012-09-24 11:36:57 -070012141 userId = handleIncomingUser(Binder.getCallingPid(),
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012142 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
12143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012144 synchronized(this) {
12145 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12146 != PackageManager.PERMISSION_GRANTED) {
12147 String msg = "Permission Denial: unbroadcastIntent() from pid="
12148 + Binder.getCallingPid()
12149 + ", uid=" + Binder.getCallingUid()
12150 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012151 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012152 throw new SecurityException(msg);
12153 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012154 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
12155 if (stickies != null) {
12156 ArrayList<Intent> list = stickies.get(intent.getAction());
12157 if (list != null) {
12158 int N = list.size();
12159 int i;
12160 for (i=0; i<N; i++) {
12161 if (intent.filterEquals(list.get(i))) {
12162 list.remove(i);
12163 break;
12164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012165 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012166 if (list.size() <= 0) {
12167 stickies.remove(intent.getAction());
12168 }
12169 }
12170 if (stickies.size() <= 0) {
12171 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012172 }
12173 }
12174 }
12175 }
12176
12177 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12178 String resultData, Bundle resultExtras, boolean resultAbort,
12179 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012180 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12181 if (r == null) {
12182 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 return false;
12184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012185
Christopher Tatef46723b2012-01-26 14:19:24 -080012186 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12187 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012188 }
12189
12190 public void finishReceiver(IBinder who, int resultCode, String resultData,
12191 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012192 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012193
12194 // Refuse possible leaked file descriptors
12195 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12196 throw new IllegalArgumentException("File descriptors passed in Bundle");
12197 }
12198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012199 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012200 try {
12201 boolean doNext = false;
12202 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012203
Christopher Tatef46723b2012-01-26 14:19:24 -080012204 synchronized(this) {
12205 r = broadcastRecordForReceiverLocked(who);
12206 if (r != null) {
12207 doNext = r.queue.finishReceiverLocked(r, resultCode,
12208 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012211
Christopher Tatef46723b2012-01-26 14:19:24 -080012212 if (doNext) {
12213 r.queue.processNextBroadcast(false);
12214 }
12215 trimApplications();
12216 } finally {
12217 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221 // =========================================================
12222 // INSTRUMENTATION
12223 // =========================================================
12224
12225 public boolean startInstrumentation(ComponentName className,
12226 String profileFile, int flags, Bundle arguments,
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012227 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection,
12228 int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012229 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn139748f2012-09-24 11:36:57 -070012230 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012231 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012232 // Refuse possible leaked file descriptors
12233 if (arguments != null && arguments.hasFileDescriptors()) {
12234 throw new IllegalArgumentException("File descriptors passed in Bundle");
12235 }
12236
12237 synchronized(this) {
12238 InstrumentationInfo ii = null;
12239 ApplicationInfo ai = null;
12240 try {
12241 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012242 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012243 ai = AppGlobals.getPackageManager().getApplicationInfo(
12244 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070012246 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012247 }
12248 if (ii == null) {
12249 reportStartInstrumentationFailure(watcher, className,
12250 "Unable to find instrumentation info for: " + className);
12251 return false;
12252 }
12253 if (ai == null) {
12254 reportStartInstrumentationFailure(watcher, className,
12255 "Unable to find instrumentation target package: " + ii.targetPackage);
12256 return false;
12257 }
12258
12259 int match = mContext.getPackageManager().checkSignatures(
12260 ii.targetPackage, ii.packageName);
12261 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12262 String msg = "Permission Denial: starting instrumentation "
12263 + className + " from pid="
12264 + Binder.getCallingPid()
12265 + ", uid=" + Binder.getCallingPid()
12266 + " not allowed because package " + ii.packageName
12267 + " does not have a signature matching the target "
12268 + ii.targetPackage;
12269 reportStartInstrumentationFailure(watcher, className, msg);
12270 throw new SecurityException(msg);
12271 }
12272
12273 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012274 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012275 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012276 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012277 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012278 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012279 app.instrumentationProfileFile = profileFile;
12280 app.instrumentationArguments = arguments;
12281 app.instrumentationWatcher = watcher;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012282 app.instrumentationUiAutomationConnection = uiAutomationConnection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012283 app.instrumentationResultClass = className;
12284 Binder.restoreCallingIdentity(origId);
12285 }
12286
12287 return true;
12288 }
12289
12290 /**
12291 * Report errors that occur while attempting to start Instrumentation. Always writes the
12292 * error to the logs, but if somebody is watching, send the report there too. This enables
12293 * the "am" command to report errors with more information.
12294 *
12295 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12296 * @param cn The component name of the instrumentation.
12297 * @param report The error report.
12298 */
12299 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12300 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012301 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012302 try {
12303 if (watcher != null) {
12304 Bundle results = new Bundle();
12305 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12306 results.putString("Error", report);
12307 watcher.instrumentationStatus(cn, -1, results);
12308 }
12309 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012310 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012311 }
12312 }
12313
12314 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12315 if (app.instrumentationWatcher != null) {
12316 try {
12317 // NOTE: IInstrumentationWatcher *must* be oneway here
12318 app.instrumentationWatcher.instrumentationFinished(
12319 app.instrumentationClass,
12320 resultCode,
12321 results);
12322 } catch (RemoteException e) {
12323 }
12324 }
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012325 if (app.instrumentationUiAutomationConnection != null) {
12326 try {
12327 app.instrumentationUiAutomationConnection.shutdown();
12328 } catch (RemoteException re) {
12329 /* ignore */
12330 }
12331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012332 app.instrumentationWatcher = null;
Svetoslav Ganov80943d82013-01-02 10:25:37 -080012333 app.instrumentationUiAutomationConnection = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012334 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012335 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 app.instrumentationProfileFile = null;
12337 app.instrumentationArguments = null;
12338
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012339 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012340 }
12341
12342 public void finishInstrumentation(IApplicationThread target,
12343 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012344 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 // Refuse possible leaked file descriptors
12346 if (results != null && results.hasFileDescriptors()) {
12347 throw new IllegalArgumentException("File descriptors passed in Intent");
12348 }
12349
12350 synchronized(this) {
12351 ProcessRecord app = getRecordForAppLocked(target);
12352 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012353 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012354 return;
12355 }
12356 final long origId = Binder.clearCallingIdentity();
12357 finishInstrumentationLocked(app, resultCode, results);
12358 Binder.restoreCallingIdentity(origId);
12359 }
12360 }
12361
12362 // =========================================================
12363 // CONFIGURATION
12364 // =========================================================
12365
12366 public ConfigurationInfo getDeviceConfigurationInfo() {
12367 ConfigurationInfo config = new ConfigurationInfo();
12368 synchronized (this) {
12369 config.reqTouchScreen = mConfiguration.touchscreen;
12370 config.reqKeyboardType = mConfiguration.keyboard;
12371 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012372 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12373 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012374 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12375 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012376 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12377 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012378 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12379 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012380 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381 }
12382 return config;
12383 }
12384
12385 public Configuration getConfiguration() {
12386 Configuration ci;
12387 synchronized(this) {
12388 ci = new Configuration(mConfiguration);
12389 }
12390 return ci;
12391 }
12392
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012393 public void updatePersistentConfiguration(Configuration values) {
12394 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12395 "updateConfiguration()");
12396 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12397 "updateConfiguration()");
12398 if (values == null) {
12399 throw new NullPointerException("Configuration must not be null");
12400 }
12401
12402 synchronized(this) {
12403 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012404 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012405 Binder.restoreCallingIdentity(origId);
12406 }
12407 }
12408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012409 public void updateConfiguration(Configuration values) {
12410 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12411 "updateConfiguration()");
12412
12413 synchronized(this) {
12414 if (values == null && mWindowManager != null) {
12415 // sentinel: fetch the current configuration from the window manager
12416 values = mWindowManager.computeNewConfiguration();
12417 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012418
12419 if (mWindowManager != null) {
12420 mProcessList.applyDisplaySize(mWindowManager);
12421 }
12422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012424 if (values != null) {
12425 Settings.System.clearConfiguration(values);
12426 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012427 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012428 Binder.restoreCallingIdentity(origId);
12429 }
12430 }
12431
12432 /**
12433 * Do either or both things: (1) change the current configuration, and (2)
12434 * make sure the given activity is running with the (now) current
12435 * configuration. Returns true if the activity has been left running, or
12436 * false if <var>starting</var> is being destroyed to match the new
12437 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012438 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012440 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012441 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012442 // do nothing if we are headless
12443 if (mHeadless) return true;
12444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 int changes = 0;
12446
12447 boolean kept = true;
12448
12449 if (values != null) {
12450 Configuration newConfig = new Configuration(mConfiguration);
12451 changes = newConfig.updateFrom(values);
12452 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012453 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012454 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 }
12456
Doug Zongker2bec3d42009-12-04 12:52:44 -080012457 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012458
Dianne Hackborn813075a62011-11-14 17:45:19 -080012459 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012460 saveLocaleLocked(values.locale,
12461 !values.locale.equals(mConfiguration.locale),
12462 values.userSetLocale);
12463 }
12464
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012465 mConfigurationSeq++;
12466 if (mConfigurationSeq <= 0) {
12467 mConfigurationSeq = 1;
12468 }
12469 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 mConfiguration = newConfig;
Craig Mautnerae446592012-12-06 19:05:05 -080012471 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012472
12473 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012474
12475 // TODO: If our config changes, should we auto dismiss any currently
12476 // showing dialogs?
12477 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012478
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012479 AttributeCache ac = AttributeCache.instance();
12480 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012481 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012484 // Make sure all resources in our process are updated
12485 // right now, so that anyone who is going to retrieve
12486 // resource values after we return will be sure to get
12487 // the new ones. This is especially important during
12488 // boot, where the first config change needs to guarantee
12489 // all resources have that config before following boot
12490 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012491 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012492
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012493 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012494 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012495 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012496 mHandler.sendMessage(msg);
12497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012498
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012499 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12500 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 try {
12502 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012503 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012504 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012505 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012506 }
12507 } catch (Exception e) {
12508 }
12509 }
12510 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012511 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012512 | Intent.FLAG_RECEIVER_REPLACE_PENDING
12513 | Intent.FLAG_RECEIVER_FOREGROUND);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012514 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012515 null, AppOpsManager.OP_NONE, false, false, MY_PID,
12516 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012517 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070012518 intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
12519 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12520 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080012521 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
12522 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012524 }
12525 }
12526
12527 if (changes != 0 && starting == null) {
12528 // If the configuration changed, and the caller is not already
12529 // in the process of starting an activity, then find the top
12530 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012531 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012532 }
12533
12534 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012535 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012536 // And we need to make sure at this point that all other activities
12537 // are made visible with the correct configuration.
12538 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012539 }
12540
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012541 if (values != null && mWindowManager != null) {
12542 mWindowManager.setNewConfiguration(mConfiguration);
12543 }
12544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545 return kept;
12546 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012547
12548 /**
12549 * Decide based on the configuration whether we should shouw the ANR,
12550 * crash, etc dialogs. The idea is that if there is no affordnace to
12551 * press the on-screen buttons, we shouldn't show the dialog.
12552 *
12553 * A thought: SystemUI might also want to get told about this, the Power
12554 * dialog / global actions also might want different behaviors.
12555 */
12556 private static final boolean shouldShowDialogs(Configuration config) {
12557 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12558 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012560
12561 /**
12562 * Save the locale. You must be inside a synchronized (this) block.
12563 */
12564 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12565 if(isDiff) {
12566 SystemProperties.set("user.language", l.getLanguage());
12567 SystemProperties.set("user.region", l.getCountry());
12568 }
12569
12570 if(isPersist) {
12571 SystemProperties.set("persist.sys.language", l.getLanguage());
12572 SystemProperties.set("persist.sys.country", l.getCountry());
12573 SystemProperties.set("persist.sys.localevar", l.getVariant());
12574 }
12575 }
12576
Adam Powelldd8fab22012-03-22 17:47:27 -070012577 @Override
12578 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12579 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012580 return srec != null && srec.task.affinity != null &&
12581 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012582 }
12583
12584 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12585 Intent resultData) {
12586 ComponentName dest = destIntent.getComponent();
12587
12588 synchronized (this) {
12589 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012590 if (srec == null) {
12591 return false;
12592 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012593 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12594 final int start = history.indexOf(srec);
12595 if (start < 0) {
12596 // Current activity is not in history stack; do nothing.
12597 return false;
12598 }
12599 int finishTo = start - 1;
12600 ActivityRecord parent = null;
12601 boolean foundParentInTask = false;
12602 if (dest != null) {
12603 TaskRecord tr = srec.task;
12604 for (int i = start - 1; i >= 0; i--) {
12605 ActivityRecord r = history.get(i);
12606 if (tr != r.task) {
12607 // Couldn't find parent in the same task; stop at the one above this.
12608 // (Root of current task; in-app "home" behavior)
12609 // Always at least finish the current activity.
12610 finishTo = Math.min(start - 1, i + 1);
12611 parent = history.get(finishTo);
12612 break;
12613 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12614 r.info.name.equals(dest.getClassName())) {
12615 finishTo = i;
12616 parent = r;
12617 foundParentInTask = true;
12618 break;
12619 }
12620 }
12621 }
12622
12623 if (mController != null) {
12624 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12625 if (next != null) {
12626 // ask watcher if this is allowed
12627 boolean resumeOK = true;
12628 try {
12629 resumeOK = mController.activityResuming(next.packageName);
12630 } catch (RemoteException e) {
12631 mController = null;
12632 }
12633
12634 if (!resumeOK) {
12635 return false;
12636 }
12637 }
12638 }
12639 final long origId = Binder.clearCallingIdentity();
12640 for (int i = start; i > finishTo; i--) {
12641 ActivityRecord r = history.get(i);
12642 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012643 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012644 // Only return the supplied result for the first activity finished
12645 resultCode = Activity.RESULT_CANCELED;
12646 resultData = null;
12647 }
12648
12649 if (parent != null && foundParentInTask) {
12650 final int parentLaunchMode = parent.info.launchMode;
12651 final int destIntentFlags = destIntent.getFlags();
12652 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12653 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12654 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12655 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012656 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012657 } else {
12658 try {
12659 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Amith Yamasaniea7e9152012-09-24 16:11:18 -070012660 destIntent.getComponent(), 0, srec.userId);
Adam Powelldd8fab22012-03-22 17:47:27 -070012661 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12662 null, aInfo, parent.appToken, null,
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012663 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
12664 0, null, true, null);
Adam Powelldd8fab22012-03-22 17:47:27 -070012665 foundParentInTask = res == ActivityManager.START_SUCCESS;
12666 } catch (RemoteException e) {
12667 foundParentInTask = false;
12668 }
12669 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012670 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012671 }
12672 }
12673 Binder.restoreCallingIdentity(origId);
12674 return foundParentInTask;
12675 }
12676 }
12677
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012678 public int getLaunchedFromUid(IBinder activityToken) {
12679 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12680 if (srec == null) {
12681 return -1;
12682 }
12683 return srec.launchedFromUid;
12684 }
12685
Dianne Hackbornf265ea92013-01-31 15:00:51 -080012686 public String getLaunchedFromPackage(IBinder activityToken) {
12687 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12688 if (srec == null) {
12689 return null;
12690 }
12691 return srec.launchedFromPackage;
12692 }
12693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 // =========================================================
12695 // LIFETIME MANAGEMENT
12696 // =========================================================
12697
Christopher Tatef46723b2012-01-26 14:19:24 -080012698 // Returns which broadcast queue the app is the current [or imminent] receiver
12699 // on, or 'null' if the app is not an active broadcast recipient.
12700 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12701 BroadcastRecord r = app.curReceiver;
12702 if (r != null) {
12703 return r.queue;
12704 }
12705
12706 // It's not the current receiver, but it might be starting up to become one
12707 synchronized (this) {
12708 for (BroadcastQueue queue : mBroadcastQueues) {
12709 r = queue.mPendingBroadcast;
12710 if (r != null && r.curApp == app) {
12711 // found it; report which queue it's in
12712 return queue;
12713 }
12714 }
12715 }
12716
12717 return null;
12718 }
12719
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012720 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj, int clientHiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012721 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012722 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012723 // This adjustment has already been computed. If we are calling
12724 // from the top, we may have already computed our adjustment with
12725 // an earlier hidden adjustment that isn't really for us... if
12726 // so, use the new hidden adjustment.
12727 if (!recursed && app.hidden) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012728 if (app.hasActivities) {
12729 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
12730 } else if (app.hasClientActivities) {
12731 app.curAdj = app.curRawAdj = app.nonStoppingAdj = clientHiddenAdj;
12732 } else {
12733 app.curAdj = app.curRawAdj = app.nonStoppingAdj = emptyAdj;
12734 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012735 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012736 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012737 }
12738
12739 if (app.thread == null) {
12740 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012741 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012742 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743 }
12744
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012745 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12746 app.adjSource = null;
12747 app.adjTarget = null;
12748 app.empty = false;
12749 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012750 app.hasClientActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012751
12752 final int activitiesSize = app.activities.size();
12753
Dianne Hackborn7d608422011-08-07 16:24:18 -070012754 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012755 // The max adjustment doesn't allow this app to be anything
12756 // below foreground, so it is not worth doing work for it.
12757 app.adjType = "fixed";
12758 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012759 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012760 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012761 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012762 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012763 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012764 // System process can do UI, and when they do we want to have
12765 // them trim their memory after the user leaves the UI. To
12766 // facilitate this, here we need to determine whether or not it
12767 // is currently showing UI.
12768 app.systemNoUi = true;
12769 if (app == TOP_APP) {
12770 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012771 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012772 } else if (activitiesSize > 0) {
12773 for (int j = 0; j < activitiesSize; j++) {
12774 final ActivityRecord r = app.activities.get(j);
12775 if (r.visible) {
12776 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012777 }
12778 if (r.app == app) {
12779 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012780 }
12781 }
12782 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012783 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012784 }
12785
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012786 app.keeping = false;
12787 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012788 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789
The Android Open Source Project4df24232009-03-05 14:34:35 -080012790 // Determine the importance of the process, starting with most
12791 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012793 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012794 boolean foregroundActivities = false;
12795 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012796 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012797 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012799 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012800 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012801 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012802 foregroundActivities = true;
12803 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012804 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012805 } else if (app.instrumentationClass != null) {
12806 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012807 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012808 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012809 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012810 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012811 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012812 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012813 // counts as being in the foreground for OOM killer purposes.
12814 // It's placed in a sched group based on the nature of the
12815 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012816 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012817 schedGroup = (queue == mFgBroadcastQueue)
12818 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012819 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 } else if (app.executingServices.size() > 0) {
12821 // An app that is currently executing a service callback also
12822 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012823 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012824 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012825 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012826 } else {
12827 // Assume process is hidden (has activities); we will correct
12828 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012829 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012830 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012831 app.hidden = true;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012832 app.adjType = "bg-act";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012834
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012835 boolean hasStoppingActivities = false;
12836
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012837 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012838 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012839 for (int j = 0; j < activitiesSize; j++) {
12840 final ActivityRecord r = app.activities.get(j);
12841 if (r.visible) {
12842 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012843 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12844 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012845 app.adjType = "visible";
12846 }
12847 schedGroup = Process.THREAD_GROUP_DEFAULT;
12848 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012849 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012850 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012851 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012852 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012853 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12854 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012855 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012856 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012857 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012858 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012859 } else if (r.state == ActivityState.STOPPING) {
12860 // We will apply the actual adjustment later, because
12861 // we want to allow this process to immediately go through
12862 // any memory trimming that is in effect.
12863 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012864 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012865 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012866 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012867 if (r.app == app) {
12868 app.hasActivities = true;
12869 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012870 }
12871 }
12872
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012873 if (adj == hiddenAdj && !app.hasActivities) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012874 if (app.hasClientActivities) {
12875 adj = clientHiddenAdj;
12876 app.adjType = "bg-client-act";
12877 } else {
12878 // Whoops, this process is completely empty as far as we know
12879 // at this point.
12880 adj = emptyAdj;
12881 app.empty = true;
12882 app.adjType = "bg-empty";
12883 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012884 }
12885
Dianne Hackborn7d608422011-08-07 16:24:18 -070012886 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012887 if (app.foregroundServices) {
12888 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012889 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012890 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012891 app.adjType = "fg-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012892 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012893 } else if (app.forcingToForeground != null) {
12894 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012895 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012896 app.hidden = false;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070012897 app.adjType = "force-fg";
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012898 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012899 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012900 }
12901 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012902
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012903 if (app.foregroundServices) {
12904 interesting = true;
12905 }
12906
Dianne Hackborn7d608422011-08-07 16:24:18 -070012907 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012908 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012909 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012910 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012911 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012912 app.adjType = "heavy";
12913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914
Dianne Hackborn7d608422011-08-07 16:24:18 -070012915 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012916 // This process is hosting what we currently consider to be the
12917 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012918 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012919 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012920 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012921 app.adjType = "home";
12922 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012923
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012924 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12925 && app.activities.size() > 0) {
12926 // This was the previous process that showed UI to the user.
12927 // We want to try to keep it around more aggressively, to give
12928 // a good experience around switching between two apps.
12929 adj = ProcessList.PREVIOUS_APP_ADJ;
12930 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12931 app.hidden = false;
12932 app.adjType = "previous";
12933 }
12934
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012935 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12936 + " reason=" + app.adjType);
12937
The Android Open Source Project4df24232009-03-05 14:34:35 -080012938 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 // there are applications dependent on our services or providers, but
12940 // this gives us a baseline and makes sure we don't get into an
12941 // infinite recursion.
12942 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012943 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012944
Christopher Tate6fa95972009-06-05 18:43:55 -070012945 if (mBackupTarget != null && app == mBackupTarget.app) {
12946 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012947 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012948 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012949 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012950 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012951 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012952 }
12953 }
12954
Dianne Hackborn7d608422011-08-07 16:24:18 -070012955 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012956 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012957 final long now = SystemClock.uptimeMillis();
12958 // This process is more important if the top activity is
12959 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012960 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012961 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012962 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012963 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012964 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012965 // If this process has shown some UI, let it immediately
12966 // go to the LRU list because it may be pretty heavy with
12967 // UI stuff. We'll tag it with a label just to help
12968 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012969 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012970 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012971 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012972 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012973 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012974 // This service has seen some activity within
12975 // recent memory, so we will keep its process ahead
12976 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012977 if (adj > ProcessList.SERVICE_ADJ) {
12978 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012979 app.adjType = "started-services";
12980 app.hidden = false;
12981 }
12982 }
12983 // If we have let the service slide into the background
12984 // state, still have some text describing what it is doing
12985 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012986 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012987 app.adjType = "started-bg-services";
12988 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012989 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012990 // Don't kill this process because it is doing work; it
12991 // has said it is doing work.
12992 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012994 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012995 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012996 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012998 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012999 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013000 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013001 // XXX should compute this based on the max of
13002 // all connected clients.
13003 ConnectionRecord cr = clist.get(i);
13004 if (cr.binding.client == app) {
13005 // Binding to ourself is not interesting.
13006 continue;
13007 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013008 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013009 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013010 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013011 int myHiddenAdj = hiddenAdj;
13012 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013013 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013014 myHiddenAdj = client.hiddenAdj;
13015 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013016 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013017 }
13018 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013019 int myClientHiddenAdj = clientHiddenAdj;
13020 if (myClientHiddenAdj > client.clientHiddenAdj) {
13021 if (client.clientHiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
13022 myClientHiddenAdj = client.clientHiddenAdj;
13023 } else {
13024 myClientHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
13025 }
13026 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013027 int myEmptyAdj = emptyAdj;
13028 if (myEmptyAdj > client.emptyAdj) {
13029 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
13030 myEmptyAdj = client.emptyAdj;
13031 } else {
13032 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
13033 }
13034 }
13035 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013036 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013037 String adjType = null;
13038 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13039 // Not doing bind OOM management, so treat
13040 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013041 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013042 // If this process has shown some UI, let it immediately
13043 // go to the LRU list because it may be pretty heavy with
13044 // UI stuff. We'll tag it with a label just to help
13045 // debug and understand what is going on.
13046 if (adj > clientAdj) {
13047 adjType = "bound-bg-ui-services";
13048 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013049 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013050 clientAdj = adj;
13051 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013052 if (now >= (s.lastActivity
13053 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013054 // This service has not seen activity within
13055 // recent memory, so allow it to drop to the
13056 // LRU list if there is no other reason to keep
13057 // it around. We'll also tag it with a label just
13058 // to help debug and undertand what is going on.
13059 if (adj > clientAdj) {
13060 adjType = "bound-bg-services";
13061 }
13062 clientAdj = adj;
13063 }
13064 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013065 } else if ((cr.flags&Context.BIND_AUTO_CREATE) != 0) {
13066 if ((cr.flags&Context.BIND_NOT_VISIBLE) == 0) {
13067 // If this connection is keeping the service
13068 // created, then we want to try to better follow
13069 // its memory management semantics for activities.
13070 // That is, if it is sitting in the background
13071 // LRU list as a hidden process (with activities),
13072 // we don't want the service it is connected to
13073 // to go into the empty LRU and quickly get killed,
13074 // because I'll we'll do is just end up restarting
13075 // the service.
13076 app.hasClientActivities |= client.hasActivities;
13077 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013078 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013079 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013080 // If this process has recently shown UI, and
13081 // the process that is binding to it is less
13082 // important than being visible, then we don't
13083 // care about the binding as much as we care
13084 // about letting this process get into the LRU
13085 // list to be killed and restarted if needed for
13086 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013087 if (app.hasShownUi && app != mHomeProcess
13088 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013089 adjType = "bound-bg-ui-services";
13090 } else {
13091 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13092 |Context.BIND_IMPORTANT)) != 0) {
13093 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013094 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13095 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13096 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13097 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13098 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013099 adj = clientAdj;
13100 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013101 app.pendingUiClean = true;
13102 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13103 adj = ProcessList.VISIBLE_APP_ADJ;
13104 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013105 }
13106 if (!client.hidden) {
13107 app.hidden = false;
13108 }
13109 if (client.keeping) {
13110 app.keeping = true;
13111 }
13112 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013113 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013114 }
13115 if (adjType != null) {
13116 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013117 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13118 .REASON_SERVICE_IN_USE;
13119 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013120 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013121 app.adjTarget = s.name;
13122 }
13123 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13124 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13125 schedGroup = Process.THREAD_GROUP_DEFAULT;
13126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013127 }
13128 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013129 final ActivityRecord a = cr.activity;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013130 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013131 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013132 (a.visible || a.state == ActivityState.RESUMED
13133 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013134 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013135 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13136 schedGroup = Process.THREAD_GROUP_DEFAULT;
13137 }
13138 app.hidden = false;
13139 app.adjType = "service";
13140 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13141 .REASON_SERVICE_IN_USE;
13142 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013143 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013144 app.adjTarget = s.name;
13145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 }
13148 }
13149 }
13150 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013151
Dianne Hackborn287952c2010-09-22 22:34:31 -070013152 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013153 // would like to avoid killing it unless it would prevent the current
13154 // application from running. By default we put the process in
13155 // with the rest of the background processes; as we scan through
13156 // its services we may bump it up from there.
13157 if (adj > hiddenAdj) {
13158 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013159 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013160 app.adjType = "bg-services";
13161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013162 }
13163
Dianne Hackborn7d608422011-08-07 16:24:18 -070013164 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013165 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013166 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013167 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013168 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013169 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013170 for (int i = cpr.connections.size()-1;
13171 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
13172 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
13173 i--) {
13174 ContentProviderConnection conn = cpr.connections.get(i);
13175 ProcessRecord client = conn.client;
13176 if (client == app) {
13177 // Being our own client is not interesting.
13178 continue;
13179 }
13180 int myHiddenAdj = hiddenAdj;
13181 if (myHiddenAdj > client.hiddenAdj) {
13182 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
13183 myHiddenAdj = client.hiddenAdj;
13184 } else {
13185 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070013186 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013187 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013188 int myClientHiddenAdj = clientHiddenAdj;
13189 if (myClientHiddenAdj > client.clientHiddenAdj) {
13190 if (client.clientHiddenAdj >= ProcessList.FOREGROUND_APP_ADJ) {
13191 myClientHiddenAdj = client.clientHiddenAdj;
13192 } else {
13193 myClientHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
13194 }
13195 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013196 int myEmptyAdj = emptyAdj;
13197 if (myEmptyAdj > client.emptyAdj) {
13198 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
13199 myEmptyAdj = client.emptyAdj;
13200 } else {
13201 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
13202 }
13203 }
13204 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013205 myClientHiddenAdj, myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013206 if (adj > clientAdj) {
13207 if (app.hasShownUi && app != mHomeProcess
13208 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13209 app.adjType = "bg-ui-provider";
13210 } else {
13211 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13212 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
13213 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013214 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013215 if (!client.hidden) {
13216 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013217 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013218 if (client.keeping) {
13219 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013220 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070013221 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13222 .REASON_PROVIDER_IN_USE;
13223 app.adjSource = client;
13224 app.adjSourceOom = clientAdj;
13225 app.adjTarget = cpr.name;
13226 }
13227 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13228 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013229 }
13230 }
13231 // If the provider has external (non-framework) process
13232 // dependencies, ensure that its adjustment is at least
13233 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013234 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013235 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13236 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013237 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013238 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013239 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013240 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013241 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013242 }
13243 }
13244 }
13245 }
13246
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013247 if (adj == ProcessList.SERVICE_ADJ) {
13248 if (doingAll) {
13249 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13250 mNewNumServiceProcs++;
13251 }
13252 if (app.serviceb) {
13253 adj = ProcessList.SERVICE_B_ADJ;
13254 }
13255 } else {
13256 app.serviceb = false;
13257 }
13258
13259 app.nonStoppingAdj = adj;
13260
13261 if (hasStoppingActivities) {
13262 // Only upgrade adjustment.
13263 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13264 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13265 app.adjType = "stopping";
13266 }
13267 }
13268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013269 app.curRawAdj = adj;
13270
Joe Onorato8a9b2202010-02-26 18:56:32 -080013271 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013272 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13273 if (adj > app.maxAdj) {
13274 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013275 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013276 schedGroup = Process.THREAD_GROUP_DEFAULT;
13277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013279 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013280 app.keeping = true;
13281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013282
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013283 if (app.hasAboveClient) {
13284 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13285 // then we need to drop its adjustment to be lower than the service's
13286 // in order to honor the request. We want to drop it by one adjustment
13287 // level... but there is special meaning applied to various levels so
13288 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013289 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013290 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013291 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13292 adj = ProcessList.VISIBLE_APP_ADJ;
13293 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13294 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13295 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13296 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013297 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013298 adj++;
13299 }
13300 }
13301
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013302 int importance = app.memImportance;
13303 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
13304 app.curAdj = adj;
13305 app.curSchedGroup = schedGroup;
13306 if (!interesting) {
13307 // For this reporting, if there is not something explicitly
13308 // interesting in this process then we will push it to the
13309 // background importance.
13310 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13311 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13312 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13313 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
13314 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13315 } else if (adj >= ProcessList.HOME_APP_ADJ) {
13316 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
13317 } else if (adj >= ProcessList.SERVICE_ADJ) {
13318 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
13319 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
13320 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
13321 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
13322 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
13323 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
13324 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
13325 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
13326 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
13327 } else {
13328 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
13329 }
13330 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013331
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013332 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
13333 if (foregroundActivities != app.foregroundActivities) {
13334 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
13335 }
13336 if (changes != 0) {
13337 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
13338 app.memImportance = importance;
13339 app.foregroundActivities = foregroundActivities;
13340 int i = mPendingProcessChanges.size()-1;
13341 ProcessChangeItem item = null;
13342 while (i >= 0) {
13343 item = mPendingProcessChanges.get(i);
13344 if (item.pid == app.pid) {
13345 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
13346 break;
13347 }
13348 i--;
13349 }
13350 if (i < 0) {
13351 // No existing item in pending changes; need a new one.
13352 final int NA = mAvailProcessChanges.size();
13353 if (NA > 0) {
13354 item = mAvailProcessChanges.remove(NA-1);
13355 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
13356 } else {
13357 item = new ProcessChangeItem();
13358 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13359 }
13360 item.changes = 0;
13361 item.pid = app.pid;
13362 item.uid = app.info.uid;
13363 if (mPendingProcessChanges.size() == 0) {
13364 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13365 "*** Enqueueing dispatch processes changed!");
13366 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13367 }
13368 mPendingProcessChanges.add(item);
13369 }
13370 item.changes |= changes;
13371 item.importance = importance;
13372 item.foregroundActivities = foregroundActivities;
13373 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13374 + Integer.toHexString(System.identityHashCode(item))
13375 + " " + app.toShortString() + ": changes=" + item.changes
13376 + " importance=" + item.importance
13377 + " foreground=" + item.foregroundActivities
13378 + " type=" + app.adjType + " source=" + app.adjSource
13379 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013380 }
13381
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013382 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013383 }
13384
13385 /**
13386 * Ask a given process to GC right now.
13387 */
13388 final void performAppGcLocked(ProcessRecord app) {
13389 try {
13390 app.lastRequestedGc = SystemClock.uptimeMillis();
13391 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013392 if (app.reportLowMemory) {
13393 app.reportLowMemory = false;
13394 app.thread.scheduleLowMemory();
13395 } else {
13396 app.thread.processInBackground();
13397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013398 }
13399 } catch (Exception e) {
13400 // whatever.
13401 }
13402 }
13403
13404 /**
13405 * Returns true if things are idle enough to perform GCs.
13406 */
Josh Bartel7f208742010-02-25 11:01:44 -060013407 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013408 boolean processingBroadcasts = false;
13409 for (BroadcastQueue q : mBroadcastQueues) {
13410 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13411 processingBroadcasts = true;
13412 }
13413 }
13414 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013415 && (mSleeping || (mMainStack.mResumedActivity != null &&
13416 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 }
13418
13419 /**
13420 * Perform GCs on all processes that are waiting for it, but only
13421 * if things are idle.
13422 */
13423 final void performAppGcsLocked() {
13424 final int N = mProcessesToGc.size();
13425 if (N <= 0) {
13426 return;
13427 }
Josh Bartel7f208742010-02-25 11:01:44 -060013428 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013429 while (mProcessesToGc.size() > 0) {
13430 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013431 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013432 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13433 <= SystemClock.uptimeMillis()) {
13434 // To avoid spamming the system, we will GC processes one
13435 // at a time, waiting a few seconds between each.
13436 performAppGcLocked(proc);
13437 scheduleAppGcsLocked();
13438 return;
13439 } else {
13440 // It hasn't been long enough since we last GCed this
13441 // process... put it in the list to wait for its time.
13442 addProcessToGcListLocked(proc);
13443 break;
13444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 }
13446 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013447
13448 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013449 }
13450 }
13451
13452 /**
13453 * If all looks good, perform GCs on all processes waiting for them.
13454 */
13455 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013456 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013457 performAppGcsLocked();
13458 return;
13459 }
13460 // Still not idle, wait some more.
13461 scheduleAppGcsLocked();
13462 }
13463
13464 /**
13465 * Schedule the execution of all pending app GCs.
13466 */
13467 final void scheduleAppGcsLocked() {
13468 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013469
13470 if (mProcessesToGc.size() > 0) {
13471 // Schedule a GC for the time to the next process.
13472 ProcessRecord proc = mProcessesToGc.get(0);
13473 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13474
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013475 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013476 long now = SystemClock.uptimeMillis();
13477 if (when < (now+GC_TIMEOUT)) {
13478 when = now + GC_TIMEOUT;
13479 }
13480 mHandler.sendMessageAtTime(msg, when);
13481 }
13482 }
13483
13484 /**
13485 * Add a process to the array of processes waiting to be GCed. Keeps the
13486 * list in sorted order by the last GC time. The process can't already be
13487 * on the list.
13488 */
13489 final void addProcessToGcListLocked(ProcessRecord proc) {
13490 boolean added = false;
13491 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13492 if (mProcessesToGc.get(i).lastRequestedGc <
13493 proc.lastRequestedGc) {
13494 added = true;
13495 mProcessesToGc.add(i+1, proc);
13496 break;
13497 }
13498 }
13499 if (!added) {
13500 mProcessesToGc.add(0, proc);
13501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502 }
13503
13504 /**
13505 * Set up to ask a process to GC itself. This will either do it
13506 * immediately, or put it on the list of processes to gc the next
13507 * time things are idle.
13508 */
13509 final void scheduleAppGcLocked(ProcessRecord app) {
13510 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013511 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 return;
13513 }
13514 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013515 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 scheduleAppGcsLocked();
13517 }
13518 }
13519
Dianne Hackborn287952c2010-09-22 22:34:31 -070013520 final void checkExcessivePowerUsageLocked(boolean doKills) {
13521 updateCpuStatsNow();
13522
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013523 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013524 boolean doWakeKills = doKills;
13525 boolean doCpuKills = doKills;
13526 if (mLastPowerCheckRealtime == 0) {
13527 doWakeKills = false;
13528 }
13529 if (mLastPowerCheckUptime == 0) {
13530 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013531 }
13532 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013533 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013534 }
13535 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013536 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13537 final long curUptime = SystemClock.uptimeMillis();
13538 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13539 mLastPowerCheckRealtime = curRealtime;
13540 mLastPowerCheckUptime = curUptime;
13541 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13542 doWakeKills = false;
13543 }
13544 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13545 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013546 }
13547 int i = mLruProcesses.size();
13548 while (i > 0) {
13549 i--;
13550 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013551 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013552 long wtime;
13553 synchronized (stats) {
13554 wtime = stats.getProcessWakeTime(app.info.uid,
13555 app.pid, curRealtime);
13556 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013557 long wtimeUsed = wtime - app.lastWakeTime;
13558 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13559 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013560 StringBuilder sb = new StringBuilder(128);
13561 sb.append("Wake for ");
13562 app.toShortString(sb);
13563 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013564 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013565 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013566 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013567 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013568 sb.append((wtimeUsed*100)/realtimeSince);
13569 sb.append("%)");
13570 Slog.i(TAG, sb.toString());
13571 sb.setLength(0);
13572 sb.append("CPU for ");
13573 app.toShortString(sb);
13574 sb.append(": over ");
13575 TimeUtils.formatDuration(uptimeSince, sb);
13576 sb.append(" used ");
13577 TimeUtils.formatDuration(cputimeUsed, sb);
13578 sb.append(" (");
13579 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013580 sb.append("%)");
13581 Slog.i(TAG, sb.toString());
13582 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013583 // If a process has held a wake lock for more
13584 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013585 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013586 if (doWakeKills && realtimeSince > 0
13587 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13588 synchronized (stats) {
13589 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13590 realtimeSince, wtimeUsed);
13591 }
13592 Slog.w(TAG, "Excessive wake lock in " + app.processName
13593 + " (pid " + app.pid + "): held " + wtimeUsed
13594 + " during " + realtimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013595 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013596 app.processName, app.setAdj, "excessive wake lock");
13597 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013598 } else if (doCpuKills && uptimeSince > 0
13599 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13600 synchronized (stats) {
13601 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13602 uptimeSince, cputimeUsed);
13603 }
13604 Slog.w(TAG, "Excessive CPU in " + app.processName
13605 + " (pid " + app.pid + "): used " + cputimeUsed
13606 + " during " + uptimeSince);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013607 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn287952c2010-09-22 22:34:31 -070013608 app.processName, app.setAdj, "excessive cpu");
13609 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013610 } else {
13611 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013612 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013613 }
13614 }
13615 }
13616 }
13617
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013618 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013619 int clientHiddenAdj, int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 app.hiddenAdj = hiddenAdj;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013621 app.clientHiddenAdj = clientHiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013622 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013623
13624 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013625 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 }
13627
Dianne Hackborn287952c2010-09-22 22:34:31 -070013628 final boolean wasKeeping = app.keeping;
13629
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013630 boolean success = true;
13631
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013632 computeOomAdjLocked(app, hiddenAdj, clientHiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633
Jeff Brown10e89712011-07-08 18:52:57 -070013634 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013635 if (wasKeeping && !app.keeping) {
13636 // This app is no longer something we want to keep. Note
13637 // its current wake lock time to later know to kill it if
13638 // it is not behaving well.
13639 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13640 synchronized (stats) {
13641 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13642 app.pid, SystemClock.elapsedRealtime());
13643 }
13644 app.lastCpuTime = app.curCpuTime;
13645 }
13646
13647 app.setRawAdj = app.curRawAdj;
13648 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013649
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013650 if (app.curAdj != app.setAdj) {
13651 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013652 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013653 TAG, "Set " + app.pid + " " + app.processName +
13654 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013655 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013656 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013657 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013658 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013659 }
13660 }
13661 if (app.setSchedGroup != app.curSchedGroup) {
13662 app.setSchedGroup = app.curSchedGroup;
13663 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13664 "Setting process group of " + app.processName
13665 + " to " + app.curSchedGroup);
13666 if (app.waitingToKill != null &&
13667 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13668 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013669 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Jeff Brown10e89712011-07-08 18:52:57 -070013670 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013671 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013672 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013673 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013674 } else {
13675 if (true) {
13676 long oldId = Binder.clearCallingIdentity();
13677 try {
13678 Process.setProcessGroup(app.pid, app.curSchedGroup);
13679 } catch (Exception e) {
13680 Slog.w(TAG, "Failed setting process group of " + app.pid
13681 + " to " + app.curSchedGroup);
13682 e.printStackTrace();
13683 } finally {
13684 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013685 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013686 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013687 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013688 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013689 app.thread.setSchedulingGroup(app.curSchedGroup);
13690 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013691 }
13692 }
13693 }
13694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013696 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013697 }
13698
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013699 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013700 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013702 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013704 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013705 }
13706 }
13707 return resumedActivity;
13708 }
13709
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013710 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013711 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013712 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13713 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013714 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13715 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013716
13717 mAdjSeq++;
13718
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013719 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.clientHiddenAdj,
13720 app.emptyAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013721 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13722 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013723 if (nowHidden != wasHidden) {
13724 // Changed to/from hidden state, so apps after it in the LRU
13725 // list may also be changed.
13726 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013727 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013728 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013729 }
13730
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013731 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013732 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013733 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013734 final long oldTime = SystemClock.uptimeMillis() - ProcessList.MAX_EMPTY_TIME;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013735
13736 if (false) {
13737 RuntimeException e = new RuntimeException();
13738 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013739 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013740 }
13741
13742 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013743 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013744
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013745 final int emptyProcessLimit;
13746 final int hiddenProcessLimit;
13747 if (mProcessLimit <= 0) {
13748 emptyProcessLimit = hiddenProcessLimit = 0;
13749 } else if (mProcessLimit == 1) {
13750 emptyProcessLimit = 1;
13751 hiddenProcessLimit = 0;
13752 } else {
13753 emptyProcessLimit = (mProcessLimit*2)/3;
13754 hiddenProcessLimit = mProcessLimit - emptyProcessLimit;
13755 }
13756
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013757 // Let's determine how many processes we have running vs.
13758 // how many slots we have for background processes; we may want
13759 // to put multiple processes in a slot of there are enough of
13760 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013761 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13762 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013763 int numEmptyProcs = mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs;
13764 if (numEmptyProcs > hiddenProcessLimit) {
13765 // If there are more empty processes than our limit on hidden
13766 // processes, then use the hidden process limit for the factor.
13767 // This ensures that the really old empty processes get pushed
13768 // down to the bottom, so if we are running low on memory we will
13769 // have a better chance at keeping around more hidden processes
13770 // instead of a gazillion empty processes.
13771 numEmptyProcs = hiddenProcessLimit;
13772 }
13773 int emptyFactor = numEmptyProcs/numSlots;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013774 if (emptyFactor < 1) emptyFactor = 1;
13775 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13776 if (hiddenFactor < 1) hiddenFactor = 1;
13777 int stepHidden = 0;
13778 int stepEmpty = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013779 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013780 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013781 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013782
13783 mNumNonHiddenProcs = 0;
13784 mNumHiddenProcs = 0;
13785
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013786 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013788 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013789 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013790 int nextHiddenAdj = curHiddenAdj+1;
13791 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13792 int nextEmptyAdj = curEmptyAdj+2;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013793 int curClientHiddenAdj = curEmptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 while (i > 0) {
13795 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013796 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013797 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013798 updateOomAdjLocked(app, curHiddenAdj, curClientHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013799 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013800 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13801 // This process was assigned as a hidden process... step the
13802 // hidden level.
13803 mNumHiddenProcs++;
13804 if (curHiddenAdj != nextHiddenAdj) {
13805 stepHidden++;
13806 if (stepHidden >= hiddenFactor) {
13807 stepHidden = 0;
13808 curHiddenAdj = nextHiddenAdj;
13809 nextHiddenAdj += 2;
13810 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13811 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13812 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013813 if (curClientHiddenAdj <= curHiddenAdj) {
13814 curClientHiddenAdj = curHiddenAdj + 1;
13815 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13816 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13817 }
13818 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013819 }
13820 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013821 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013822 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013823 Slog.i(TAG, "No longer want " + app.processName
13824 + " (pid " + app.pid + "): hidden #" + numHidden);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013825 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013826 app.processName, app.setAdj, "too many background");
13827 app.killedBackground = true;
13828 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013829 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013830 } else if (app.curRawAdj == curHiddenAdj && app.hasClientActivities) {
13831 // This process has a client that has activities. We will have
13832 // given it the current hidden adj; here we will just leave it
13833 // without stepping the hidden adj.
13834 curClientHiddenAdj++;
13835 if (curClientHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13836 curClientHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13837 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013838 } else {
13839 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13840 // This process was assigned as an empty process... step the
13841 // empty level.
13842 if (curEmptyAdj != nextEmptyAdj) {
13843 stepEmpty++;
13844 if (stepEmpty >= emptyFactor) {
13845 stepEmpty = 0;
13846 curEmptyAdj = nextEmptyAdj;
13847 nextEmptyAdj += 2;
13848 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13849 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13850 }
13851 }
13852 }
13853 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13854 mNumNonHiddenProcs++;
13855 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013856 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13857 && !app.hasClientActivities) {
13858 if (numEmpty > ProcessList.TRIM_EMPTY_APPS
13859 && app.lastActivityTime < oldTime) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013860 Slog.i(TAG, "No longer want " + app.processName
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013861 + " (pid " + app.pid + "): empty for "
13862 + ((oldTime+ProcessList.MAX_EMPTY_TIME-app.lastActivityTime)
13863 / 1000) + "s");
13864 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13865 app.processName, app.setAdj, "old background process");
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013866 app.killedBackground = true;
13867 Process.killProcessQuiet(app.pid);
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013868 } else {
13869 numEmpty++;
13870 if (numEmpty > emptyProcessLimit) {
13871 Slog.i(TAG, "No longer want " + app.processName
13872 + " (pid " + app.pid + "): empty #" + numEmpty);
13873 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
13874 app.processName, app.setAdj, "too many background");
13875 app.killedBackground = true;
13876 Process.killProcessQuiet(app.pid);
13877 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013878 }
13879 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013880 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013881 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013882 // If this is an isolated process, and there are no
13883 // services running in it, then the process is no longer
13884 // needed. We agressively kill these because we can by
13885 // definition not re-use the same process again, and it is
13886 // good to avoid having whatever code was running in them
13887 // left sitting around after no longer needed.
13888 Slog.i(TAG, "Isolated process " + app.processName
13889 + " (pid " + app.pid + ") no longer needed");
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013890 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013891 app.processName, app.setAdj, "isolated not needed");
13892 app.killedBackground = true;
13893 Process.killProcessQuiet(app.pid);
13894 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013895 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13896 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13897 && !app.killedBackground) {
13898 numTrimming++;
13899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013900 }
13901 }
13902
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013903 mNumServiceProcs = mNewNumServiceProcs;
13904
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013905 // Now determine the memory trimming level of background processes.
13906 // Unfortunately we need to start at the back of the list to do this
13907 // properly. We only do this if the number of background apps we
13908 // are managing to keep around is less than half the maximum we desire;
13909 // if we are keeping a good number around, we'll let them use whatever
13910 // memory they want.
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013911 if (numHidden <= ProcessList.TRIM_HIDDEN_APPS
13912 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013913 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013914 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013915 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013916 int minFactor = 2;
13917 if (mHomeProcess != null) minFactor++;
13918 if (mPreviousProcess != null) minFactor++;
13919 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013920 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013921 int fgTrimLevel;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013922 if (numHiddenAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013923 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornb12e1352012-09-26 11:39:20 -070013924 } else if (numHiddenAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013925 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13926 } else {
13927 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13928 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013929 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013930 for (i=0; i<N; i++) {
13931 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013932 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13933 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013934 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013935 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13936 try {
13937 app.thread.scheduleTrimMemory(curLevel);
13938 } catch (RemoteException e) {
13939 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013940 if (false) {
13941 // For now we won't do this; our memory trimming seems
13942 // to be good enough at this point that destroying
13943 // activities causes more harm than good.
13944 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13945 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013946 // Need to do this on its own message because the stack may not
13947 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013948 // For these apps we will also finish their activities
13949 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013950 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013951 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013952 }
13953 }
13954 app.trimMemoryLevel = curLevel;
13955 step++;
13956 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013957 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013958 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013959 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13960 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013961 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013962 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13963 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013964 break;
13965 }
13966 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013967 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013968 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013969 && app.thread != null) {
13970 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013971 app.thread.scheduleTrimMemory(
13972 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013973 } catch (RemoteException e) {
13974 }
13975 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013976 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013977 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013978 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013979 && app.pendingUiClean) {
13980 // If this application is now in the background and it
13981 // had done UI, then give it the special trim level to
13982 // have it free UI resources.
13983 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13984 if (app.trimMemoryLevel < level && app.thread != null) {
13985 try {
13986 app.thread.scheduleTrimMemory(level);
13987 } catch (RemoteException e) {
13988 }
13989 }
13990 app.pendingUiClean = false;
13991 }
13992 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013993 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013994 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013995 } catch (RemoteException e) {
13996 }
13997 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013998 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013999 }
14000 }
14001 } else {
14002 final int N = mLruProcesses.size();
14003 for (i=0; i<N; i++) {
14004 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014005 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014006 && app.pendingUiClean) {
14007 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14008 && app.thread != null) {
14009 try {
14010 app.thread.scheduleTrimMemory(
14011 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14012 } catch (RemoteException e) {
14013 }
14014 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014015 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014016 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014017 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014018 }
14019 }
14020
14021 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014022 // Need to do this on its own message because the stack may not
14023 // be in a consistent state at this point.
14024 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014026 }
14027
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014028 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014029 synchronized (this) {
14030 int i;
14031
14032 // First remove any unused application processes whose package
14033 // has been removed.
14034 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14035 final ProcessRecord app = mRemovedProcesses.get(i);
14036 if (app.activities.size() == 0
14037 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014038 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014039 TAG, "Exiting empty application process "
14040 + app.processName + " ("
14041 + (app.thread != null ? app.thread.asBinder() : null)
14042 + ")\n");
14043 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -070014044 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid,
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014045 app.processName, app.setAdj, "empty");
14046 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 } else {
14048 try {
14049 app.thread.scheduleExit();
14050 } catch (Exception e) {
14051 // Ignore exceptions.
14052 }
14053 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014054 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014055 mRemovedProcesses.remove(i);
14056
14057 if (app.persistent) {
14058 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014059 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014060 }
14061 }
14062 }
14063 }
14064
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014065 // Now update the oom adj for all processes.
14066 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014067 }
14068 }
14069
14070 /** This method sends the specified signal to each of the persistent apps */
14071 public void signalPersistentProcesses(int sig) throws RemoteException {
14072 if (sig != Process.SIGNAL_USR1) {
14073 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14074 }
14075
14076 synchronized (this) {
14077 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14078 != PackageManager.PERMISSION_GRANTED) {
14079 throw new SecurityException("Requires permission "
14080 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14081 }
14082
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014083 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14084 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014085 if (r.thread != null && r.persistent) {
14086 Process.sendSignal(r.pid, sig);
14087 }
14088 }
14089 }
14090 }
14091
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014092 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14093 if (proc == null || proc == mProfileProc) {
14094 proc = mProfileProc;
14095 path = mProfileFile;
14096 profileType = mProfileType;
14097 clearProfilerLocked();
14098 }
14099 if (proc == null) {
14100 return;
14101 }
14102 try {
14103 proc.thread.profilerControl(false, path, null, profileType);
14104 } catch (RemoteException e) {
14105 throw new IllegalStateException("Process disappeared");
14106 }
14107 }
14108
14109 private void clearProfilerLocked() {
14110 if (mProfileFd != null) {
14111 try {
14112 mProfileFd.close();
14113 } catch (IOException e) {
14114 }
14115 }
14116 mProfileApp = null;
14117 mProfileProc = null;
14118 mProfileFile = null;
14119 mProfileType = 0;
14120 mAutoStopProfiler = false;
14121 }
14122
Dianne Hackborn1676c852012-09-10 14:52:30 -070014123 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014124 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014125
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014126 try {
14127 synchronized (this) {
14128 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14129 // its own permission.
14130 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14131 != PackageManager.PERMISSION_GRANTED) {
14132 throw new SecurityException("Requires permission "
14133 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
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 if (start && fd == null) {
14137 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014138 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014139
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014140 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014141 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014142 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014143 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014144
14145 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014146 throw new IllegalArgumentException("Unknown process: " + process);
14147 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014148
14149 if (start) {
14150 stopProfilerLocked(null, null, 0);
14151 setProfileApp(proc.info, proc.processName, path, fd, false);
14152 mProfileProc = proc;
14153 mProfileType = profileType;
14154 try {
14155 fd = fd.dup();
14156 } catch (IOException e) {
14157 fd = null;
14158 }
14159 proc.thread.profilerControl(start, path, fd, profileType);
14160 fd = null;
14161 mProfileFd = null;
14162 } else {
14163 stopProfilerLocked(proc, path, profileType);
14164 if (fd != null) {
14165 try {
14166 fd.close();
14167 } catch (IOException e) {
14168 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014169 }
14170 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014171
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014172 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014173 }
14174 } catch (RemoteException e) {
14175 throw new IllegalStateException("Process disappeared");
14176 } finally {
14177 if (fd != null) {
14178 try {
14179 fd.close();
14180 } catch (IOException e) {
14181 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014182 }
14183 }
14184 }
Andy McFadden824c5102010-07-09 16:26:57 -070014185
Dianne Hackborn1676c852012-09-10 14:52:30 -070014186 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
Dianne Hackborn139748f2012-09-24 11:36:57 -070014187 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
Dianne Hackborn1676c852012-09-10 14:52:30 -070014188 userId, true, true, callName, null);
14189 ProcessRecord proc = null;
14190 try {
14191 int pid = Integer.parseInt(process);
14192 synchronized (mPidsSelfLocked) {
14193 proc = mPidsSelfLocked.get(pid);
14194 }
14195 } catch (NumberFormatException e) {
14196 }
14197
14198 if (proc == null) {
14199 HashMap<String, SparseArray<ProcessRecord>> all
14200 = mProcessNames.getMap();
14201 SparseArray<ProcessRecord> procs = all.get(process);
14202 if (procs != null && procs.size() > 0) {
14203 proc = procs.valueAt(0);
14204 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
14205 for (int i=1; i<procs.size(); i++) {
14206 ProcessRecord thisProc = procs.valueAt(i);
14207 if (thisProc.userId == userId) {
14208 proc = thisProc;
14209 break;
14210 }
14211 }
14212 }
14213 }
14214 }
14215
14216 return proc;
14217 }
14218
14219 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070014220 String path, ParcelFileDescriptor fd) throws RemoteException {
14221
14222 try {
14223 synchronized (this) {
14224 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14225 // its own permission (same as profileControl).
14226 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14227 != PackageManager.PERMISSION_GRANTED) {
14228 throw new SecurityException("Requires permission "
14229 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14230 }
14231
14232 if (fd == null) {
14233 throw new IllegalArgumentException("null fd");
14234 }
14235
Dianne Hackborn1676c852012-09-10 14:52:30 -070014236 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070014237 if (proc == null || proc.thread == null) {
14238 throw new IllegalArgumentException("Unknown process: " + process);
14239 }
14240
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014241 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14242 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014243 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14244 throw new SecurityException("Process not debuggable: " + proc);
14245 }
14246 }
14247
14248 proc.thread.dumpHeap(managed, path, fd);
14249 fd = null;
14250 return true;
14251 }
14252 } catch (RemoteException e) {
14253 throw new IllegalStateException("Process disappeared");
14254 } finally {
14255 if (fd != null) {
14256 try {
14257 fd.close();
14258 } catch (IOException e) {
14259 }
14260 }
14261 }
14262 }
14263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014264 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14265 public void monitor() {
14266 synchronized (this) { }
14267 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014268
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014269 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014270 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14271 ProcessRecord processRecord = mLruProcesses.get(i);
14272 try {
14273 if (processRecord.thread != null) {
14274 processRecord.thread.setCoreSettings(settings);
14275 }
14276 } catch (RemoteException re) {
14277 /* ignore */
14278 }
14279 }
14280 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014281
14282 // Multi-user methods
14283
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014284 @Override
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014285 public boolean switchUser(final int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014286 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14287 != PackageManager.PERMISSION_GRANTED) {
14288 String msg = "Permission Denial: switchUser() from pid="
14289 + Binder.getCallingPid()
14290 + ", uid=" + Binder.getCallingUid()
14291 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14292 Slog.w(TAG, msg);
14293 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070014294 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014295
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014296 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014297 try {
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014298 synchronized (this) {
14299 final int oldUserId = mCurrentUserId;
14300 if (oldUserId == userId) {
14301 return true;
14302 }
14303
14304 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId);
14305 if (userInfo == null) {
14306 Slog.w(TAG, "No user info for user #" + userId);
14307 return false;
14308 }
14309
14310 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
14311 R.anim.screen_user_enter);
14312
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014313 boolean needStart = false;
14314
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014315 // If the user we are switching to is not currently started, then
14316 // we need to start it now.
14317 if (mStartedUsers.get(userId) == null) {
14318 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014319 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014320 needStart = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014321 }
14322
14323 mCurrentUserId = userId;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014324 mCurrentUserArray = new int[] { userId };
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014325 final Integer userIdInt = Integer.valueOf(userId);
14326 mUserLru.remove(userIdInt);
14327 mUserLru.add(userIdInt);
14328
Craig Mautnerf1b67412012-09-19 13:18:29 -070014329 mWindowManager.setCurrentUser(userId);
14330
Adam Cohenf7522022012-10-03 20:03:18 -070014331 // Once the internal notion of the active user has switched, we lock the device
14332 // with the option to show the user switcher on the keyguard.
Winson Chungf7614fc2012-11-26 14:43:24 -080014333 mWindowManager.lockNow(null);
Adam Cohenf7522022012-10-03 20:03:18 -070014334
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014335 final UserStartedState uss = mStartedUsers.get(userId);
14336
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014337 // Make sure user is in the started state. If it is currently
14338 // stopping, we need to knock that off.
14339 if (uss.mState == UserStartedState.STATE_STOPPING) {
14340 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
14341 // so we can just fairly silently bring the user back from
14342 // the almost-dead.
14343 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014344 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014345 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014346 } else if (uss.mState == UserStartedState.STATE_SHUTDOWN) {
14347 // This means ACTION_SHUTDOWN has been sent, so we will
14348 // need to treat this as a new boot of the user.
14349 uss.mState = UserStartedState.STATE_BOOTING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014350 updateStartedUserArrayLocked();
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014351 needStart = true;
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014352 }
14353
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014354 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
14355 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14356 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
14357 oldUserId, userId, uss));
14358 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
14359 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014360 if (needStart) {
14361 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
14362 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14363 | Intent.FLAG_RECEIVER_FOREGROUND);
14364 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14365 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014366 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014367 false, false, MY_PID, Process.SYSTEM_UID, userId);
14368 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014369
14370 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
14371 if (userId != 0) {
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014372 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014373 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014374 broadcastIntentLocked(null, null, intent, null,
14375 new IIntentReceiver.Stub() {
14376 public void performReceive(Intent intent, int resultCode,
14377 String data, Bundle extras, boolean ordered,
14378 boolean sticky, int sendingUser) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014379 userInitialized(uss, userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014380 }
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014381 }, 0, null, null, null, AppOpsManager.OP_NONE,
14382 true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014383 userId);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014384 uss.initializing = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014385 } else {
14386 getUserManagerLocked().makeInitialized(userInfo.id);
14387 }
14388 }
14389
14390 boolean haveActivities = mMainStack.switchUserLocked(userId, uss);
14391 if (!haveActivities) {
14392 startHomeActivityLocked(userId);
14393 }
Craig Mautnerf1b67412012-09-19 13:18:29 -070014394
Jeff Sharkey86597df2012-11-09 15:00:31 -080014395 EventLogTags.writeAmSwitchUser(userId);
Amith Yamasani920ace02012-09-20 22:15:37 -070014396 getUserManagerLocked().userForeground(userId);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014397 sendUserSwitchBroadcastsLocked(oldUserId, userId);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014398 if (needStart) {
14399 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
14400 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14401 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14402 broadcastIntentLocked(null, null, intent,
14403 null, new IIntentReceiver.Stub() {
14404 @Override
14405 public void performReceive(Intent intent, int resultCode, String data,
14406 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
14407 throws RemoteException {
14408 }
14409 }, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014410 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014411 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornc0bd7472012-10-09 14:00:30 -070014412 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014413 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014414 } finally {
14415 Binder.restoreCallingIdentity(ident);
14416 }
Amith Yamasani13593602012-03-22 16:16:17 -070014417
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014418 return true;
14419 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014420
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014421 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
14422 long ident = Binder.clearCallingIdentity();
14423 try {
14424 Intent intent;
14425 if (oldUserId >= 0) {
14426 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014427 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14428 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014429 intent.putExtra(Intent.EXTRA_USER_HANDLE, oldUserId);
14430 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014431 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014432 false, false, MY_PID, Process.SYSTEM_UID, oldUserId);
14433 }
14434 if (newUserId >= 0) {
14435 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014436 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14437 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014438 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14439 broadcastIntentLocked(null, null, intent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014440 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014441 false, false, MY_PID, Process.SYSTEM_UID, newUserId);
14442 intent = new Intent(Intent.ACTION_USER_SWITCHED);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014443 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
14444 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014445 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
14446 broadcastIntentLocked(null, null, intent,
14447 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014448 android.Manifest.permission.MANAGE_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014449 false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
14450 }
14451 } finally {
14452 Binder.restoreCallingIdentity(ident);
14453 }
14454 }
14455
14456 void dispatchUserSwitch(final UserStartedState uss, final int oldUserId,
14457 final int newUserId) {
14458 final int N = mUserSwitchObservers.beginBroadcast();
14459 if (N > 0) {
14460 final IRemoteCallback callback = new IRemoteCallback.Stub() {
14461 int mCount = 0;
14462 @Override
14463 public void sendResult(Bundle data) throws RemoteException {
14464 synchronized (ActivityManagerService.this) {
14465 if (mCurUserSwitchCallback == this) {
14466 mCount++;
14467 if (mCount == N) {
14468 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14469 }
14470 }
14471 }
14472 }
14473 };
14474 synchronized (this) {
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014475 uss.switching = true;
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014476 mCurUserSwitchCallback = callback;
14477 }
14478 for (int i=0; i<N; i++) {
14479 try {
14480 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
14481 newUserId, callback);
14482 } catch (RemoteException e) {
14483 }
14484 }
14485 } else {
14486 synchronized (this) {
14487 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14488 }
14489 }
14490 mUserSwitchObservers.finishBroadcast();
14491 }
14492
14493 void timeoutUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
14494 synchronized (this) {
14495 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
14496 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
14497 }
14498 }
14499
14500 void sendContinueUserSwitchLocked(UserStartedState uss, int oldUserId, int newUserId) {
14501 mCurUserSwitchCallback = null;
14502 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
14503 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
14504 oldUserId, newUserId, uss));
14505 }
14506
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014507 void userInitialized(UserStartedState uss, int newUserId) {
14508 completeSwitchAndInitalize(uss, newUserId, true, false);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014509 }
14510
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014511 void continueUserSwitch(UserStartedState uss, int oldUserId, int newUserId) {
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014512 completeSwitchAndInitalize(uss, newUserId, false, true);
Dianne Hackbornd4ac8d72012-09-27 23:20:10 -070014513 }
14514
Dianne Hackborn4d78abf2012-11-29 15:10:18 -080014515 void completeSwitchAndInitalize(UserStartedState uss, int newUserId,
14516 boolean clearInitializing, boolean clearSwitching) {
14517 boolean unfrozen = false;
14518 synchronized (this) {
14519 if (clearInitializing) {
14520 uss.initializing = false;
14521 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier());
14522 }
14523 if (clearSwitching) {
14524 uss.switching = false;
14525 }
14526 if (!uss.switching && !uss.initializing) {
14527 mWindowManager.stopFreezingScreen();
14528 unfrozen = true;
14529 }
14530 }
14531 if (unfrozen) {
14532 final int N = mUserSwitchObservers.beginBroadcast();
14533 for (int i=0; i<N; i++) {
14534 try {
14535 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
14536 } catch (RemoteException e) {
14537 }
14538 }
14539 mUserSwitchObservers.finishBroadcast();
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014540 }
14541 }
14542
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014543 void finishUserSwitch(UserStartedState uss) {
14544 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014545 if (uss.mState == UserStartedState.STATE_BOOTING
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014546 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
14547 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070014548 final int userId = uss.mHandle.getIdentifier();
14549 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
14550 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14551 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014552 null, null, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014553 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, AppOpsManager.OP_NONE,
Dianne Hackborn41203752012-08-31 14:05:51 -070014554 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014555 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014556 int num = mUserLru.size();
14557 int i = 0;
14558 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
14559 Integer oldUserId = mUserLru.get(i);
14560 UserStartedState oldUss = mStartedUsers.get(oldUserId);
14561 if (oldUss == null) {
14562 // Shouldn't happen, but be sane if it does.
14563 mUserLru.remove(i);
14564 num--;
14565 continue;
14566 }
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014567 if (oldUss.mState == UserStartedState.STATE_STOPPING
14568 || oldUss.mState == UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014569 // This user is already stopping, doesn't count.
14570 num--;
14571 i++;
14572 continue;
14573 }
14574 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) {
14575 // Owner and current can't be stopped, but count as running.
14576 i++;
14577 continue;
14578 }
14579 // This is a user to be stopped.
14580 stopUserLocked(oldUserId, null);
14581 num--;
14582 i++;
14583 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014584 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070014585 }
14586
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014587 @Override
14588 public int stopUser(final int userId, final IStopUserCallback callback) {
14589 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14590 != PackageManager.PERMISSION_GRANTED) {
14591 String msg = "Permission Denial: switchUser() from pid="
14592 + Binder.getCallingPid()
14593 + ", uid=" + Binder.getCallingUid()
14594 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14595 Slog.w(TAG, msg);
14596 throw new SecurityException(msg);
14597 }
14598 if (userId <= 0) {
14599 throw new IllegalArgumentException("Can't stop primary user " + userId);
14600 }
Amith Yamasani13593602012-03-22 16:16:17 -070014601 synchronized (this) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014602 return stopUserLocked(userId, callback);
14603 }
14604 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014605
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014606 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
14607 if (mCurrentUserId == userId) {
14608 return ActivityManager.USER_OP_IS_CURRENT;
14609 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014610
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014611 final UserStartedState uss = mStartedUsers.get(userId);
14612 if (uss == null) {
14613 // User is not started, nothing to do... but we do need to
14614 // callback if requested.
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014615 if (callback != null) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014616 mHandler.post(new Runnable() {
14617 @Override
14618 public void run() {
14619 try {
14620 callback.userStopped(userId);
14621 } catch (RemoteException e) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014622 }
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014623 }
14624 });
14625 }
14626 return ActivityManager.USER_OP_SUCCESS;
14627 }
14628
14629 if (callback != null) {
14630 uss.mStopCallbacks.add(callback);
14631 }
14632
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014633 if (uss.mState != UserStartedState.STATE_STOPPING
14634 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014635 uss.mState = UserStartedState.STATE_STOPPING;
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014636 updateStartedUserArrayLocked();
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014637
14638 long ident = Binder.clearCallingIdentity();
14639 try {
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014640 // We are going to broadcast ACTION_USER_STOPPING and then
Dianne Hackborn40e9f292012-11-27 19:12:23 -080014641 // once that is done send a final ACTION_SHUTDOWN and then
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014642 // stop the user.
14643 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
14644 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
14645 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
14646 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
14647 // This is the result receiver for the final shutdown broadcast.
14648 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014649 @Override
14650 public void performReceive(Intent intent, int resultCode, String data,
14651 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14652 finishUserStop(uss);
14653 }
14654 };
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014655 // This is the result receiver for the initial stopping broadcast.
14656 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
14657 @Override
14658 public void performReceive(Intent intent, int resultCode, String data,
14659 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
14660 // On to the next.
14661 synchronized (ActivityManagerService.this) {
14662 if (uss.mState != UserStartedState.STATE_STOPPING) {
14663 // Whoops, we are being started back up. Abort, abort!
14664 return;
14665 }
14666 uss.mState = UserStartedState.STATE_SHUTDOWN;
14667 }
14668 broadcastIntentLocked(null, null, shutdownIntent,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014669 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014670 true, false, MY_PID, Process.SYSTEM_UID, userId);
14671 }
14672 };
14673 // Kick things off.
14674 broadcastIntentLocked(null, null, stoppingIntent,
14675 null, stoppingReceiver, 0, null, null,
Dianne Hackbornf51f6122013-02-04 18:23:34 -080014676 android.Manifest.permission.INTERACT_ACROSS_USERS, AppOpsManager.OP_NONE,
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014677 true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014678 } finally {
14679 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014680 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014681 }
Amith Yamasani13593602012-03-22 16:16:17 -070014682
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014683 return ActivityManager.USER_OP_SUCCESS;
14684 }
14685
14686 void finishUserStop(UserStartedState uss) {
14687 final int userId = uss.mHandle.getIdentifier();
14688 boolean stopped;
14689 ArrayList<IStopUserCallback> callbacks;
14690 synchronized (this) {
14691 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014692 if (mStartedUsers.get(userId) != uss) {
14693 stopped = false;
14694 } else if (uss.mState != UserStartedState.STATE_SHUTDOWN) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014695 stopped = false;
14696 } else {
14697 stopped = true;
14698 // User can no longer run.
14699 mStartedUsers.remove(userId);
Dianne Hackbornbb1aeff2012-09-18 15:48:21 -070014700 mUserLru.remove(Integer.valueOf(userId));
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014701 updateStartedUserArrayLocked();
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014702
14703 // Clean up all state and processes associated with the user.
14704 // Kill all the processes for the user.
14705 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014706 }
14707 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014708
14709 for (int i=0; i<callbacks.size(); i++) {
14710 try {
14711 if (stopped) callbacks.get(i).userStopped(userId);
14712 else callbacks.get(i).userStopAborted(userId);
14713 } catch (RemoteException e) {
14714 }
14715 }
14716 }
14717
14718 @Override
14719 public UserInfo getCurrentUser() {
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014720 if ((checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14721 != PackageManager.PERMISSION_GRANTED) && (
14722 checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14723 != PackageManager.PERMISSION_GRANTED)) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014724 String msg = "Permission Denial: getCurrentUser() from pid="
14725 + Binder.getCallingPid()
14726 + ", uid=" + Binder.getCallingUid()
Jeff Sharkey27bd34d2012-09-16 12:49:00 -070014727 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014728 Slog.w(TAG, msg);
14729 throw new SecurityException(msg);
14730 }
14731 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014732 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014733 }
Amith Yamasani13593602012-03-22 16:16:17 -070014734 }
14735
Dianne Hackborn50cdf7c32012-09-23 17:08:57 -070014736 int getCurrentUserIdLocked() {
14737 return mCurrentUserId;
14738 }
14739
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014740 @Override
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014741 public boolean isUserRunning(int userId, boolean orStopped) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014742 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14743 != PackageManager.PERMISSION_GRANTED) {
14744 String msg = "Permission Denial: isUserRunning() from pid="
14745 + Binder.getCallingPid()
14746 + ", uid=" + Binder.getCallingUid()
14747 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14748 Slog.w(TAG, msg);
14749 throw new SecurityException(msg);
14750 }
14751 synchronized (this) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014752 return isUserRunningLocked(userId, orStopped);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014753 }
14754 }
14755
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014756 boolean isUserRunningLocked(int userId, boolean orStopped) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014757 UserStartedState state = mStartedUsers.get(userId);
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014758 if (state == null) {
14759 return false;
14760 }
14761 if (orStopped) {
14762 return true;
14763 }
14764 return state.mState != UserStartedState.STATE_STOPPING
Dianne Hackborn36d337a2012-10-08 14:33:47 -070014765 && state.mState != UserStartedState.STATE_SHUTDOWN;
Amith Yamasani258848d2012-08-10 17:06:33 -070014766 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014767
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014768 @Override
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014769 public int[] getRunningUserIds() {
14770 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14771 != PackageManager.PERMISSION_GRANTED) {
14772 String msg = "Permission Denial: isUserRunning() from pid="
14773 + Binder.getCallingPid()
14774 + ", uid=" + Binder.getCallingUid()
14775 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14776 Slog.w(TAG, msg);
14777 throw new SecurityException(msg);
14778 }
14779 synchronized (this) {
14780 return mStartedUserArray;
14781 }
14782 }
14783
14784 private void updateStartedUserArrayLocked() {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014785 int num = 0;
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014786 for (int i=0; i<mStartedUsers.size(); i++) {
Dianne Hackborna8a9bd62012-10-09 15:36:59 -070014787 UserStartedState uss = mStartedUsers.valueAt(i);
14788 // This list does not include stopping users.
14789 if (uss.mState != UserStartedState.STATE_STOPPING
14790 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14791 num++;
14792 }
14793 }
14794 mStartedUserArray = new int[num];
14795 num = 0;
14796 for (int i=0; i<mStartedUsers.size(); i++) {
14797 UserStartedState uss = mStartedUsers.valueAt(i);
14798 if (uss.mState != UserStartedState.STATE_STOPPING
14799 && uss.mState != UserStartedState.STATE_SHUTDOWN) {
14800 mStartedUserArray[num] = mStartedUsers.keyAt(i);
14801 num++;
14802 }
Dianne Hackbornc72fc672012-09-20 13:12:03 -070014803 }
14804 }
14805
14806 @Override
Dianne Hackborn5dc5a002012-09-15 19:33:48 -070014807 public void registerUserSwitchObserver(IUserSwitchObserver observer) {
14808 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14809 != PackageManager.PERMISSION_GRANTED) {
14810 String msg = "Permission Denial: registerUserSwitchObserver() from pid="
14811 + Binder.getCallingPid()
14812 + ", uid=" + Binder.getCallingUid()
14813 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14814 Slog.w(TAG, msg);
14815 throw new SecurityException(msg);
14816 }
14817
14818 mUserSwitchObservers.register(observer);
14819 }
14820
14821 @Override
14822 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
14823 mUserSwitchObservers.unregister(observer);
14824 }
14825
Dianne Hackborn1676c852012-09-10 14:52:30 -070014826 private boolean userExists(int userId) {
14827 if (userId == 0) {
14828 return true;
14829 }
14830 UserManagerService ums = getUserManagerLocked();
14831 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14832 }
14833
14834 int[] getUsersLocked() {
14835 UserManagerService ums = getUserManagerLocked();
14836 return ums != null ? ums.getUserIds() : new int[] { 0 };
14837 }
14838
14839 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014840 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014841 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14842 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014843 }
14844 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014845 }
14846
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014847 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014848 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014849
14850 throw new SecurityException("Caller uid=" + uid
14851 + " is not privileged to communicate with user=" + userId);
14852 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014853
14854 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014855 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014856 }
14857
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014858 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014859 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014860 ApplicationInfo newInfo = new ApplicationInfo(info);
14861 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014862 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14863 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014864 return newInfo;
14865 }
14866
14867 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014868 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014869 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014870 return aInfo;
14871 }
14872
14873 ActivityInfo info = new ActivityInfo(aInfo);
14874 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14875 return info;
14876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014877}