blob: 1c5a8a5d985901f619bf130f7d8458905be159de [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborn1676c852012-09-10 14:52:30 -070030import com.android.server.pm.UserManagerService;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080031import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032
Dianne Hackborndd71fc82009-12-16 19:24:32 -080033import dalvik.system.Zygote;
34
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.app.Activity;
36import android.app.ActivityManager;
37import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070038import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.app.ActivityThread;
40import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070041import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020042import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070044import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.app.IApplicationThread;
46import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070047import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070048import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070050import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.app.IThumbnailReceiver;
52import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070053import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070054import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080056import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020057import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080058import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080059import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070060import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070062import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.content.ContentResolver;
64import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020065import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070066import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070067import android.content.IIntentReceiver;
68import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070069import android.content.Intent;
70import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070071import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.content.pm.ActivityInfo;
73import android.content.pm.ApplicationInfo;
74import android.content.pm.ConfigurationInfo;
75import android.content.pm.IPackageDataObserver;
76import android.content.pm.IPackageManager;
77import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080078import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070080import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070081import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070082import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.content.pm.ProviderInfo;
84import android.content.pm.ResolveInfo;
85import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040086import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.content.res.Configuration;
88import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070089import android.net.Proxy;
90import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.net.Uri;
92import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080093import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080094import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070095import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080096import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080098import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.os.FileUtils;
100import android.os.Handler;
101import android.os.IBinder;
102import android.os.IPermissionController;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700103import android.os.IUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.os.Looper;
105import android.os.Message;
106import android.os.Parcel;
107import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700109import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400111import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700113import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.os.SystemClock;
115import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700116import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700118import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800120import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700121import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700123import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.util.SparseArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700125import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.view.Gravity;
127import android.view.LayoutInflater;
128import android.view.View;
129import android.view.WindowManager;
130import android.view.WindowManagerPolicy;
131
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.BufferedInputStream;
133import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700134import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.DataInputStream;
136import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.File;
138import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200142import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800143import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700145import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.lang.ref.WeakReference;
147import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700148import java.util.Collections;
149import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.util.HashMap;
151import java.util.HashSet;
152import java.util.Iterator;
153import java.util.List;
154import java.util.Locale;
155import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700179 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700180 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800181 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700184 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700185 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_POWER = localLOGV || false;
187 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean VALIDATE_TOKENS = false;
190 static final boolean SHOW_ACTIVITY_START_TIME = true;
191
192 // Control over CPU and battery monitoring.
193 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
194 static final boolean MONITOR_CPU_USAGE = true;
195 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
196 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
197 static final boolean MONITOR_THREAD_CPU_USAGE = false;
198
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700200 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800202 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700204 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Maximum number of recent tasks that we can remember.
207 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700208
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700209 // Amount of time after a call to stopAppSwitches() during which we will
210 // prevent further untrusted switches from happening.
211 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 // How long we wait for a launched process to attach to the activity manager
214 // before we decide it's never going to come up for real.
215 static final int PROC_START_TIMEOUT = 10*1000;
216
Jeff Brown3f9dd282011-07-08 20:02:19 -0700217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real, when the process was
219 // started with a wrapper for instrumentation (such as Valgrind) because it
220 // could take much longer than usual.
221 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // How long to wait after going idle before forcing apps to GC.
224 static final int GC_TIMEOUT = 5*1000;
225
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700226 // The minimum amount of time between successive GC requests for a process.
227 static final int GC_MIN_INTERVAL = 60*1000;
228
Dianne Hackborn287952c2010-09-22 22:34:31 -0700229 // The rate at which we check for apps using excessive power -- 15 mins.
230 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
231
232 // The minimum sample duration we will allow before deciding we have
233 // enough data on wake locks to start killing things.
234 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on CPU usage to start killing things.
238 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800241 static final int BROADCAST_FG_TIMEOUT = 10*1000;
242 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we wait until we timeout on key dispatching.
245 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we wait until we timeout on key dispatching during instrumentation.
248 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
249
Dan Egnor42471dd2010-01-07 17:25:22 -0800250 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 static final String[] EMPTY_STRING_ARRAY = new String[0];
253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700254 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700255
256 private final boolean mHeadless;
257
Joe Onorato54a4a412011-11-02 20:50:08 -0700258 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
259 // default actuion automatically. Important for devices without direct input
260 // devices.
261 private boolean mShowDialogs = true;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700264 * Description of a request to start a new activity, which has been held
265 * due to app switches being disabled.
266 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700267 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700268 ActivityRecord r;
269 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700270 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700271 }
272
273 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
274 = new ArrayList<PendingActivityLaunch>();
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800277 BroadcastQueue mFgBroadcastQueue;
278 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800279 // Convenient for easy iteration over the queues. Foreground is first
280 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800282
283 BroadcastQueue broadcastQueueForIntent(Intent intent) {
284 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
285 if (DEBUG_BACKGROUND_BROADCAST) {
286 Slog.i(TAG, "Broadcast intent " + intent + " on "
287 + (isFg ? "foreground" : "background")
288 + " queue");
289 }
290 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
291 }
292
293 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
294 for (BroadcastQueue queue : mBroadcastQueues) {
295 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
296 if (r != null) {
297 return r;
298 }
299 }
300 return null;
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * Activity we have told the window manager to have key focus.
305 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700306 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * List of intents that were used to start the most recent tasks.
309 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700310 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700313 * Process management.
314 */
315 final ProcessList mProcessList = new ProcessList();
316
317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * All of the applications we currently have running organized by name.
319 * The keys are strings of the application package name (as
320 * returned by the package manager), and the keys are ApplicationRecord
321 * objects.
322 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700323 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800326 * The currently running isolated processes.
327 */
328 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
329
330 /**
331 * Counter for assigning isolated process uids, to avoid frequently reusing the
332 * same ones.
333 */
334 int mNextIsolatedProcessUid = 0;
335
336 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700337 * The currently running heavy-weight process, if any.
338 */
339 ProcessRecord mHeavyWeightProcess = null;
340
341 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 * The last time that various processes have crashed.
343 */
344 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
345
346 /**
347 * Set of applications that we consider to be bad, and will reject
348 * incoming broadcasts from (which the user has no control over).
349 * Processes are added to this set when they have crashed twice within
350 * a minimum amount of time; they are removed from it when they are
351 * later restarted (hopefully due to some user action). The value is the
352 * time it was added to the list.
353 */
354 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
355
356 /**
357 * All of the processes we currently have running organized by pid.
358 * The keys are the pid running the application.
359 *
360 * <p>NOTE: This object is protected by its own lock, NOT the global
361 * activity manager lock!
362 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 /**
366 * All of the processes that have been forced to be foreground. The key
367 * is the pid of the caller who requested it (we hold a death
368 * link on it).
369 */
370 abstract class ForegroundToken implements IBinder.DeathRecipient {
371 int pid;
372 IBinder token;
373 }
374 final SparseArray<ForegroundToken> mForegroundProcesses
375 = new SparseArray<ForegroundToken>();
376
377 /**
378 * List of records for processes that someone had tried to start before the
379 * system was ready. We don't start them at that point, but ensure they
380 * are started by the time booting is complete.
381 */
382 final ArrayList<ProcessRecord> mProcessesOnHold
383 = new ArrayList<ProcessRecord>();
384
385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * List of persistent applications that are in the process
387 * of being started.
388 */
389 final ArrayList<ProcessRecord> mPersistentStartingProcesses
390 = new ArrayList<ProcessRecord>();
391
392 /**
393 * Processes that are being forcibly torn down.
394 */
395 final ArrayList<ProcessRecord> mRemovedProcesses
396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * List of running applications, sorted by recent usage.
400 * The first entry in the list is the least recently used.
401 * It contains ApplicationRecord objects. This list does NOT include
402 * any persistent application records (since we never want to exit them).
403 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800404 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 = new ArrayList<ProcessRecord>();
406
407 /**
408 * List of processes that should gc as soon as things are idle.
409 */
410 final ArrayList<ProcessRecord> mProcessesToGc
411 = new ArrayList<ProcessRecord>();
412
413 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800414 * This is the process holding what we currently consider to be
415 * the "home" activity.
416 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800418
419 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700420 * This is the process holding the activity the user last visited that
421 * is in a different process from the one they are currently in.
422 */
423 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800424
425 /**
426 * The time at which the previous process was last visible.
427 */
428 long mPreviousProcessVisibleTime;
429
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700430 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700431 * Which uses have been started, so are allowed to run code.
432 */
433 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
434
435 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700436 * LRU list of history of current users. Most recently current is at the end.
437 */
438 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
439
440 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400441 * Packages that the user has asked to have run in screen size
442 * compatibility mode instead of filling the screen.
443 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700444 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400445
446 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 * Set of PendingResultRecord objects that are currently active.
448 */
449 final HashSet mPendingResultRecords = new HashSet();
450
451 /**
452 * Set of IntentSenderRecord objects that are currently active.
453 */
454 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
455 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
456
457 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800458 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700459 * already logged DropBox entries for. Guarded by itself. If
460 * something (rogue user app) forces this over
461 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
462 */
463 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
464 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
465
466 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700467 * Strict Mode background batched logging state.
468 *
469 * The string buffer is guarded by itself, and its lock is also
470 * used to determine if another batched write is already
471 * in-flight.
472 */
473 private final StringBuilder mStrictModeBuffer = new StringBuilder();
474
475 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 * Keeps track of all IIntentReceivers that have been registered for
477 * broadcasts. Hash keys are the receiver IBinder, hash value is
478 * a ReceiverList.
479 */
480 final HashMap mRegisteredReceivers = new HashMap();
481
482 /**
483 * Resolver for broadcast intents to registered receivers.
484 * Holds BroadcastFilter (subclass of IntentFilter).
485 */
486 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
487 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
488 @Override
489 protected boolean allowFilterResult(
490 BroadcastFilter filter, List<BroadcastFilter> dest) {
491 IBinder target = filter.receiverList.receiver.asBinder();
492 for (int i=dest.size()-1; i>=0; i--) {
493 if (dest.get(i).receiverList.receiver.asBinder() == target) {
494 return false;
495 }
496 }
497 return true;
498 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700499
500 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700501 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700502 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
503 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700504 return super.newResult(filter, match, userId);
505 }
506 return null;
507 }
508
509 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700510 protected BroadcastFilter[] newArray(int size) {
511 return new BroadcastFilter[size];
512 }
513
514 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700515 protected String packageForFilter(BroadcastFilter filter) {
516 return filter.packageName;
517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 };
519
520 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700521 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700523 * that action (which should usually be one). The SparseArray is keyed
524 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
525 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700527 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
528 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700530 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531
532 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700533 * Backup/restore process management
534 */
535 String mBackupAppName = null;
536 BackupRecord mBackupTarget = null;
537
538 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 * List of PendingThumbnailsRecord objects of clients who are still
540 * waiting to receive all of the thumbnails for a task.
541 */
542 final ArrayList mPendingThumbnails = new ArrayList();
543
544 /**
545 * List of HistoryRecord objects that have been finished and must
546 * still report back to a pending thumbnail receiver.
547 */
548 final ArrayList mCancelledThumbnails = new ArrayList();
549
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700550 final ProviderMap mProviderMap;
Amith Yamasani742a6712011-05-04 14:49:28 -0700551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
553 * List of content providers who have clients waiting for them. The
554 * application is currently being launched and the provider will be
555 * removed from this list once it is published.
556 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700557 final ArrayList<ContentProviderRecord> mLaunchingProviders
558 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559
560 /**
561 * Global set of specific Uri permissions that have been granted.
562 */
563 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
564 = new SparseArray<HashMap<Uri, UriPermission>>();
565
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800566 CoreSettingsObserver mCoreSettingsObserver;
567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 /**
569 * Thread-local storage used to carry caller permissions over through
570 * indirect content-provider access.
571 * @see #ActivityManagerService.openContentUri()
572 */
573 private class Identity {
574 public int pid;
575 public int uid;
576
577 Identity(int _pid, int _uid) {
578 pid = _pid;
579 uid = _uid;
580 }
581 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
584
585 /**
586 * All information we have collected about the runtime performance of
587 * any user id that can impact battery performance.
588 */
589 final BatteryStatsService mBatteryStatsService;
590
591 /**
592 * information about component usage
593 */
594 final UsageStatsService mUsageStatsService;
595
596 /**
597 * Current configuration information. HistoryRecord objects are given
598 * a reference to this object to indicate which configuration they are
599 * currently running in, so this object must be kept immutable.
600 */
601 Configuration mConfiguration = new Configuration();
602
603 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800604 * Current sequencing integer of the configuration, for skipping old
605 * configurations.
606 */
607 int mConfigurationSeq = 0;
608
609 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700610 * Hardware-reported OpenGLES version.
611 */
612 final int GL_ES_VERSION;
613
614 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 * List of initialization arguments to pass to all processes when binding applications to them.
616 * For example, references to the commonly used services.
617 */
618 HashMap<String, IBinder> mAppBindArgs;
619
620 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700621 * Temporary to avoid allocations. Protected by main lock.
622 */
623 final StringBuilder mStringBuilder = new StringBuilder(256);
624
625 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 * Used to control how we initialize the service.
627 */
628 boolean mStartRunning = false;
629 ComponentName mTopComponent;
630 String mTopAction;
631 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700632 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 boolean mSystemReady = false;
634 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700635 boolean mWaitingUpdate = false;
636 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700637 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700638 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639
640 Context mContext;
641
642 int mFactoryTest;
643
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700644 boolean mCheckedForSetup;
645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700647 * The time at which we will allow normal application switches again,
648 * after a call to {@link #stopAppSwitches()}.
649 */
650 long mAppSwitchesAllowedTime;
651
652 /**
653 * This is set to true after the first switch after mAppSwitchesAllowedTime
654 * is set; any switches after that will clear the time.
655 */
656 boolean mDidAppSwitch;
657
658 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700659 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700660 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700661 long mLastPowerCheckRealtime;
662
663 /**
664 * Last time (in uptime) at which we checked for power usage.
665 */
666 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700667
668 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669 * Set while we are wanting to sleep, to prevent any
670 * activities from being started/resumed.
671 */
672 boolean mSleeping = false;
673
674 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700675 * State of external calls telling us if the device is asleep.
676 */
677 boolean mWentToSleep = false;
678
679 /**
680 * State of external call telling us if the lock screen is shown.
681 */
682 boolean mLockScreenShown = false;
683
684 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700685 * Set if we are shutting down the system, similar to sleeping.
686 */
687 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688
689 /**
690 * Task identifier that activities are currently being started
691 * in. Incremented each time a new task is created.
692 * todo: Replace this with a TokenSpace class that generates non-repeating
693 * integers that won't wrap.
694 */
695 int mCurTask = 1;
696
697 /**
698 * Current sequence id for oom_adj computation traversal.
699 */
700 int mAdjSeq = 0;
701
702 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700703 * Current sequence id for process LRU updating.
704 */
705 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706
707 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700708 * Keep track of the non-hidden/empty process we last found, to help
709 * determine how to distribute hidden/empty processes next time.
710 */
711 int mNumNonHiddenProcs = 0;
712
713 /**
714 * Keep track of the number of hidden procs, to balance oom adj
715 * distribution between those and empty procs.
716 */
717 int mNumHiddenProcs = 0;
718
719 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700720 * Keep track of the number of service processes we last found, to
721 * determine on the next iteration which should be B services.
722 */
723 int mNumServiceProcs = 0;
724 int mNewNumServiceProcs = 0;
725
726 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 * System monitoring: number of processes that died since the last
728 * N procs were started.
729 */
730 int[] mProcDeaths = new int[20];
731
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700732 /**
733 * This is set if we had to do a delayed dexopt of an app before launching
734 * it, to increasing the ANR timeouts in that case.
735 */
736 boolean mDidDexOpt;
737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 String mDebugApp = null;
739 boolean mWaitForDebugger = false;
740 boolean mDebugTransient = false;
741 String mOrigDebugApp = null;
742 boolean mOrigWaitForDebugger = false;
743 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700744 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700745 String mProfileApp = null;
746 ProcessRecord mProfileProc = null;
747 String mProfileFile;
748 ParcelFileDescriptor mProfileFd;
749 int mProfileType = 0;
750 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800751 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700753 static class ProcessChangeItem {
754 static final int CHANGE_ACTIVITIES = 1<<0;
755 static final int CHANGE_IMPORTANCE= 1<<1;
756 int changes;
757 int uid;
758 int pid;
759 int importance;
760 boolean foregroundActivities;
761 }
762
Jeff Sharkeya4620792011-05-20 15:29:23 -0700763 final RemoteCallbackList<IProcessObserver> mProcessObservers
764 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700765 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
766
767 final ArrayList<ProcessChangeItem> mPendingProcessChanges
768 = new ArrayList<ProcessChangeItem>();
769 final ArrayList<ProcessChangeItem> mAvailProcessChanges
770 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772 /**
773 * Callback of last caller to {@link #requestPss}.
774 */
775 Runnable mRequestPssCallback;
776
777 /**
778 * Remaining processes for which we are waiting results from the last
779 * call to {@link #requestPss}.
780 */
781 final ArrayList<ProcessRecord> mRequestPssList
782 = new ArrayList<ProcessRecord>();
783
784 /**
785 * Runtime statistics collection thread. This object's lock is used to
786 * protect all related state.
787 */
788 final Thread mProcessStatsThread;
789
790 /**
791 * Used to collect process stats when showing not responding dialog.
792 * Protected by mProcessStatsThread.
793 */
794 final ProcessStats mProcessStats = new ProcessStats(
795 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700796 final AtomicLong mLastCpuTime = new AtomicLong(0);
797 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 long mLastWriteTime = 0;
800
801 /**
802 * Set to true after the system has finished booting.
803 */
804 boolean mBooted = false;
805
Dianne Hackborn7d608422011-08-07 16:24:18 -0700806 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700807 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808
809 WindowManagerService mWindowManager;
810
811 static ActivityManagerService mSelf;
812 static ActivityThread mSystemThread;
813
Amith Yamasani258848d2012-08-10 17:06:33 -0700814 private int mCurrentUserId;
Dianne Hackborn1676c852012-09-10 14:52:30 -0700815 private UserManagerService mUserManager;
Amith Yamasani258848d2012-08-10 17:06:33 -0700816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 private final class AppDeathRecipient implements IBinder.DeathRecipient {
818 final ProcessRecord mApp;
819 final int mPid;
820 final IApplicationThread mAppThread;
821
822 AppDeathRecipient(ProcessRecord app, int pid,
823 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800824 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 TAG, "New death recipient " + this
826 + " for thread " + thread.asBinder());
827 mApp = app;
828 mPid = pid;
829 mAppThread = thread;
830 }
831
832 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800833 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 TAG, "Death received in " + this
835 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 synchronized(ActivityManagerService.this) {
837 appDiedLocked(mApp, mPid, mAppThread);
838 }
839 }
840 }
841
842 static final int SHOW_ERROR_MSG = 1;
843 static final int SHOW_NOT_RESPONDING_MSG = 2;
844 static final int SHOW_FACTORY_ERROR_MSG = 3;
845 static final int UPDATE_CONFIGURATION_MSG = 4;
846 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
847 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 static final int SERVICE_TIMEOUT_MSG = 12;
849 static final int UPDATE_TIME_ZONE = 13;
850 static final int SHOW_UID_ERROR_MSG = 14;
851 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700853 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700854 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800855 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700856 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
857 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700858 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700859 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700860 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700861 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700862 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700863 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700864 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700865 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800867 static final int FIRST_ACTIVITY_STACK_MSG = 100;
868 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
869 static final int FIRST_COMPAT_MODE_MSG = 300;
870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700872 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700873 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874
875 final Handler mHandler = new Handler() {
876 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 //}
879
880 public void handleMessage(Message msg) {
881 switch (msg.what) {
882 case SHOW_ERROR_MSG: {
883 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800884 synchronized (ActivityManagerService.this) {
885 ProcessRecord proc = (ProcessRecord)data.get("app");
886 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800887 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 return;
889 }
890 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700891 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800892 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 d.show();
894 proc.crashDialog = d;
895 } else {
896 // The device is asleep, so just pretend that the user
897 // saw a crash dialog and hit "force quit".
898 res.set(0);
899 }
900 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700901
902 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 } break;
904 case SHOW_NOT_RESPONDING_MSG: {
905 synchronized (ActivityManagerService.this) {
906 HashMap data = (HashMap) msg.obj;
907 ProcessRecord proc = (ProcessRecord)data.get("app");
908 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800909 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 return;
911 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800912
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700913 Intent intent = new Intent("android.intent.action.ANR");
914 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800915 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
916 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700917 }
918 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800919 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700920 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800921
Justin Kohbc52ca22012-03-29 15:11:44 -0700922 if (mShowDialogs) {
923 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700924 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700925 d.show();
926 proc.anrDialog = d;
927 } else {
928 // Just kill the app if there is no dialog to be shown.
929 killAppAtUsersRequest(proc, null);
930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700932
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700933 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700935 case SHOW_STRICT_MODE_VIOLATION_MSG: {
936 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
937 synchronized (ActivityManagerService.this) {
938 ProcessRecord proc = (ProcessRecord) data.get("app");
939 if (proc == null) {
940 Slog.e(TAG, "App not found when showing strict mode dialog.");
941 break;
942 }
943 if (proc.crashDialog != null) {
944 Slog.e(TAG, "App already has strict mode dialog: " + proc);
945 return;
946 }
947 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700948 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700949 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
950 d.show();
951 proc.crashDialog = d;
952 } else {
953 // The device is asleep, so just pretend that the user
954 // saw a crash dialog and hit "force quit".
955 res.set(0);
956 }
957 }
958 ensureBootCompleted();
959 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 case SHOW_FACTORY_ERROR_MSG: {
961 Dialog d = new FactoryErrorDialog(
962 mContext, msg.getData().getCharSequence("msg"));
963 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700964 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 } break;
966 case UPDATE_CONFIGURATION_MSG: {
967 final ContentResolver resolver = mContext.getContentResolver();
968 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
969 } break;
970 case GC_BACKGROUND_PROCESSES_MSG: {
971 synchronized (ActivityManagerService.this) {
972 performAppGcsIfAppropriateLocked();
973 }
974 } break;
975 case WAIT_FOR_DEBUGGER_MSG: {
976 synchronized (ActivityManagerService.this) {
977 ProcessRecord app = (ProcessRecord)msg.obj;
978 if (msg.arg1 != 0) {
979 if (!app.waitedForDebugger) {
980 Dialog d = new AppWaitingForDebuggerDialog(
981 ActivityManagerService.this,
982 mContext, app);
983 app.waitDialog = d;
984 app.waitedForDebugger = true;
985 d.show();
986 }
987 } else {
988 if (app.waitDialog != null) {
989 app.waitDialog.dismiss();
990 app.waitDialog = null;
991 }
992 }
993 }
994 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700996 if (mDidDexOpt) {
997 mDidDexOpt = false;
998 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
999 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001000 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001001 return;
1002 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001003 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 } break;
1005 case UPDATE_TIME_ZONE: {
1006 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001007 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1008 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 if (r.thread != null) {
1010 try {
1011 r.thread.updateTimeZone();
1012 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001013 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 }
1015 }
1016 }
1017 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001018 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001019 case CLEAR_DNS_CACHE: {
1020 synchronized (ActivityManagerService.this) {
1021 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1022 ProcessRecord r = mLruProcesses.get(i);
1023 if (r.thread != null) {
1024 try {
1025 r.thread.clearDnsCache();
1026 } catch (RemoteException ex) {
1027 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1028 }
1029 }
1030 }
1031 }
1032 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001033 case UPDATE_HTTP_PROXY: {
1034 ProxyProperties proxy = (ProxyProperties)msg.obj;
1035 String host = "";
1036 String port = "";
1037 String exclList = "";
1038 if (proxy != null) {
1039 host = proxy.getHost();
1040 port = Integer.toString(proxy.getPort());
1041 exclList = proxy.getExclusionList();
1042 }
1043 synchronized (ActivityManagerService.this) {
1044 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1045 ProcessRecord r = mLruProcesses.get(i);
1046 if (r.thread != null) {
1047 try {
1048 r.thread.setHttpProxy(host, port, exclList);
1049 } catch (RemoteException ex) {
1050 Slog.w(TAG, "Failed to update http proxy for: " +
1051 r.info.processName);
1052 }
1053 }
1054 }
1055 }
1056 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001058 String title = "System UIDs Inconsistent";
1059 String text = "UIDs on the system are inconsistent, you need to wipe your"
1060 + " data partition or your device will be unstable.";
1061 Log.e(TAG, title + ": " + text);
1062 if (mShowDialogs) {
1063 // XXX This is a temporary dialog, no need to localize.
1064 AlertDialog d = new BaseErrorDialog(mContext);
1065 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1066 d.setCancelable(false);
1067 d.setTitle(title);
1068 d.setMessage(text);
1069 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1070 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1071 mUidAlert = d;
1072 d.show();
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } break;
1075 case IM_FEELING_LUCKY_MSG: {
1076 if (mUidAlert != null) {
1077 mUidAlert.dismiss();
1078 mUidAlert = null;
1079 }
1080 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001082 if (mDidDexOpt) {
1083 mDidDexOpt = false;
1084 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1085 nmsg.obj = msg.obj;
1086 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1087 return;
1088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 ProcessRecord app = (ProcessRecord)msg.obj;
1090 synchronized (ActivityManagerService.this) {
1091 processStartTimedOutLocked(app);
1092 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001093 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001094 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1095 synchronized (ActivityManagerService.this) {
1096 doPendingActivityLaunchesLocked(true);
1097 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001098 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001099 case KILL_APPLICATION_MSG: {
1100 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001101 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001102 boolean restart = (msg.arg2 == 1);
1103 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001104 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1105 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001106 }
1107 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001108 case FINALIZE_PENDING_INTENT_MSG: {
1109 ((PendingIntentRecord)msg.obj).completeFinalize();
1110 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001111 case POST_HEAVY_NOTIFICATION_MSG: {
1112 INotificationManager inm = NotificationManager.getService();
1113 if (inm == null) {
1114 return;
1115 }
1116
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001117 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001118 ProcessRecord process = root.app;
1119 if (process == null) {
1120 return;
1121 }
1122
1123 try {
1124 Context context = mContext.createPackageContext(process.info.packageName, 0);
1125 String text = mContext.getString(R.string.heavy_weight_notification,
1126 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1127 Notification notification = new Notification();
1128 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1129 notification.when = 0;
1130 notification.flags = Notification.FLAG_ONGOING_EVENT;
1131 notification.tickerText = text;
1132 notification.defaults = 0; // please be quiet
1133 notification.sound = null;
1134 notification.vibrate = null;
1135 notification.setLatestEventInfo(context, text,
1136 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001137 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1138 PendingIntent.FLAG_CANCEL_CURRENT, null,
1139 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001140
1141 try {
1142 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001143 inm.enqueueNotificationWithTag("android", null,
1144 R.string.heavy_weight_notification,
1145 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001146 } catch (RuntimeException e) {
1147 Slog.w(ActivityManagerService.TAG,
1148 "Error showing notification for heavy-weight app", e);
1149 } catch (RemoteException e) {
1150 }
1151 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001152 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001153 }
1154 } break;
1155 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1156 INotificationManager inm = NotificationManager.getService();
1157 if (inm == null) {
1158 return;
1159 }
1160 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001161 inm.cancelNotificationWithTag("android", null,
1162 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001163 } catch (RuntimeException e) {
1164 Slog.w(ActivityManagerService.TAG,
1165 "Error canceling notification for service", e);
1166 } catch (RemoteException e) {
1167 }
1168 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001169 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1170 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001171 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001172 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001173 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1174 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001175 }
1176 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001177 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1178 synchronized (ActivityManagerService.this) {
1179 ActivityRecord ar = (ActivityRecord)msg.obj;
1180 if (mCompatModeDialog != null) {
1181 if (mCompatModeDialog.mAppInfo.packageName.equals(
1182 ar.info.applicationInfo.packageName)) {
1183 return;
1184 }
1185 mCompatModeDialog.dismiss();
1186 mCompatModeDialog = null;
1187 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001188 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001189 if (mCompatModePackages.getPackageAskCompatModeLocked(
1190 ar.packageName)) {
1191 int mode = mCompatModePackages.computeCompatModeLocked(
1192 ar.info.applicationInfo);
1193 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1194 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1195 mCompatModeDialog = new CompatModeDialog(
1196 ActivityManagerService.this, mContext,
1197 ar.info.applicationInfo);
1198 mCompatModeDialog.show();
1199 }
1200 }
1201 }
1202 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001203 break;
1204 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001205 case DISPATCH_PROCESSES_CHANGED: {
1206 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001207 break;
1208 }
1209 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001210 final int pid = msg.arg1;
1211 final int uid = msg.arg2;
1212 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001213 break;
1214 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001215 case REPORT_MEM_USAGE: {
1216 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1217 if (!isDebuggable) {
1218 return;
1219 }
1220 synchronized (ActivityManagerService.this) {
1221 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001222 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1223 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001224 // avoid spamming.
1225 return;
1226 }
1227 mLastMemUsageReportTime = now;
1228 }
1229 Thread thread = new Thread() {
1230 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001231 StringBuilder dropBuilder = new StringBuilder(1024);
1232 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001233 StringWriter oomSw = new StringWriter();
1234 PrintWriter oomPw = new PrintWriter(oomSw);
1235 StringWriter catSw = new StringWriter();
1236 PrintWriter catPw = new PrintWriter(catSw);
1237 String[] emptyArgs = new String[] { };
1238 StringBuilder tag = new StringBuilder(128);
1239 StringBuilder stack = new StringBuilder(128);
1240 tag.append("Low on memory -- ");
1241 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1242 tag, stack);
1243 dropBuilder.append(stack);
1244 dropBuilder.append('\n');
1245 dropBuilder.append('\n');
1246 String oomString = oomSw.toString();
1247 dropBuilder.append(oomString);
1248 dropBuilder.append('\n');
1249 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001250 try {
1251 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1252 "procrank", });
1253 final InputStreamReader converter = new InputStreamReader(
1254 proc.getInputStream());
1255 BufferedReader in = new BufferedReader(converter);
1256 String line;
1257 while (true) {
1258 line = in.readLine();
1259 if (line == null) {
1260 break;
1261 }
1262 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001263 logBuilder.append(line);
1264 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001265 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001266 dropBuilder.append(line);
1267 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001268 }
1269 converter.close();
1270 } catch (IOException e) {
1271 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001272 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001273 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001274 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001275 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001276 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1277 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001278 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001279 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001280 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001281 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001282 addErrorToDropBox("lowmem", null, "system_server", null,
1283 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001284 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001285 synchronized (ActivityManagerService.this) {
1286 long now = SystemClock.uptimeMillis();
1287 if (mLastMemUsageReportTime < now) {
1288 mLastMemUsageReportTime = now;
1289 }
1290 }
1291 }
1292 };
1293 thread.start();
1294 break;
1295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
1297 }
1298 };
1299
1300 public static void setSystemProcess() {
1301 try {
1302 ActivityManagerService m = mSelf;
1303
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001304 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001306 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001307 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (MONITOR_CPU_USAGE) {
1309 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 ServiceManager.addService("permission", new PermissionController(m));
1312
1313 ApplicationInfo info =
1314 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001315 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001316 mSystemThread.installSystemApplicationInfo(info);
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 synchronized (mSelf) {
1319 ProcessRecord app = mSelf.newProcessRecordLocked(
1320 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001321 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001323 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001324 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001325 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 synchronized (mSelf.mPidsSelfLocked) {
1327 mSelf.mPidsSelfLocked.put(app.pid, app);
1328 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001329 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 }
1331 } catch (PackageManager.NameNotFoundException e) {
1332 throw new RuntimeException(
1333 "Unable to find android system package", e);
1334 }
1335 }
1336
1337 public void setWindowManager(WindowManagerService wm) {
1338 mWindowManager = wm;
1339 }
1340
1341 public static final Context main(int factoryTest) {
1342 AThread thr = new AThread();
1343 thr.start();
1344
1345 synchronized (thr) {
1346 while (thr.mService == null) {
1347 try {
1348 thr.wait();
1349 } catch (InterruptedException e) {
1350 }
1351 }
1352 }
1353
1354 ActivityManagerService m = thr.mService;
1355 mSelf = m;
1356 ActivityThread at = ActivityThread.systemMain();
1357 mSystemThread = at;
1358 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001359 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 m.mContext = context;
1361 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001362 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363
1364 m.mBatteryStatsService.publish(context);
1365 m.mUsageStatsService.publish(context);
1366
1367 synchronized (thr) {
1368 thr.mReady = true;
1369 thr.notifyAll();
1370 }
1371
1372 m.startRunning(null, null, null, null);
1373
1374 return context;
1375 }
1376
1377 public static ActivityManagerService self() {
1378 return mSelf;
1379 }
1380
1381 static class AThread extends Thread {
1382 ActivityManagerService mService;
1383 boolean mReady = false;
1384
1385 public AThread() {
1386 super("ActivityManager");
1387 }
1388
1389 public void run() {
1390 Looper.prepare();
1391
1392 android.os.Process.setThreadPriority(
1393 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001394 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395
1396 ActivityManagerService m = new ActivityManagerService();
1397
1398 synchronized (this) {
1399 mService = m;
1400 notifyAll();
1401 }
1402
1403 synchronized (this) {
1404 while (!mReady) {
1405 try {
1406 wait();
1407 } catch (InterruptedException e) {
1408 }
1409 }
1410 }
1411
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001412 // For debug builds, log event loop stalls to dropbox for analysis.
1413 if (StrictMode.conditionallyEnableDebugLogging()) {
1414 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 Looper.loop();
1418 }
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 static class MemBinder extends Binder {
1422 ActivityManagerService mActivityManagerService;
1423 MemBinder(ActivityManagerService activityManagerService) {
1424 mActivityManagerService = activityManagerService;
1425 }
1426
1427 @Override
1428 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001429 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1430 != PackageManager.PERMISSION_GRANTED) {
1431 pw.println("Permission Denial: can't dump meminfo from from pid="
1432 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1433 + " without permission " + android.Manifest.permission.DUMP);
1434 return;
1435 }
1436
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001437 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001438 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 }
1441
Chet Haase9c1e23b2011-03-24 10:51:31 -07001442 static class GraphicsBinder extends Binder {
1443 ActivityManagerService mActivityManagerService;
1444 GraphicsBinder(ActivityManagerService activityManagerService) {
1445 mActivityManagerService = activityManagerService;
1446 }
1447
1448 @Override
1449 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001450 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1451 != PackageManager.PERMISSION_GRANTED) {
1452 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1453 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1454 + " without permission " + android.Manifest.permission.DUMP);
1455 return;
1456 }
1457
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001458 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001459 }
1460 }
1461
Jeff Brown6754ba22011-12-14 20:20:01 -08001462 static class DbBinder extends Binder {
1463 ActivityManagerService mActivityManagerService;
1464 DbBinder(ActivityManagerService activityManagerService) {
1465 mActivityManagerService = activityManagerService;
1466 }
1467
1468 @Override
1469 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1470 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1471 != PackageManager.PERMISSION_GRANTED) {
1472 pw.println("Permission Denial: can't dump dbinfo from from pid="
1473 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1474 + " without permission " + android.Manifest.permission.DUMP);
1475 return;
1476 }
1477
1478 mActivityManagerService.dumpDbInfo(fd, pw, args);
1479 }
1480 }
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 static class CpuBinder extends Binder {
1483 ActivityManagerService mActivityManagerService;
1484 CpuBinder(ActivityManagerService activityManagerService) {
1485 mActivityManagerService = activityManagerService;
1486 }
1487
1488 @Override
1489 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001490 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1491 != PackageManager.PERMISSION_GRANTED) {
1492 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1493 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1494 + " without permission " + android.Manifest.permission.DUMP);
1495 return;
1496 }
1497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001499 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1500 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1501 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503 }
1504 }
1505
1506 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001508
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001509 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1510 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1511 mBroadcastQueues[0] = mFgBroadcastQueue;
1512 mBroadcastQueues[1] = mBgBroadcastQueue;
1513
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001514 mServices = new ActiveServices(this);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001515 mProviderMap = new ProviderMap(this);
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 File dataDir = Environment.getDataDirectory();
1518 File systemDir = new File(dataDir, "system");
1519 systemDir.mkdirs();
1520 mBatteryStatsService = new BatteryStatsService(new File(
1521 systemDir, "batterystats.bin").toString());
1522 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001523 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001524 mOnBattery = DEBUG_POWER ? true
1525 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001526 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001528 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001529 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001530 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001532 // User 0 is the first and only user that runs at boot.
1533 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001534 mUserLru.add(Integer.valueOf(0));
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001535
Jack Palevichb90d28c2009-07-22 15:35:24 -07001536 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1537 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1538
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001539 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001540 mConfiguration.setLocale(Locale.getDefault());
1541
Dianne Hackborn813075a62011-11-14 17:45:19 -08001542 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 mProcessStats.init();
1544
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001545 mCompatModePackages = new CompatModePackages(this, systemDir);
1546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 // Add ourself to the Watchdog monitors.
1548 Watchdog.getInstance().addMonitor(this);
1549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 mProcessStatsThread = new Thread("ProcessStats") {
1551 public void run() {
1552 while (true) {
1553 try {
1554 try {
1555 synchronized(this) {
1556 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001557 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001559 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 // + ", write delay=" + nextWriteDelay);
1561 if (nextWriteDelay < nextCpuDelay) {
1562 nextCpuDelay = nextWriteDelay;
1563 }
1564 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001565 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 this.wait(nextCpuDelay);
1567 }
1568 }
1569 } catch (InterruptedException e) {
1570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 updateCpuStatsNow();
1572 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001573 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 }
1575 }
1576 }
1577 };
1578 mProcessStatsThread.start();
1579 }
1580
1581 @Override
1582 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1583 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001584 if (code == SYSPROPS_TRANSACTION) {
1585 // We need to tell all apps about the system property change.
1586 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1587 synchronized(this) {
1588 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1589 final int NA = apps.size();
1590 for (int ia=0; ia<NA; ia++) {
1591 ProcessRecord app = apps.valueAt(ia);
1592 if (app.thread != null) {
1593 procs.add(app.thread.asBinder());
1594 }
1595 }
1596 }
1597 }
1598
1599 int N = procs.size();
1600 for (int i=0; i<N; i++) {
1601 Parcel data2 = Parcel.obtain();
1602 try {
1603 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1604 } catch (RemoteException e) {
1605 }
1606 data2.recycle();
1607 }
1608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 try {
1610 return super.onTransact(code, data, reply, flags);
1611 } catch (RuntimeException e) {
1612 // The activity manager only throws security exceptions, so let's
1613 // log all others.
1614 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001615 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 }
1617 throw e;
1618 }
1619 }
1620
1621 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001622 final long now = SystemClock.uptimeMillis();
1623 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1624 return;
1625 }
1626 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1627 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 mProcessStatsThread.notify();
1629 }
1630 }
1631 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 void updateCpuStatsNow() {
1634 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001635 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 final long now = SystemClock.uptimeMillis();
1637 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001640 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1641 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 haveNewCpuStats = true;
1643 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001644 //Slog.i(TAG, mProcessStats.printCurrentState());
1645 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 // + mProcessStats.getTotalCpuPercent() + "%");
1647
Joe Onorato8a9b2202010-02-26 18:56:32 -08001648 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 if ("true".equals(SystemProperties.get("events.cpu"))) {
1650 int user = mProcessStats.getLastUserTime();
1651 int system = mProcessStats.getLastSystemTime();
1652 int iowait = mProcessStats.getLastIoWaitTime();
1653 int irq = mProcessStats.getLastIrqTime();
1654 int softIrq = mProcessStats.getLastSoftIrqTime();
1655 int idle = mProcessStats.getLastIdleTime();
1656
1657 int total = user + system + iowait + irq + softIrq + idle;
1658 if (total == 0) total = 1;
1659
Doug Zongker2bec3d42009-12-04 12:52:44 -08001660 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 ((user+system+iowait+irq+softIrq) * 100) / total,
1662 (user * 100) / total,
1663 (system * 100) / total,
1664 (iowait * 100) / total,
1665 (irq * 100) / total,
1666 (softIrq * 100) / total);
1667 }
1668 }
1669
Amith Yamasanie43530a2009-08-21 13:11:37 -07001670 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001671 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 synchronized(mPidsSelfLocked) {
1674 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001675 if (mOnBattery) {
1676 int perc = bstats.startAddingCpuLocked();
1677 int totalUTime = 0;
1678 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001679 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001681 ProcessStats.Stats st = mProcessStats.getStats(i);
1682 if (!st.working) {
1683 continue;
1684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001686 int otherUTime = (st.rel_utime*perc)/100;
1687 int otherSTime = (st.rel_stime*perc)/100;
1688 totalUTime += otherUTime;
1689 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 if (pr != null) {
1691 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1693 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001694 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001695 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001696 } else {
1697 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001698 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001699 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001700 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1701 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001702 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001706 bstats.finishAddingCpuLocked(perc, totalUTime,
1707 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
1709 }
1710 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1713 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001714 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716 }
1717 }
1718 }
1719
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001720 @Override
1721 public void batteryNeedsCpuUpdate() {
1722 updateCpuStatsNow();
1723 }
1724
1725 @Override
1726 public void batteryPowerChanged(boolean onBattery) {
1727 // When plugging in, update the CPU stats first before changing
1728 // the plug state.
1729 updateCpuStatsNow();
1730 synchronized (this) {
1731 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001732 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001733 }
1734 }
1735 }
1736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 /**
1738 * Initialize the application bind args. These are passed to each
1739 * process when the bindApplication() IPC is sent to the process. They're
1740 * lazily setup to make sure the services are running when they're asked for.
1741 */
1742 private HashMap<String, IBinder> getCommonServicesLocked() {
1743 if (mAppBindArgs == null) {
1744 mAppBindArgs = new HashMap<String, IBinder>();
1745
1746 // Setup the application init args
1747 mAppBindArgs.put("package", ServiceManager.getService("package"));
1748 mAppBindArgs.put("window", ServiceManager.getService("window"));
1749 mAppBindArgs.put(Context.ALARM_SERVICE,
1750 ServiceManager.getService(Context.ALARM_SERVICE));
1751 }
1752 return mAppBindArgs;
1753 }
1754
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001755 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (mFocusedActivity != r) {
1757 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001758 if (r != null) {
1759 mWindowManager.setFocusedApp(r.appToken, true);
1760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
1762 }
1763
Dianne Hackborn906497c2010-05-10 15:57:38 -07001764 private final void updateLruProcessInternalLocked(ProcessRecord app,
1765 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 int lrui = mLruProcesses.indexOf(app);
1768 if (lrui >= 0) mLruProcesses.remove(lrui);
1769
1770 int i = mLruProcesses.size()-1;
1771 int skipTop = 0;
1772
Dianne Hackborn906497c2010-05-10 15:57:38 -07001773 app.lruSeq = mLruSeq;
1774
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001775 // compute the new weight for this process.
1776 if (updateActivityTime) {
1777 app.lastActivityTime = SystemClock.uptimeMillis();
1778 }
1779 if (app.activities.size() > 0) {
1780 // If this process has activities, we more strongly want to keep
1781 // it around.
1782 app.lruWeight = app.lastActivityTime;
1783 } else if (app.pubProviders.size() > 0) {
1784 // If this process contains content providers, we want to keep
1785 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001786 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001787 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001788 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001789 } else {
1790 // If this process doesn't have activities, we less strongly
1791 // want to keep it around, and generally want to avoid getting
1792 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001793 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001794 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001795 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001796 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001797
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001798 while (i >= 0) {
1799 ProcessRecord p = mLruProcesses.get(i);
1800 // If this app shouldn't be in front of the first N background
1801 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001802 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001803 skipTop--;
1804 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001805 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001806 mLruProcesses.add(i+1, app);
1807 break;
1808 }
1809 i--;
1810 }
1811 if (i < 0) {
1812 mLruProcesses.add(0, app);
1813 }
1814
Dianne Hackborn906497c2010-05-10 15:57:38 -07001815 // If the app is currently using a content provider or service,
1816 // bump those processes as well.
1817 if (app.connections.size() > 0) {
1818 for (ConnectionRecord cr : app.connections) {
1819 if (cr.binding != null && cr.binding.service != null
1820 && cr.binding.service.app != null
1821 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001822 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001823 updateActivityTime, i+1);
1824 }
1825 }
1826 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001827 for (int j=app.conProviders.size()-1; j>=0; j--) {
1828 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1829 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001830 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001831 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001832 }
1833 }
1834
Joe Onorato8a9b2202010-02-26 18:56:32 -08001835 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 if (oomAdj) {
1837 updateOomAdjLocked();
1838 }
1839 }
1840
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001841 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001842 boolean oomAdj, boolean updateActivityTime) {
1843 mLruSeq++;
1844 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1845 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001846
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001847 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001849 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001850 // The system gets to run in any process. If there are multiple
1851 // processes with the same uid, just pick the first (this
1852 // should never happen).
1853 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1854 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001855 if (procs == null) return null;
1856 final int N = procs.size();
1857 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001858 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 ProcessRecord proc = mProcessNames.get(processName, uid);
1862 return proc;
1863 }
1864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001865 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001866 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001867 try {
1868 if (pm.performDexOpt(packageName)) {
1869 mDidDexOpt = true;
1870 }
1871 } catch (RemoteException e) {
1872 }
1873 }
1874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001875 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 int transit = mWindowManager.getPendingAppTransition();
1877 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1878 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1879 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1880 }
1881
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001882 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001884 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1885 boolean isolated) {
1886 ProcessRecord app;
1887 if (!isolated) {
1888 app = getProcessRecordLocked(processName, info.uid);
1889 } else {
1890 // If this is an isolated process, it can't re-use an existing process.
1891 app = null;
1892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 // We don't have to do anything more if:
1894 // (1) There is an existing application record; and
1895 // (2) The caller doesn't think it is dead, OR there is no thread
1896 // object attached to it so we know it couldn't have crashed; and
1897 // (3) There is a pid assigned to it, so it is either starting or
1898 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001899 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 + " app=" + app + " knownToBeDead=" + knownToBeDead
1901 + " thread=" + (app != null ? app.thread : null)
1902 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001903 if (app != null && app.pid > 0) {
1904 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001905 // We already have the app running, or are waiting for it to
1906 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001907 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001908 // If this is a new package in the process, add the package to the list
1909 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001910 return app;
1911 } else {
1912 // An application record is attached to a previous process,
1913 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001914 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001915 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 String hostingNameStr = hostingName != null
1920 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001921
1922 if (!isolated) {
1923 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1924 // If we are in the background, then check to see if this process
1925 // is bad. If so, we will just silently fail.
1926 if (mBadProcesses.get(info.processName, info.uid) != null) {
1927 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1928 + "/" + info.processName);
1929 return null;
1930 }
1931 } else {
1932 // When the user is explicitly starting a process, then clear its
1933 // crash count so that we won't make it bad until they see at
1934 // least one crash dialog again, and make the process good again
1935 // if it had been bad.
1936 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001937 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001938 mProcessCrashTimes.remove(info.processName, info.uid);
1939 if (mBadProcesses.get(info.processName, info.uid) != null) {
1940 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1941 info.processName);
1942 mBadProcesses.remove(info.processName, info.uid);
1943 if (app != null) {
1944 app.bad = false;
1945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947 }
1948 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001951 app = newProcessRecordLocked(null, info, processName, isolated);
1952 if (app == null) {
1953 Slog.w(TAG, "Failed making new process record for "
1954 + processName + "/" + info.uid + " isolated=" + isolated);
1955 return null;
1956 }
1957 mProcessNames.put(processName, app.uid, app);
1958 if (isolated) {
1959 mIsolatedProcesses.put(app.uid, app);
1960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 } else {
1962 // If this is a new package in the process, add the package to the list
1963 app.addPackage(info.packageName);
1964 }
1965
1966 // If the system is not ready yet, then hold off on starting this
1967 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001968 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001969 && !isAllowedWhileBooting(info)
1970 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 if (!mProcessesOnHold.contains(app)) {
1972 mProcessesOnHold.add(app);
1973 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001974 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 return app;
1976 }
1977
1978 startProcessLocked(app, hostingType, hostingNameStr);
1979 return (app.pid != 0) ? app : null;
1980 }
1981
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001982 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1983 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1984 }
1985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 private final void startProcessLocked(ProcessRecord app,
1987 String hostingType, String hostingNameStr) {
1988 if (app.pid > 0 && app.pid != MY_PID) {
1989 synchronized (mPidsSelfLocked) {
1990 mPidsSelfLocked.remove(app.pid);
1991 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1992 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001993 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001996 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1997 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 mProcessesOnHold.remove(app);
1999
2000 updateCpuStats();
2001
2002 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2003 mProcDeaths[0] = 0;
2004
2005 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002006 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002009 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002010 if (!app.isolated) {
Kenny Roote091f222012-09-11 15:01:26 -07002011 int[] permGids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002012 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002013 final PackageManager pm = mContext.getPackageManager();
Kenny Roote091f222012-09-11 15:01:26 -07002014 permGids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002015
2016 if (Environment.isExternalStorageEmulated()) {
2017 if (pm.checkPermission(
2018 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2019 app.info.packageName) == PERMISSION_GRANTED) {
2020 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2021 } else {
2022 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2023 }
2024 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002025 } catch (PackageManager.NameNotFoundException e) {
2026 Slog.w(TAG, "Unable to retrieve gids", e);
2027 }
Kenny Roote091f222012-09-11 15:01:26 -07002028
2029 /*
2030 * Add shared application GID so applications can share some
2031 * resources like shared libraries
2032 */
2033 if (permGids == null) {
2034 gids = new int[1];
2035 } else {
2036 gids = new int[permGids.length + 1];
2037 System.arraycopy(permGids, 0, gids, 1, permGids.length);
2038 }
2039 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
2041 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2042 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2043 && mTopComponent != null
2044 && app.processName.equals(mTopComponent.getPackageName())) {
2045 uid = 0;
2046 }
2047 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2048 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2049 uid = 0;
2050 }
2051 }
2052 int debugFlags = 0;
2053 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2054 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002055 // Also turn on CheckJNI for debuggable apps. It's quite
2056 // awkward to turn on otherwise.
2057 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002059 // Run the app in safe mode if its manifest requests so or the
2060 // system is booted in safe mode.
2061 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2062 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002063 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002065 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2066 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2067 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002068 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2069 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 if ("1".equals(SystemProperties.get("debug.assert"))) {
2072 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2073 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002074
2075 // Start the process. It will either succeed and return a result containing
2076 // the PID of the new process, or else throw a RuntimeException.
2077 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002078 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002079 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2082 synchronized (bs) {
2083 if (bs.isOnBattery()) {
2084 app.batteryStats.incStartsLocked();
2085 }
2086 }
2087
Jeff Brown3f9dd282011-07-08 20:02:19 -07002088 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 app.processName, hostingType,
2090 hostingNameStr != null ? hostingNameStr : "");
2091
2092 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002093 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002096 StringBuilder buf = mStringBuilder;
2097 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002098 buf.append("Start proc ");
2099 buf.append(app.processName);
2100 buf.append(" for ");
2101 buf.append(hostingType);
2102 if (hostingNameStr != null) {
2103 buf.append(" ");
2104 buf.append(hostingNameStr);
2105 }
2106 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002107 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 buf.append(" uid=");
2109 buf.append(uid);
2110 buf.append(" gids={");
2111 if (gids != null) {
2112 for (int gi=0; gi<gids.length; gi++) {
2113 if (gi != 0) buf.append(", ");
2114 buf.append(gids[gi]);
2115
2116 }
2117 }
2118 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002119 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002120 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002121 app.usingWrapper = startResult.usingWrapper;
2122 app.removed = false;
2123 synchronized (mPidsSelfLocked) {
2124 this.mPidsSelfLocked.put(startResult.pid, app);
2125 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2126 msg.obj = app;
2127 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2128 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002129 }
2130 } catch (RuntimeException e) {
2131 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002132 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002133 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 }
2135 }
2136
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002137 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002138 if (resumed) {
2139 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2140 } else {
2141 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2142 }
2143 }
2144
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002145 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002146 if (mHeadless) {
2147 // Added because none of the other calls to ensureBootCompleted seem to fire
2148 // when running headless.
2149 ensureBootCompleted();
2150 return false;
2151 }
2152
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002153 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2154 && mTopAction == null) {
2155 // We are running in factory test mode, but unable to find
2156 // the factory test app, so just sit around displaying the
2157 // error message and don't try to start anything.
2158 return false;
2159 }
2160 Intent intent = new Intent(
2161 mTopAction,
2162 mTopData != null ? Uri.parse(mTopData) : null);
2163 intent.setComponent(mTopComponent);
2164 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2165 intent.addCategory(Intent.CATEGORY_HOME);
2166 }
2167 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002168 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002169 if (aInfo != null) {
2170 intent.setComponent(new ComponentName(
2171 aInfo.applicationInfo.packageName, aInfo.name));
2172 // Don't do this if the home app is currently being
2173 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002174 aInfo = new ActivityInfo(aInfo);
2175 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002176 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2177 aInfo.applicationInfo.uid);
2178 if (app == null || app.instrumentationClass == null) {
2179 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002180 mMainStack.startActivityLocked(null, intent, null, aInfo,
2181 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002182 }
2183 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002184 if (startingUser != null) {
2185 mMainStack.addStartingUserLocked(startingUser);
2186 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002187
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002188 return true;
2189 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002190
Amith Yamasani259d5e52012-08-31 15:11:01 -07002191 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2192 ActivityInfo ai = null;
2193 ComponentName comp = intent.getComponent();
2194 try {
2195 if (comp != null) {
2196 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2197 } else {
2198 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2199 intent,
2200 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2201 flags, userId);
2202
2203 if (info != null) {
2204 ai = info.activityInfo;
2205 }
2206 }
2207 } catch (RemoteException e) {
2208 // ignore
2209 }
2210
2211 return ai;
2212 }
2213
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002214 /**
2215 * Starts the "new version setup screen" if appropriate.
2216 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002217 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002218 // Only do this once per boot.
2219 if (mCheckedForSetup) {
2220 return;
2221 }
2222
2223 // We will show this screen if the current one is a different
2224 // version than the last one shown, and we are not running in
2225 // low-level factory test mode.
2226 final ContentResolver resolver = mContext.getContentResolver();
2227 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2228 Settings.Secure.getInt(resolver,
2229 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2230 mCheckedForSetup = true;
2231
2232 // See if we should be showing the platform update setup UI.
2233 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2234 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2235 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2236
2237 // We don't allow third party apps to replace this.
2238 ResolveInfo ri = null;
2239 for (int i=0; ris != null && i<ris.size(); i++) {
2240 if ((ris.get(i).activityInfo.applicationInfo.flags
2241 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2242 ri = ris.get(i);
2243 break;
2244 }
2245 }
2246
2247 if (ri != null) {
2248 String vers = ri.activityInfo.metaData != null
2249 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2250 : null;
2251 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2252 vers = ri.activityInfo.applicationInfo.metaData.getString(
2253 Intent.METADATA_SETUP_VERSION);
2254 }
2255 String lastVers = Settings.Secure.getString(
2256 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2257 if (vers != null && !vers.equals(lastVers)) {
2258 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2259 intent.setComponent(new ComponentName(
2260 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002261 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2262 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002263 }
2264 }
2265 }
2266 }
2267
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002268 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002269 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002270 }
2271
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002272 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002273 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002274 throw new SecurityException("Isolated process not allowed to call " + caller);
2275 }
2276 }
2277
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002278 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002279 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002280 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002281 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2282 }
2283 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002284
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002285 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002286 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2287 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002288 synchronized (this) {
2289 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2290 }
2291 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002292
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002293 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002294 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002295 synchronized (this) {
2296 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2297 }
2298 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002299
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002300 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002301 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2302 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002303 synchronized (this) {
2304 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002305 }
2306 }
2307
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002308 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002309 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002310 synchronized (this) {
2311 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2312 }
2313 }
2314
2315 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002316 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2317 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002318 synchronized (this) {
2319 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2320 }
2321 }
2322
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002323 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002324 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002325 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002328 private void dispatchProcessesChanged() {
2329 int N;
2330 synchronized (this) {
2331 N = mPendingProcessChanges.size();
2332 if (mActiveProcessChanges.length < N) {
2333 mActiveProcessChanges = new ProcessChangeItem[N];
2334 }
2335 mPendingProcessChanges.toArray(mActiveProcessChanges);
2336 mAvailProcessChanges.addAll(mPendingProcessChanges);
2337 mPendingProcessChanges.clear();
2338 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2339 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002340 int i = mProcessObservers.beginBroadcast();
2341 while (i > 0) {
2342 i--;
2343 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2344 if (observer != null) {
2345 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002346 for (int j=0; j<N; j++) {
2347 ProcessChangeItem item = mActiveProcessChanges[j];
2348 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2349 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2350 + item.pid + " uid=" + item.uid + ": "
2351 + item.foregroundActivities);
2352 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2353 item.foregroundActivities);
2354 }
2355 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2356 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2357 + item.pid + " uid=" + item.uid + ": " + item.importance);
2358 observer.onImportanceChanged(item.pid, item.uid,
2359 item.importance);
2360 }
2361 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002362 } catch (RemoteException e) {
2363 }
2364 }
2365 }
2366 mProcessObservers.finishBroadcast();
2367 }
2368
2369 private void dispatchProcessDied(int pid, int uid) {
2370 int i = mProcessObservers.beginBroadcast();
2371 while (i > 0) {
2372 i--;
2373 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2374 if (observer != null) {
2375 try {
2376 observer.onProcessDied(pid, uid);
2377 } catch (RemoteException e) {
2378 }
2379 }
2380 }
2381 mProcessObservers.finishBroadcast();
2382 }
2383
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002384 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002385 final int N = mPendingActivityLaunches.size();
2386 if (N <= 0) {
2387 return;
2388 }
2389 for (int i=0; i<N; i++) {
2390 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002391 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002392 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002393 }
2394 mPendingActivityLaunches.clear();
2395 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002396
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002397 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 Intent intent, String resolvedType, IBinder resultTo,
2399 String resultWho, int requestCode, int startFlags,
2400 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002401 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002402 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002403 }
2404
2405 public final int startActivityAsUser(IApplicationThread caller,
2406 Intent intent, String resolvedType, IBinder resultTo,
2407 String resultWho, int requestCode, int startFlags,
2408 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002409 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornd8883992012-09-07 15:58:52 -07002410 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2411 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002412 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002413 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2414 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002415 }
2416
2417 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002418 Intent intent, String resolvedType, IBinder resultTo,
2419 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002420 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002421 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002422 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2423 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002424 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002425 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002426 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002427 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002428 return res;
2429 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002430
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002431 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002432 Intent intent, String resolvedType, IBinder resultTo,
2433 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002434 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002435 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002436 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2437 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002438 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002439 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002440 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002441 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002442 }
2443
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002444 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002445 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002446 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002447 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002448 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002449 // Refuse possible leaked file descriptors
2450 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2451 throw new IllegalArgumentException("File descriptors passed in Intent");
2452 }
2453
2454 IIntentSender sender = intent.getTarget();
2455 if (!(sender instanceof PendingIntentRecord)) {
2456 throw new IllegalArgumentException("Bad PendingIntent object");
2457 }
2458
2459 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002460
2461 synchronized (this) {
2462 // If this is coming from the currently resumed activity, it is
2463 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002464 if (mMainStack.mResumedActivity != null
2465 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002466 Binder.getCallingUid()) {
2467 mAppSwitchesAllowedTime = 0;
2468 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002469 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002470 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2471 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002472 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002473 }
2474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002476 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 // Refuse possible leaked file descriptors
2478 if (intent != null && intent.hasFileDescriptors() == true) {
2479 throw new IllegalArgumentException("File descriptors passed in Intent");
2480 }
2481
2482 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002483 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2484 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002485 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 return false;
2487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 if (r.app == null || r.app.thread == null) {
2489 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002490 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 return false;
2492 }
2493 intent = new Intent(intent);
2494 // The caller is not allowed to change the data.
2495 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2496 // And we are resetting to find the next component...
2497 intent.setComponent(null);
2498
2499 ActivityInfo aInfo = null;
2500 try {
2501 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002502 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002504 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002505 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506
2507 // Look for the original activity in the list...
2508 final int N = resolves != null ? resolves.size() : 0;
2509 for (int i=0; i<N; i++) {
2510 ResolveInfo rInfo = resolves.get(i);
2511 if (rInfo.activityInfo.packageName.equals(r.packageName)
2512 && rInfo.activityInfo.name.equals(r.info.name)) {
2513 // We found the current one... the next matching is
2514 // after it.
2515 i++;
2516 if (i<N) {
2517 aInfo = resolves.get(i).activityInfo;
2518 }
2519 break;
2520 }
2521 }
2522 } catch (RemoteException e) {
2523 }
2524
2525 if (aInfo == null) {
2526 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002527 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 return false;
2529 }
2530
2531 intent.setComponent(new ComponentName(
2532 aInfo.applicationInfo.packageName, aInfo.name));
2533 intent.setFlags(intent.getFlags()&~(
2534 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2535 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2536 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2537 Intent.FLAG_ACTIVITY_NEW_TASK));
2538
2539 // Okay now we need to start the new activity, replacing the
2540 // currently running activity. This is a little tricky because
2541 // we want to start the new one as if the current one is finished,
2542 // but not finish the current one first so that there is no flicker.
2543 // And thus...
2544 final boolean wasFinishing = r.finishing;
2545 r.finishing = true;
2546
2547 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002548 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 final String resultWho = r.resultWho;
2550 final int requestCode = r.requestCode;
2551 r.resultTo = null;
2552 if (resultTo != null) {
2553 resultTo.removeResultsLocked(r, resultWho, requestCode);
2554 }
2555
2556 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002557 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002558 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2559 resultWho, requestCode, -1, r.launchedFromUid, 0,
2560 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 Binder.restoreCallingIdentity(origId);
2562
2563 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 return false;
2566 }
2567 return true;
2568 }
2569 }
2570
Dianne Hackborn41203752012-08-31 14:05:51 -07002571 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002573 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2574
2575 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2576 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577
Amith Yamasani742a6712011-05-04 14:49:28 -07002578 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002579 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002580 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002581 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002582 }
2583
2584 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002585 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002586 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002587 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002588 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002589 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002590 }
2591
Dianne Hackborn41203752012-08-31 14:05:51 -07002592 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002593 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002594 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002595
Dianne Hackborn41203752012-08-31 14:05:51 -07002596 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2597 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002598 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002599 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002600 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002603 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002605 // Quick case: check if the top-most recent task is the same.
2606 if (N > 0 && mRecentTasks.get(0) == task) {
2607 return;
2608 }
2609 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 for (int i=0; i<N; i++) {
2611 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002612 if (task.userId == tr.userId
2613 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2614 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 mRecentTasks.remove(i);
2616 i--;
2617 N--;
2618 if (task.intent == null) {
2619 // If the new recent task we are adding is not fully
2620 // specified, then replace it with the existing recent task.
2621 task = tr;
2622 }
2623 }
2624 }
2625 if (N >= MAX_RECENT_TASKS) {
2626 mRecentTasks.remove(N-1);
2627 }
2628 mRecentTasks.add(0, task);
2629 }
2630
2631 public void setRequestedOrientation(IBinder token,
2632 int requestedOrientation) {
2633 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002634 ActivityRecord r = mMainStack.isInStackLocked(token);
2635 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 return;
2637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002639 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002641 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002642 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (config != null) {
2644 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002645 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002646 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
2649 Binder.restoreCallingIdentity(origId);
2650 }
2651 }
2652
2653 public int getRequestedOrientation(IBinder token) {
2654 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002655 ActivityRecord r = mMainStack.isInStackLocked(token);
2656 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2658 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002659 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 }
2661 }
2662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 /**
2664 * This is the internal entry point for handling Activity.finish().
2665 *
2666 * @param token The Binder token referencing the Activity we want to finish.
2667 * @param resultCode Result code, if any, from this Activity.
2668 * @param resultData Result data (Intent), if any, from this Activity.
2669 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002670 * @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 -08002671 */
2672 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2673 // Refuse possible leaked file descriptors
2674 if (resultData != null && resultData.hasFileDescriptors() == true) {
2675 throw new IllegalArgumentException("File descriptors passed in Intent");
2676 }
2677
2678 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002679 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002680 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002681 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 if (next != null) {
2683 // ask watcher if this is allowed
2684 boolean resumeOK = true;
2685 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002686 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002688 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002689 }
2690
2691 if (!resumeOK) {
2692 return false;
2693 }
2694 }
2695 }
2696 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002697 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002698 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 Binder.restoreCallingIdentity(origId);
2700 return res;
2701 }
2702 }
2703
Dianne Hackborn860755f2010-06-03 18:47:52 -07002704 public final void finishHeavyWeightApp() {
2705 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2706 != PackageManager.PERMISSION_GRANTED) {
2707 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2708 + Binder.getCallingPid()
2709 + ", uid=" + Binder.getCallingUid()
2710 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2711 Slog.w(TAG, msg);
2712 throw new SecurityException(msg);
2713 }
2714
2715 synchronized(this) {
2716 if (mHeavyWeightProcess == null) {
2717 return;
2718 }
2719
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002720 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002721 mHeavyWeightProcess.activities);
2722 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002723 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002724 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002725 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002726 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002728 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002729 }
2730 }
2731 }
2732
Dianne Hackborn41203752012-08-31 14:05:51 -07002733 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2734 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002735 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002736 }
2737 }
2738
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002739 public void crashApplication(int uid, int initialPid, String packageName,
2740 String message) {
2741 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2742 != PackageManager.PERMISSION_GRANTED) {
2743 String msg = "Permission Denial: crashApplication() from pid="
2744 + Binder.getCallingPid()
2745 + ", uid=" + Binder.getCallingUid()
2746 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2747 Slog.w(TAG, msg);
2748 throw new SecurityException(msg);
2749 }
2750
2751 synchronized(this) {
2752 ProcessRecord proc = null;
2753
2754 // Figure out which process to kill. We don't trust that initialPid
2755 // still has any relation to current pids, so must scan through the
2756 // list.
2757 synchronized (mPidsSelfLocked) {
2758 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2759 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002760 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002761 continue;
2762 }
2763 if (p.pid == initialPid) {
2764 proc = p;
2765 break;
2766 }
2767 for (String str : p.pkgList) {
2768 if (str.equals(packageName)) {
2769 proc = p;
2770 }
2771 }
2772 }
2773 }
2774
2775 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002776 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002777 + " initialPid=" + initialPid
2778 + " packageName=" + packageName);
2779 return;
2780 }
2781
2782 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002783 if (proc.pid == Process.myPid()) {
2784 Log.w(TAG, "crashApplication: trying to crash self!");
2785 return;
2786 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002787 long ident = Binder.clearCallingIdentity();
2788 try {
2789 proc.thread.scheduleCrash(message);
2790 } catch (RemoteException e) {
2791 }
2792 Binder.restoreCallingIdentity(ident);
2793 }
2794 }
2795 }
2796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002797 public final void finishSubActivity(IBinder token, String resultWho,
2798 int requestCode) {
2799 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002801 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 Binder.restoreCallingIdentity(origId);
2803 }
2804 }
2805
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002806 public boolean finishActivityAffinity(IBinder token) {
2807 synchronized(this) {
2808 final long origId = Binder.clearCallingIdentity();
2809 boolean res = mMainStack.finishActivityAffinityLocked(token);
2810 Binder.restoreCallingIdentity(origId);
2811 return res;
2812 }
2813 }
2814
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002815 public boolean willActivityBeVisible(IBinder token) {
2816 synchronized(this) {
2817 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2819 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002820 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002821 return true;
2822 }
2823 if (r.fullscreen && !r.finishing) {
2824 return false;
2825 }
2826 }
2827 return true;
2828 }
2829 }
2830
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002831 public void overridePendingTransition(IBinder token, String packageName,
2832 int enterAnim, int exitAnim) {
2833 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002834 ActivityRecord self = mMainStack.isInStackLocked(token);
2835 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002836 return;
2837 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002838
2839 final long origId = Binder.clearCallingIdentity();
2840
2841 if (self.state == ActivityState.RESUMED
2842 || self.state == ActivityState.PAUSING) {
2843 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002844 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002845 }
2846
2847 Binder.restoreCallingIdentity(origId);
2848 }
2849 }
2850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 * Main function for removing an existing process from the activity manager
2853 * as a result of that process going away. Clears out all connections
2854 * to the process.
2855 */
2856 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002857 boolean restarting, boolean allowRestart) {
2858 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002859 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002860 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002861 }
2862
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002863 if (mProfileProc == app) {
2864 clearProfilerLocked();
2865 }
2866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002868 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2869 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2870 mMainStack.mPausingActivity = null;
2871 }
2872 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2873 mMainStack.mLastPausedActivity = null;
2874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875
2876 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002877 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878
2879 boolean atTop = true;
2880 boolean hasVisibleActivities = false;
2881
2882 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002883 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002884 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 TAG, "Removing app " + app + " from history with " + i + " entries");
2886 while (i > 0) {
2887 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002888 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002889 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002890 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2891 if (r.app == app) {
2892 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002893 if (ActivityStack.DEBUG_ADD_REMOVE) {
2894 RuntimeException here = new RuntimeException("here");
2895 here.fillInStackTrace();
2896 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2897 + ": haveState=" + r.haveState
2898 + " stateNotNeeded=" + r.stateNotNeeded
2899 + " finishing=" + r.finishing
2900 + " state=" + r.state, here);
2901 }
2902 if (!r.finishing) {
2903 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002904 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2905 System.identityHashCode(r),
2906 r.task.taskId, r.shortComponentName,
2907 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002908 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002909 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910
2911 } else {
2912 // We have the current state for this activity, so
2913 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002914 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 TAG, "Keeping entry, setting app to null");
2916 if (r.visible) {
2917 hasVisibleActivities = true;
2918 }
2919 r.app = null;
2920 r.nowVisible = false;
2921 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002922 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2923 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 r.icicle = null;
2925 }
2926 }
2927
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002928 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 atTop = false;
2931 }
2932
2933 app.activities.clear();
2934
2935 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002936 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 + " running instrumentation " + app.instrumentationClass);
2938 Bundle info = new Bundle();
2939 info.putString("shortMsg", "Process crashed.");
2940 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2941 }
2942
2943 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002944 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 // If there was nothing to resume, and we are not already
2946 // restarting this process, but there is a visible activity that
2947 // is hosted by the process... then make sure all visible
2948 // activities are running, taking care of restarting this
2949 // process.
2950 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002951 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
2953 }
2954 }
2955 }
2956
2957 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2958 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002960 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2961 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2963 return i;
2964 }
2965 }
2966 return -1;
2967 }
2968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002969 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 IApplicationThread thread) {
2971 if (thread == null) {
2972 return null;
2973 }
2974
2975 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002976 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002977 }
2978
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002979 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 IApplicationThread thread) {
2981
2982 mProcDeaths[0]++;
2983
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002984 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2985 synchronized (stats) {
2986 stats.noteProcessDiedLocked(app.info.uid, pid);
2987 }
2988
Magnus Edlund7bb25812010-02-24 15:45:06 +01002989 // Clean up already done if the process has been re-started.
2990 if (app.pid == pid && app.thread != null &&
2991 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002992 if (!app.killedBackground) {
2993 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2994 + ") has died.");
2995 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002996 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002997 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 TAG, "Dying app: " + app + ", pid: " + pid
2999 + ", thread: " + thread.asBinder());
3000 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003001 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002
3003 if (doLowMem) {
3004 // If there are no longer any background processes running,
3005 // and the app that died was not running instrumentation,
3006 // then tell everyone we are now low on memory.
3007 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003008 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3009 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07003010 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 haveBg = true;
3012 break;
3013 }
3014 }
3015
3016 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003017 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003018 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003019 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3020 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003021 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003022 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3023 // The low memory report is overriding any current
3024 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003025 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003026 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003027 rec.lastRequestedGc = 0;
3028 } else {
3029 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003030 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003031 rec.reportLowMemory = true;
3032 rec.lastLowMemory = now;
3033 mProcessesToGc.remove(rec);
3034 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 }
3036 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003037 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003038 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 }
3040 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003041 } else if (app.pid != pid) {
3042 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003043 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003044 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003045 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003046 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003047 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 + thread.asBinder());
3049 }
3050 }
3051
Dan Egnor42471dd2010-01-07 17:25:22 -08003052 /**
3053 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003054 * @param clearTraces causes the dump file to be erased prior to the new
3055 * traces being written, if true; when false, the new traces will be
3056 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003057 * @param firstPids of dalvik VM processes to dump stack traces for first
3058 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003059 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003060 * @return file containing stack traces, or null if no dump file is configured
3061 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003062 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003063 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003064 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3065 if (tracesPath == null || tracesPath.length() == 0) {
3066 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003068
3069 File tracesFile = new File(tracesPath);
3070 try {
3071 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003072 if (!tracesDir.exists()) {
3073 tracesFile.mkdirs();
3074 if (!SELinux.restorecon(tracesDir)) {
3075 return null;
3076 }
3077 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003078 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3079
Christopher Tate6ee412d2010-05-28 12:01:56 -07003080 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003081 tracesFile.createNewFile();
3082 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3083 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003084 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003085 return null;
3086 }
3087
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003088 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003089 return tracesFile;
3090 }
3091
3092 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003093 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003094 // Use a FileObserver to detect when traces finish writing.
3095 // The order of traces is considered important to maintain for legibility.
3096 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3097 public synchronized void onEvent(int event, String path) { notify(); }
3098 };
3099
3100 try {
3101 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003102
3103 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003104 if (firstPids != null) {
3105 try {
3106 int num = firstPids.size();
3107 for (int i = 0; i < num; i++) {
3108 synchronized (observer) {
3109 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3110 observer.wait(200); // Wait for write-close, give up after 200msec
3111 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003112 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003113 } catch (InterruptedException e) {
3114 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003115 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003116 }
3117
3118 // Next measure CPU usage.
3119 if (processStats != null) {
3120 processStats.init();
3121 System.gc();
3122 processStats.update();
3123 try {
3124 synchronized (processStats) {
3125 processStats.wait(500); // measure over 1/2 second.
3126 }
3127 } catch (InterruptedException e) {
3128 }
3129 processStats.update();
3130
3131 // We'll take the stack crawls of just the top apps using CPU.
3132 final int N = processStats.countWorkingStats();
3133 int numProcs = 0;
3134 for (int i=0; i<N && numProcs<5; i++) {
3135 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3136 if (lastPids.indexOfKey(stats.pid) >= 0) {
3137 numProcs++;
3138 try {
3139 synchronized (observer) {
3140 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3141 observer.wait(200); // Wait for write-close, give up after 200msec
3142 }
3143 } catch (InterruptedException e) {
3144 Log.wtf(TAG, e);
3145 }
3146
3147 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003148 }
3149 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003150
Dan Egnor42471dd2010-01-07 17:25:22 -08003151 } finally {
3152 observer.stopWatching();
3153 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003154
3155 if (nativeProcs != null) {
3156 int[] pids = Process.getPidsForCommands(nativeProcs);
3157 if (pids != null) {
3158 for (int pid : pids) {
3159 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3160 }
3161 }
3162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 }
3164
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003165 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003166 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003167 return;
3168 }
3169 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3170 if (tracesPath == null || tracesPath.length() == 0) {
3171 return;
3172 }
3173
3174 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3175 StrictMode.allowThreadDiskWrites();
3176 try {
3177 final File tracesFile = new File(tracesPath);
3178 final File tracesDir = tracesFile.getParentFile();
3179 final File tracesTmp = new File(tracesDir, "__tmp__");
3180 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003181 if (!tracesDir.exists()) {
3182 tracesFile.mkdirs();
3183 if (!SELinux.restorecon(tracesDir.getPath())) {
3184 return;
3185 }
3186 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003187 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3188
3189 if (tracesFile.exists()) {
3190 tracesTmp.delete();
3191 tracesFile.renameTo(tracesTmp);
3192 }
3193 StringBuilder sb = new StringBuilder();
3194 Time tobj = new Time();
3195 tobj.set(System.currentTimeMillis());
3196 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3197 sb.append(": ");
3198 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3199 sb.append(" since ");
3200 sb.append(msg);
3201 FileOutputStream fos = new FileOutputStream(tracesFile);
3202 fos.write(sb.toString().getBytes());
3203 if (app == null) {
3204 fos.write("\n*** No application process!".getBytes());
3205 }
3206 fos.close();
3207 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3208 } catch (IOException e) {
3209 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3210 return;
3211 }
3212
3213 if (app != null) {
3214 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3215 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003216 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003217 }
3218
3219 File lastTracesFile = null;
3220 File curTracesFile = null;
3221 for (int i=9; i>=0; i--) {
3222 String name = String.format("slow%02d.txt", i);
3223 curTracesFile = new File(tracesDir, name);
3224 if (curTracesFile.exists()) {
3225 if (lastTracesFile != null) {
3226 curTracesFile.renameTo(lastTracesFile);
3227 } else {
3228 curTracesFile.delete();
3229 }
3230 }
3231 lastTracesFile = curTracesFile;
3232 }
3233 tracesFile.renameTo(curTracesFile);
3234 if (tracesTmp.exists()) {
3235 tracesTmp.renameTo(tracesFile);
3236 }
3237 } finally {
3238 StrictMode.setThreadPolicy(oldPolicy);
3239 }
3240 }
3241
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003242 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3243 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003244 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3245 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3246
Dianne Hackborn287952c2010-09-22 22:34:31 -07003247 if (mController != null) {
3248 try {
3249 // 0 == continue, -1 = kill process immediately
3250 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3251 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3252 } catch (RemoteException e) {
3253 mController = null;
3254 }
3255 }
3256
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003257 long anrTime = SystemClock.uptimeMillis();
3258 if (MONITOR_CPU_USAGE) {
3259 updateCpuStatsNow();
3260 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003261
3262 synchronized (this) {
3263 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3264 if (mShuttingDown) {
3265 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3266 return;
3267 } else if (app.notResponding) {
3268 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3269 return;
3270 } else if (app.crashing) {
3271 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3272 return;
3273 }
3274
3275 // In case we come through here for the same app before completing
3276 // this one, mark as anring now so we will bail out.
3277 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003278
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003279 // Log the ANR to the event log.
3280 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3281 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003282
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003283 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003284 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003285
3286 int parentPid = app.pid;
3287 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003288 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003289
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003290 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003291
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003292 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3293 ProcessRecord r = mLruProcesses.get(i);
3294 if (r != null && r.thread != null) {
3295 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003296 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3297 if (r.persistent) {
3298 firstPids.add(pid);
3299 } else {
3300 lastPids.put(pid, Boolean.TRUE);
3301 }
3302 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
3305 }
3306
Dan Egnor42471dd2010-01-07 17:25:22 -08003307 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003308 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003309 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003310 info.append("ANR in ").append(app.processName);
3311 if (activity != null && activity.shortComponentName != null) {
3312 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003313 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003314 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003316 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003318 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003319 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321
Dianne Hackborn287952c2010-09-22 22:34:31 -07003322 final ProcessStats processStats = new ProcessStats(true);
3323
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003324 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003325
Dan Egnor42471dd2010-01-07 17:25:22 -08003326 String cpuInfo = null;
3327 if (MONITOR_CPU_USAGE) {
3328 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003329 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003330 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003331 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003332 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003333 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003336 info.append(processStats.printCurrentState(anrTime));
3337
Joe Onorato8a9b2202010-02-26 18:56:32 -08003338 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003339 if (tracesFile == null) {
3340 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3341 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3342 }
3343
Jeff Sharkeya353d262011-10-28 11:12:06 -07003344 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3345 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003346
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003347 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003349 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3350 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003352 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3353 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003356 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 }
3358 }
3359
Dan Egnor42471dd2010-01-07 17:25:22 -08003360 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3361 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3362 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003363
3364 synchronized (this) {
3365 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003366 Slog.w(TAG, "Killing " + app + ": background ANR");
3367 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3368 app.processName, app.setAdj, "background ANR");
3369 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003370 return;
3371 }
3372
3373 // Set the app's notResponding state, and look up the errorReportReceiver
3374 makeAppNotRespondingLocked(app,
3375 activity != null ? activity.shortComponentName : null,
3376 annotation != null ? "ANR " + annotation : "ANR",
3377 info.toString());
3378
3379 // Bring up the infamous App Not Responding dialog
3380 Message msg = Message.obtain();
3381 HashMap map = new HashMap();
3382 msg.what = SHOW_NOT_RESPONDING_MSG;
3383 msg.obj = map;
3384 map.put("app", app);
3385 if (activity != null) {
3386 map.put("activity", activity);
3387 }
3388
3389 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 }
3392
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003393 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3394 if (!mLaunchWarningShown) {
3395 mLaunchWarningShown = true;
3396 mHandler.post(new Runnable() {
3397 @Override
3398 public void run() {
3399 synchronized (ActivityManagerService.this) {
3400 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3401 d.show();
3402 mHandler.postDelayed(new Runnable() {
3403 @Override
3404 public void run() {
3405 synchronized (ActivityManagerService.this) {
3406 d.dismiss();
3407 mLaunchWarningShown = false;
3408 }
3409 }
3410 }, 4000);
3411 }
3412 }
3413 });
3414 }
3415 }
3416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003418 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003419 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 int uid = Binder.getCallingUid();
3421 int pid = Binder.getCallingPid();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003422 userId = handleIncomingUserLocked(pid, uid,
3423 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 long callingId = Binder.clearCallingIdentity();
3425 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003426 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 int pkgUid = -1;
3428 synchronized(this) {
3429 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003430 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 } catch (RemoteException e) {
3432 }
3433 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003434 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 return false;
3436 }
3437 if (uid == pkgUid || checkComponentPermission(
3438 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003439 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003441 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } else {
3443 throw new SecurityException(pid+" does not have permission:"+
3444 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3445 "for process:"+packageName);
3446 }
3447 }
3448
3449 try {
3450 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003451 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3453 Uri.fromParts("package", packageName, null));
3454 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003455 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003456 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 } catch (RemoteException e) {
3458 }
3459 } finally {
3460 Binder.restoreCallingIdentity(callingId);
3461 }
3462 return true;
3463 }
3464
Dianne Hackborn1676c852012-09-10 14:52:30 -07003465 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003466 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3467 != PackageManager.PERMISSION_GRANTED &&
3468 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3469 != PackageManager.PERMISSION_GRANTED) {
3470 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 + Binder.getCallingPid()
3472 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003473 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003474 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 throw new SecurityException(msg);
3476 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003477
3478 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3479 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 long callingId = Binder.clearCallingIdentity();
3481 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003482 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003483 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003484 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003486 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 } catch (RemoteException e) {
3488 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003489 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003490 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 return;
3492 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003493 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003494 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3495 }
3496 } finally {
3497 Binder.restoreCallingIdentity(callingId);
3498 }
3499 }
3500
3501 public void killAllBackgroundProcesses() {
3502 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3503 != PackageManager.PERMISSION_GRANTED) {
3504 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3505 + Binder.getCallingPid()
3506 + ", uid=" + Binder.getCallingUid()
3507 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3508 Slog.w(TAG, msg);
3509 throw new SecurityException(msg);
3510 }
3511
3512 long callingId = Binder.clearCallingIdentity();
3513 try {
3514 synchronized(this) {
3515 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3516 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3517 final int NA = apps.size();
3518 for (int ia=0; ia<NA; ia++) {
3519 ProcessRecord app = apps.valueAt(ia);
3520 if (app.persistent) {
3521 // we don't kill persistent processes
3522 continue;
3523 }
3524 if (app.removed) {
3525 procs.add(app);
3526 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3527 app.removed = true;
3528 procs.add(app);
3529 }
3530 }
3531 }
3532
3533 int N = procs.size();
3534 for (int i=0; i<N; i++) {
3535 removeProcessLocked(procs.get(i), false, true, "kill all background");
3536 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003537 }
3538 } finally {
3539 Binder.restoreCallingIdentity(callingId);
3540 }
3541 }
3542
Dianne Hackborn1676c852012-09-10 14:52:30 -07003543 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003544 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3545 != PackageManager.PERMISSION_GRANTED) {
3546 String msg = "Permission Denial: forceStopPackage() from pid="
3547 + Binder.getCallingPid()
3548 + ", uid=" + Binder.getCallingUid()
3549 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003550 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003551 throw new SecurityException(msg);
3552 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003553 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3554 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003555 long callingId = Binder.clearCallingIdentity();
3556 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003557 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003558 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003559 int[] users = userId == UserHandle.USER_ALL
3560 ? getUsersLocked() : new int[] { userId };
3561 for (int user : users) {
3562 int pkgUid = -1;
3563 try {
3564 pkgUid = pm.getPackageUid(packageName, user);
3565 } catch (RemoteException e) {
3566 }
3567 if (pkgUid == -1) {
3568 Slog.w(TAG, "Invalid packageName: " + packageName);
3569 continue;
3570 }
3571 try {
3572 pm.setPackageStoppedState(packageName, true, user);
3573 } catch (RemoteException e) {
3574 } catch (IllegalArgumentException e) {
3575 Slog.w(TAG, "Failed trying to unstop package "
3576 + packageName + ": " + e);
3577 }
3578 if (isUserRunningLocked(user)) {
3579 forceStopPackageLocked(packageName, pkgUid);
3580 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 }
3583 } finally {
3584 Binder.restoreCallingIdentity(callingId);
3585 }
3586 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003587
3588 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003589 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003590 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003591 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003592 if (pkg == null) {
3593 return;
3594 }
3595 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003596 if (appid < 0) {
3597 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003598 return;
3599 }
3600 int callerUid = Binder.getCallingUid();
3601 // Only the system server can kill an application
3602 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003603 // Post an aysnc message to kill the application
3604 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003605 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003606 msg.arg2 = 0;
3607 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003608 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003609 } else {
3610 throw new SecurityException(callerUid + " cannot kill pkg: " +
3611 pkg);
3612 }
3613 }
3614
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003615 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003616 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003617
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003618 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003619 final int uid = Binder.getCallingUid();
3620 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003621 try {
3622 synchronized (this) {
3623 // Only allow this from foreground processes, so that background
3624 // applications can't abuse it to prevent system UI from being shown.
3625 if (uid >= Process.FIRST_APPLICATION_UID) {
3626 ProcessRecord proc;
3627 synchronized (mPidsSelfLocked) {
3628 proc = mPidsSelfLocked.get(pid);
3629 }
3630 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3631 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3632 + " from background process " + proc);
3633 return;
3634 }
3635 }
3636 closeSystemDialogsLocked(reason);
3637 }
3638 } finally {
3639 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003640 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003641 }
3642
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003643 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003644 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003645 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003646 if (reason != null) {
3647 intent.putExtra("reason", reason);
3648 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003649 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003650
Dianne Hackborne302a162012-05-15 14:58:32 -07003651 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3652 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003653 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003654 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003655 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003656 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003657 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003658
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003659 broadcastIntentLocked(null, null, intent, null,
3660 null, 0, null, null, null, false, false, -1,
3661 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003662 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003663
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003664 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003665 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003666 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003667 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3668 for (int i=pids.length-1; i>=0; i--) {
3669 infos[i] = new Debug.MemoryInfo();
3670 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003671 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003672 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003673 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003674
Dianne Hackbornb437e092011-08-05 17:50:29 -07003675 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003676 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003677 long[] pss = new long[pids.length];
3678 for (int i=pids.length-1; i>=0; i--) {
3679 pss[i] = Debug.getPss(pids[i]);
3680 }
3681 return pss;
3682 }
3683
Christopher Tate5e1ab332009-09-01 20:32:49 -07003684 public void killApplicationProcess(String processName, int uid) {
3685 if (processName == null) {
3686 return;
3687 }
3688
3689 int callerUid = Binder.getCallingUid();
3690 // Only the system server can kill an application
3691 if (callerUid == Process.SYSTEM_UID) {
3692 synchronized (this) {
3693 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003694 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003695 try {
3696 app.thread.scheduleSuicide();
3697 } catch (RemoteException e) {
3698 // If the other end already died, then our work here is done.
3699 }
3700 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003701 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003702 + processName + " / " + uid);
3703 }
3704 }
3705 } else {
3706 throw new SecurityException(callerUid + " cannot kill app process: " +
3707 processName);
3708 }
3709 }
3710
Dianne Hackborn03abb812010-01-04 18:43:19 -08003711 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003712 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3713 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3715 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003716 if (!mProcessesReady) {
3717 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 intent.putExtra(Intent.EXTRA_UID, uid);
3720 broadcastIntentLocked(null, null, intent,
3721 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003722 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003723 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003725
3726 private void forceStopUserLocked(int userId) {
3727 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3728 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3729 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3730 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3731 broadcastIntentLocked(null, null, intent,
3732 null, null, 0, null, null, null,
3733 false, false,
3734 MY_PID, Process.SYSTEM_UID, userId);
3735 }
3736
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003737 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003738 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3739 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003740 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741
Dianne Hackborn03abb812010-01-04 18:43:19 -08003742 // Remove all processes this package may have touched: all with the
3743 // same UID (except for the system or root user), and all whose name
3744 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003745 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003746 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3747 final int NA = apps.size();
3748 for (int ia=0; ia<NA; ia++) {
3749 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003750 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003751 // we don't kill persistent processes
3752 continue;
3753 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003754 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003755 if (doit) {
3756 procs.add(app);
3757 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003758 continue;
3759 }
3760
3761 // Skip process if it doesn't meet our oom adj requirement.
3762 if (app.setAdj < minOomAdj) {
3763 continue;
3764 }
3765
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003766 // If no package is specified, we call all processes under the
3767 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003768 if (packageName == null) {
3769 if (app.userId != userId) {
3770 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003771 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003772 // Package has been specified, we want to hit all processes
3773 // that match it. We need to qualify this by the processes
3774 // that are running under the specified app and user ID.
3775 } else {
3776 if (UserHandle.getAppId(app.uid) != appId) {
3777 continue;
3778 }
3779 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3780 continue;
3781 }
3782 if (!app.pkgList.contains(packageName)) {
3783 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003784 }
3785 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003786
3787 // Process has passed all conditions, kill it!
3788 if (!doit) {
3789 return true;
3790 }
3791 app.removed = true;
3792 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003793 }
3794 }
3795
3796 int N = procs.size();
3797 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003798 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003799 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003800 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003801 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003802
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003803 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003804 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003805 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003806 int i;
3807 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003809 if (userId == UserHandle.USER_ALL && name == null) {
3810 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3811 }
3812
3813 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003815 appId = UserHandle.getAppId(
3816 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 } catch (RemoteException e) {
3818 }
3819 }
3820
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003821 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003822 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003823 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3824 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003825 } else {
3826 Slog.i(TAG, "Force stopping user " + userId);
3827 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003828
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003829 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3830 while (badApps.hasNext()) {
3831 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003832 for (i=ba.size()-1; i>=0; i--) {
3833 boolean remove = false;
3834 final int entUid = ba.keyAt(i);
3835 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003836 if (userId == UserHandle.USER_ALL) {
3837 if (UserHandle.getAppId(entUid) == appId) {
3838 remove = true;
3839 }
3840 } else {
3841 if (entUid == UserHandle.getUid(userId, appId)) {
3842 remove = true;
3843 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003844 }
3845 } else if (UserHandle.getUserId(entUid) == userId) {
3846 remove = true;
3847 }
3848 if (remove) {
3849 ba.removeAt(i);
3850 }
3851 }
3852 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003853 badApps.remove();
3854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
3856 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003857
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003858 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3859 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003860 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003862 TaskRecord lastTask = null;
3863 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003864 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003865 final boolean samePackage = r.packageName.equals(name)
3866 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003867 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003868 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003869 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003870 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003871 if (r.finishing) {
3872 // If this activity is just finishing, then it is not
3873 // interesting as far as something to stop.
3874 continue;
3875 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003876 return true;
3877 }
3878 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003879 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003880 if (samePackage) {
3881 if (r.app != null) {
3882 r.app.removed = true;
3883 }
3884 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003886 lastTask = r.task;
3887 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003888 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003889 i--;
3890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892 }
3893
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003894 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3895 if (!doit) {
3896 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003898 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003900
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003901 if (name == null) {
3902 // Remove all sticky broadcasts from this user.
3903 mStickyBroadcasts.remove(userId);
3904 }
3905
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003906 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003907 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3908 userId, providers)) {
3909 if (!doit) {
3910 return true;
3911 }
3912 didSomething = true;
3913 }
3914 N = providers.size();
3915 for (i=0; i<N; i++) {
3916 removeDyingProviderLocked(null, providers.get(i), true);
3917 }
3918
3919 if (mIntentSenderRecords.size() > 0) {
3920 Iterator<WeakReference<PendingIntentRecord>> it
3921 = mIntentSenderRecords.values().iterator();
3922 while (it.hasNext()) {
3923 WeakReference<PendingIntentRecord> wpir = it.next();
3924 if (wpir == null) {
3925 it.remove();
3926 continue;
3927 }
3928 PendingIntentRecord pir = wpir.get();
3929 if (pir == null) {
3930 it.remove();
3931 continue;
3932 }
3933 if (name == null) {
3934 // Stopping user, remove all objects for the user.
3935 if (pir.key.userId != userId) {
3936 // Not the same user, skip it.
3937 continue;
3938 }
3939 } else {
3940 if (UserHandle.getAppId(pir.uid) != appId) {
3941 // Different app id, skip it.
3942 continue;
3943 }
3944 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3945 // Different user, skip it.
3946 continue;
3947 }
3948 if (!pir.key.packageName.equals(name)) {
3949 // Different package, skip it.
3950 continue;
3951 }
3952 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003953 if (!doit) {
3954 return true;
3955 }
3956 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003957 it.remove();
3958 pir.canceled = true;
3959 if (pir.key.activity != null) {
3960 pir.key.activity.pendingResults.remove(pir.ref);
3961 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003962 }
3963 }
3964
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003965 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003966 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003967 AttributeCache ac = AttributeCache.instance();
3968 if (ac != null) {
3969 ac.removePackage(name);
3970 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003971 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003972 if (mBooted) {
3973 mMainStack.resumeTopActivityLocked(null);
3974 mMainStack.scheduleIdleLocked();
3975 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003976 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003977
3978 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 }
3980
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003981 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003982 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003984 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003985 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003986 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 + "/" + uid + ")");
3988
3989 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003990 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003991 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003992 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3993 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003994 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 boolean needRestart = false;
3997 if (app.pid > 0 && app.pid != MY_PID) {
3998 int pid = app.pid;
3999 synchronized (mPidsSelfLocked) {
4000 mPidsSelfLocked.remove(pid);
4001 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4002 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004003 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004004 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004005 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08004006 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004008 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 } else {
4012 needRestart = true;
4013 }
4014 }
4015 } else {
4016 mRemovedProcesses.add(app);
4017 }
4018
4019 return needRestart;
4020 }
4021
4022 private final void processStartTimedOutLocked(ProcessRecord app) {
4023 final int pid = app.pid;
4024 boolean gone = false;
4025 synchronized (mPidsSelfLocked) {
4026 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4027 if (knownApp != null && knownApp.thread == null) {
4028 mPidsSelfLocked.remove(pid);
4029 gone = true;
4030 }
4031 }
4032
4033 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004035 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004036 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004037 mProcessNames.remove(app.processName, app.uid);
4038 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004039 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004040 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4041 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004042 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004043 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004044 // Take care of any launching providers waiting for this process.
4045 checkAppInLaunchingProvidersLocked(app, true);
4046 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004047 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004048 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4049 app.processName, app.setAdj, "start timeout");
4050 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004051 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004052 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004053 try {
4054 IBackupManager bm = IBackupManager.Stub.asInterface(
4055 ServiceManager.getService(Context.BACKUP_SERVICE));
4056 bm.agentDisconnected(app.info.packageName);
4057 } catch (RemoteException e) {
4058 // Can't happen; the backup manager is local
4059 }
4060 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004061 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004062 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004063 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004066 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 }
4068 }
4069
4070 private final boolean attachApplicationLocked(IApplicationThread thread,
4071 int pid) {
4072
4073 // Find the application record that is being attached... either via
4074 // the pid if we are running in multiple processes, or just pull the
4075 // next app record if we are emulating process with anonymous threads.
4076 ProcessRecord app;
4077 if (pid != MY_PID && pid >= 0) {
4078 synchronized (mPidsSelfLocked) {
4079 app = mPidsSelfLocked.get(pid);
4080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 } else {
4082 app = null;
4083 }
4084
4085 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004086 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004088 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004089 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004090 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004091 } else {
4092 try {
4093 thread.scheduleExit();
4094 } catch (Exception e) {
4095 // Ignore exceptions.
4096 }
4097 }
4098 return false;
4099 }
4100
4101 // If this application record is still attached to a previous
4102 // process, clean it up now.
4103 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004104 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 }
4106
4107 // Tell the process all about itself.
4108
Joe Onorato8a9b2202010-02-26 18:56:32 -08004109 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 TAG, "Binding process pid " + pid + " to record " + app);
4111
4112 String processName = app.processName;
4113 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004114 AppDeathRecipient adr = new AppDeathRecipient(
4115 app, pid, thread);
4116 thread.asBinder().linkToDeath(adr, 0);
4117 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 } catch (RemoteException e) {
4119 app.resetPackageList();
4120 startProcessLocked(app, "link fail", processName);
4121 return false;
4122 }
4123
Doug Zongker2bec3d42009-12-04 12:52:44 -08004124 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125
4126 app.thread = thread;
4127 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004128 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4129 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 app.forcingToForeground = null;
4131 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004132 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 app.debugging = false;
4134
4135 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4136
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004137 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004138 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004140 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004141 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004142 }
4143
Joe Onorato8a9b2202010-02-26 18:56:32 -08004144 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 TAG, "New app record " + app
4146 + " thread=" + thread.asBinder() + " pid=" + pid);
4147 try {
4148 int testMode = IApplicationThread.DEBUG_OFF;
4149 if (mDebugApp != null && mDebugApp.equals(processName)) {
4150 testMode = mWaitForDebugger
4151 ? IApplicationThread.DEBUG_WAIT
4152 : IApplicationThread.DEBUG_ON;
4153 app.debugging = true;
4154 if (mDebugTransient) {
4155 mDebugApp = mOrigDebugApp;
4156 mWaitForDebugger = mOrigWaitForDebugger;
4157 }
4158 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004159 String profileFile = app.instrumentationProfileFile;
4160 ParcelFileDescriptor profileFd = null;
4161 boolean profileAutoStop = false;
4162 if (mProfileApp != null && mProfileApp.equals(processName)) {
4163 mProfileProc = app;
4164 profileFile = mProfileFile;
4165 profileFd = mProfileFd;
4166 profileAutoStop = mAutoStopProfiler;
4167 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004168 boolean enableOpenGlTrace = false;
4169 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4170 enableOpenGlTrace = true;
4171 mOpenGlTraceApp = null;
4172 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004173
Christopher Tate181fafa2009-05-14 11:12:14 -07004174 // If the app is being launched for restore or full backup, set it up specially
4175 boolean isRestrictedBackupMode = false;
4176 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4177 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004178 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004179 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4180 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004181
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004182 ensurePackageDexOpt(app.instrumentationInfo != null
4183 ? app.instrumentationInfo.packageName
4184 : app.info.packageName);
4185 if (app.instrumentationClass != null) {
4186 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004187 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004188 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004189 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004190 ApplicationInfo appInfo = app.instrumentationInfo != null
4191 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004192 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004193 if (profileFd != null) {
4194 profileFd = profileFd.dup();
4195 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004196 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004197 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004198 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4199 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004200 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004201 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004202 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004203 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 } catch (Exception e) {
4205 // todo: Yikes! What should we do? For now we will try to
4206 // start another process, but that could easily get us in
4207 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004208 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209
4210 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004211 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 startProcessLocked(app, "bind fail", processName);
4213 return false;
4214 }
4215
4216 // Remove this record from the list of starting applications.
4217 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004218 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4219 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004220 mProcessesOnHold.remove(app);
4221
4222 boolean badApp = false;
4223 boolean didSomething = false;
4224
4225 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004226 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004227 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004228 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 && processName.equals(hr.processName)) {
4230 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004231 if (mHeadless) {
4232 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4233 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 didSomething = true;
4235 }
4236 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004237 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 + hr.intent.getComponent().flattenToShortString(), e);
4239 badApp = true;
4240 }
4241 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004242 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
4244 }
4245
4246 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004247 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004249 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004251 badApp = true;
4252 }
4253 }
4254
Christopher Tatef46723b2012-01-26 14:19:24 -08004255 // Check if a next-broadcast receiver is in this process...
4256 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004258 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004260 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 }
4263 }
4264
Christopher Tate181fafa2009-05-14 11:12:14 -07004265 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004266 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004267 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004268 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004269 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004270 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4271 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4272 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004273 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004274 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004275 e.printStackTrace();
4276 }
4277 }
4278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 if (badApp) {
4280 // todo: Also need to kill application to deal with all
4281 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004282 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 return false;
4284 }
4285
4286 if (!didSomething) {
4287 updateOomAdjLocked();
4288 }
4289
4290 return true;
4291 }
4292
4293 public final void attachApplication(IApplicationThread thread) {
4294 synchronized (this) {
4295 int callingPid = Binder.getCallingPid();
4296 final long origId = Binder.clearCallingIdentity();
4297 attachApplicationLocked(thread, callingPid);
4298 Binder.restoreCallingIdentity(origId);
4299 }
4300 }
4301
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004302 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004304 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4305 if (stopProfiling) {
4306 synchronized (this) {
4307 if (mProfileProc == r.app) {
4308 if (mProfileFd != null) {
4309 try {
4310 mProfileFd.close();
4311 } catch (IOException e) {
4312 }
4313 clearProfilerLocked();
4314 }
4315 }
4316 }
4317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 Binder.restoreCallingIdentity(origId);
4319 }
4320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004321 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004322 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004323 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004324 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004325
4326 synchronized (this) {
4327 updateEventDispatchingLocked();
4328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 }
4330
Dianne Hackborn661cd522011-08-22 00:26:20 -07004331 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004332 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004333 mWindowManager.showBootMessage(msg, always);
4334 }
4335
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004336 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004337 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004338 final long token = Binder.clearCallingIdentity();
4339 try {
4340 synchronized (this) {
4341 if (mLockScreenShown) {
4342 mLockScreenShown = false;
4343 comeOutOfSleepIfNeededLocked();
4344 }
4345 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004346 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004347 } finally {
4348 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004349 }
4350 }
4351
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004352 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004353 IntentFilter pkgFilter = new IntentFilter();
4354 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4355 pkgFilter.addDataScheme("package");
4356 mContext.registerReceiver(new BroadcastReceiver() {
4357 @Override
4358 public void onReceive(Context context, Intent intent) {
4359 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4360 if (pkgs != null) {
4361 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004362 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004363 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4364 setResultCode(Activity.RESULT_OK);
4365 return;
4366 }
4367 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004368 }
4369 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004370 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004371 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004372
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004373 synchronized (this) {
4374 // Ensure that any processes we had put on hold are now started
4375 // up.
4376 final int NP = mProcessesOnHold.size();
4377 if (NP > 0) {
4378 ArrayList<ProcessRecord> procs =
4379 new ArrayList<ProcessRecord>(mProcessesOnHold);
4380 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004381 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4382 + procs.get(ip));
4383 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004384 }
4385 }
4386
4387 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004388 // Start looking for apps that are abusing wake locks.
4389 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004390 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004391 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004392 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004393 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004394 for (int i=0; i<mStartedUsers.size(); i++) {
4395 UserStartedState uss = mStartedUsers.valueAt(i);
4396 if (uss.mState == UserStartedState.STATE_BOOTING) {
4397 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004398 final int userId = mStartedUsers.keyAt(i);
4399 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4400 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4401 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004402 null, null, 0, null, null,
4403 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004404 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004405 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004406 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004407 }
4408 }
4409 }
4410
4411 final void ensureBootCompleted() {
4412 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004413 boolean enableScreen;
4414 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004415 booting = mBooting;
4416 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004417 enableScreen = !mBooted;
4418 mBooted = true;
4419 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004420
4421 if (booting) {
4422 finishBooting();
4423 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004424
4425 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004426 enableScreenAfterBoot();
4427 }
4428 }
4429
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004430 public final void activityPaused(IBinder token) {
4431 final long origId = Binder.clearCallingIdentity();
4432 mMainStack.activityPaused(token, false);
4433 Binder.restoreCallingIdentity(origId);
4434 }
4435
4436 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4437 CharSequence description) {
4438 if (localLOGV) Slog.v(
4439 TAG, "Activity stopped: token=" + token);
4440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 // Refuse possible leaked file descriptors
4442 if (icicle != null && icicle.hasFileDescriptors()) {
4443 throw new IllegalArgumentException("File descriptors passed in Bundle");
4444 }
4445
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004446 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447
4448 final long origId = Binder.clearCallingIdentity();
4449
4450 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004451 r = mMainStack.isInStackLocked(token);
4452 if (r != null) {
4453 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 }
4455 }
4456
4457 if (r != null) {
4458 sendPendingThumbnail(r, null, null, null, false);
4459 }
4460
4461 trimApplications();
4462
4463 Binder.restoreCallingIdentity(origId);
4464 }
4465
4466 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004467 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004468 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 }
4470
4471 public String getCallingPackage(IBinder token) {
4472 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004473 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004474 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 }
4476 }
4477
4478 public ComponentName getCallingActivity(IBinder token) {
4479 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004480 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 return r != null ? r.intent.getComponent() : null;
4482 }
4483 }
4484
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004485 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004486 ActivityRecord r = mMainStack.isInStackLocked(token);
4487 if (r == null) {
4488 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004490 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004491 }
4492
4493 public ComponentName getActivityClassForToken(IBinder token) {
4494 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004495 ActivityRecord r = mMainStack.isInStackLocked(token);
4496 if (r == null) {
4497 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004499 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
4501 }
4502
4503 public String getPackageForToken(IBinder token) {
4504 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004505 ActivityRecord r = mMainStack.isInStackLocked(token);
4506 if (r == null) {
4507 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004509 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 }
4512
4513 public IIntentSender getIntentSender(int type,
4514 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004515 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004516 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004517 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004518 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004519 if (intents != null) {
4520 if (intents.length < 1) {
4521 throw new IllegalArgumentException("Intents array length must be >= 1");
4522 }
4523 for (int i=0; i<intents.length; i++) {
4524 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004525 if (intent != null) {
4526 if (intent.hasFileDescriptors()) {
4527 throw new IllegalArgumentException("File descriptors passed in Intent");
4528 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004529 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004530 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4531 throw new IllegalArgumentException(
4532 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4533 }
4534 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004535 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004536 }
4537 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004538 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004539 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004540 }
4541 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004542 if (options != null) {
4543 if (options.hasFileDescriptors()) {
4544 throw new IllegalArgumentException("File descriptors passed in options");
4545 }
4546 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004548 synchronized(this) {
4549 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004550 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4551 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004553 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004554 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004555 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4556 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 String msg = "Permission Denial: getIntentSender() from pid="
4558 + Binder.getCallingPid()
4559 + ", uid=" + Binder.getCallingUid()
4560 + ", (need uid=" + uid + ")"
4561 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004562 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 throw new SecurityException(msg);
4564 }
4565 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004566
4567 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004568 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 } catch (RemoteException e) {
4571 throw new SecurityException(e);
4572 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004573 }
4574 }
4575
Dianne Hackborn41203752012-08-31 14:05:51 -07004576 IIntentSender getIntentSenderLocked(int type, String packageName,
4577 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004578 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4579 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004580 if (DEBUG_MU)
4581 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004582 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004583 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004584 activity = mMainStack.isInStackLocked(token);
4585 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004586 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004588 if (activity.finishing) {
4589 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004590 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004591 }
4592
4593 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4594 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4595 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4596 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4597 |PendingIntent.FLAG_UPDATE_CURRENT);
4598
4599 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4600 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004601 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004602 WeakReference<PendingIntentRecord> ref;
4603 ref = mIntentSenderRecords.get(key);
4604 PendingIntentRecord rec = ref != null ? ref.get() : null;
4605 if (rec != null) {
4606 if (!cancelCurrent) {
4607 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004608 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004609 rec.key.requestIntent.replaceExtras(intents != null ?
4610 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004611 }
4612 if (intents != null) {
4613 intents[intents.length-1] = rec.key.requestIntent;
4614 rec.key.allIntents = intents;
4615 rec.key.allResolvedTypes = resolvedTypes;
4616 } else {
4617 rec.key.allIntents = null;
4618 rec.key.allResolvedTypes = null;
4619 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 return rec;
4622 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004623 rec.canceled = true;
4624 mIntentSenderRecords.remove(key);
4625 }
4626 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 return rec;
4628 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004629 rec = new PendingIntentRecord(this, key, callingUid);
4630 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004631 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004632 if (activity.pendingResults == null) {
4633 activity.pendingResults
4634 = new HashSet<WeakReference<PendingIntentRecord>>();
4635 }
4636 activity.pendingResults.add(rec.ref);
4637 }
4638 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004639 }
4640
4641 public void cancelIntentSender(IIntentSender sender) {
4642 if (!(sender instanceof PendingIntentRecord)) {
4643 return;
4644 }
4645 synchronized(this) {
4646 PendingIntentRecord rec = (PendingIntentRecord)sender;
4647 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004648 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004649 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4650 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651 String msg = "Permission Denial: cancelIntentSender() from pid="
4652 + Binder.getCallingPid()
4653 + ", uid=" + Binder.getCallingUid()
4654 + " is not allowed to cancel packges "
4655 + rec.key.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 } catch (RemoteException e) {
4660 throw new SecurityException(e);
4661 }
4662 cancelIntentSenderLocked(rec, true);
4663 }
4664 }
4665
4666 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4667 rec.canceled = true;
4668 mIntentSenderRecords.remove(rec.key);
4669 if (cleanActivity && rec.key.activity != null) {
4670 rec.key.activity.pendingResults.remove(rec.ref);
4671 }
4672 }
4673
4674 public String getPackageForIntentSender(IIntentSender pendingResult) {
4675 if (!(pendingResult instanceof PendingIntentRecord)) {
4676 return null;
4677 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004678 try {
4679 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4680 return res.key.packageName;
4681 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
4683 return null;
4684 }
4685
Christopher Tatec4a07d12012-04-06 14:19:13 -07004686 public int getUidForIntentSender(IIntentSender sender) {
4687 if (sender instanceof PendingIntentRecord) {
4688 try {
4689 PendingIntentRecord res = (PendingIntentRecord)sender;
4690 return res.uid;
4691 } catch (ClassCastException e) {
4692 }
4693 }
4694 return -1;
4695 }
4696
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004697 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4698 if (!(pendingResult instanceof PendingIntentRecord)) {
4699 return false;
4700 }
4701 try {
4702 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4703 if (res.key.allIntents == null) {
4704 return false;
4705 }
4706 for (int i=0; i<res.key.allIntents.length; i++) {
4707 Intent intent = res.key.allIntents[i];
4708 if (intent.getPackage() != null && intent.getComponent() != null) {
4709 return false;
4710 }
4711 }
4712 return true;
4713 } catch (ClassCastException e) {
4714 }
4715 return false;
4716 }
4717
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004718 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4719 if (!(pendingResult instanceof PendingIntentRecord)) {
4720 return false;
4721 }
4722 try {
4723 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4724 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4725 return true;
4726 }
4727 return false;
4728 } catch (ClassCastException e) {
4729 }
4730 return false;
4731 }
4732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 public void setProcessLimit(int max) {
4734 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4735 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004736 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004737 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004738 mProcessLimitOverride = max;
4739 }
4740 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 }
4742
4743 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004744 synchronized (this) {
4745 return mProcessLimitOverride;
4746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 }
4748
4749 void foregroundTokenDied(ForegroundToken token) {
4750 synchronized (ActivityManagerService.this) {
4751 synchronized (mPidsSelfLocked) {
4752 ForegroundToken cur
4753 = mForegroundProcesses.get(token.pid);
4754 if (cur != token) {
4755 return;
4756 }
4757 mForegroundProcesses.remove(token.pid);
4758 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4759 if (pr == null) {
4760 return;
4761 }
4762 pr.forcingToForeground = null;
4763 pr.foregroundServices = false;
4764 }
4765 updateOomAdjLocked();
4766 }
4767 }
4768
4769 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4770 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4771 "setProcessForeground()");
4772 synchronized(this) {
4773 boolean changed = false;
4774
4775 synchronized (mPidsSelfLocked) {
4776 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004777 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004778 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 return;
4780 }
4781 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4782 if (oldToken != null) {
4783 oldToken.token.unlinkToDeath(oldToken, 0);
4784 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004785 if (pr != null) {
4786 pr.forcingToForeground = null;
4787 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 changed = true;
4789 }
4790 if (isForeground && token != null) {
4791 ForegroundToken newToken = new ForegroundToken() {
4792 public void binderDied() {
4793 foregroundTokenDied(this);
4794 }
4795 };
4796 newToken.pid = pid;
4797 newToken.token = token;
4798 try {
4799 token.linkToDeath(newToken, 0);
4800 mForegroundProcesses.put(pid, newToken);
4801 pr.forcingToForeground = token;
4802 changed = true;
4803 } catch (RemoteException e) {
4804 // If the process died while doing this, we will later
4805 // do the cleanup with the process death link.
4806 }
4807 }
4808 }
4809
4810 if (changed) {
4811 updateOomAdjLocked();
4812 }
4813 }
4814 }
4815
4816 // =========================================================
4817 // PERMISSIONS
4818 // =========================================================
4819
4820 static class PermissionController extends IPermissionController.Stub {
4821 ActivityManagerService mActivityManagerService;
4822 PermissionController(ActivityManagerService activityManagerService) {
4823 mActivityManagerService = activityManagerService;
4824 }
4825
4826 public boolean checkPermission(String permission, int pid, int uid) {
4827 return mActivityManagerService.checkPermission(permission, pid,
4828 uid) == PackageManager.PERMISSION_GRANTED;
4829 }
4830 }
4831
4832 /**
4833 * This can be called with or without the global lock held.
4834 */
4835 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004836 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004837 // We might be performing an operation on behalf of an indirect binder
4838 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4839 // client identity accordingly before proceeding.
4840 Identity tlsIdentity = sCallerIdentity.get();
4841 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004842 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004843 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4844 uid = tlsIdentity.uid;
4845 pid = tlsIdentity.pid;
4846 }
4847
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004848 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004849 return PackageManager.PERMISSION_GRANTED;
4850 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004851
4852 return ActivityManager.checkComponentPermission(permission, uid,
4853 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004854 }
4855
4856 /**
4857 * As the only public entry point for permissions checking, this method
4858 * can enforce the semantic that requesting a check on a null global
4859 * permission is automatically denied. (Internally a null permission
4860 * string is used when calling {@link #checkComponentPermission} in cases
4861 * when only uid-based security is needed.)
4862 *
4863 * This can be called with or without the global lock held.
4864 */
4865 public int checkPermission(String permission, int pid, int uid) {
4866 if (permission == null) {
4867 return PackageManager.PERMISSION_DENIED;
4868 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004869 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871
4872 /**
4873 * Binder IPC calls go through the public entry point.
4874 * This can be called with or without the global lock held.
4875 */
4876 int checkCallingPermission(String permission) {
4877 return checkPermission(permission,
4878 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004879 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004880 }
4881
4882 /**
4883 * This can be called with or without the global lock held.
4884 */
4885 void enforceCallingPermission(String permission, String func) {
4886 if (checkCallingPermission(permission)
4887 == PackageManager.PERMISSION_GRANTED) {
4888 return;
4889 }
4890
4891 String msg = "Permission Denial: " + func + " from pid="
4892 + Binder.getCallingPid()
4893 + ", uid=" + Binder.getCallingUid()
4894 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004895 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 throw new SecurityException(msg);
4897 }
4898
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004899 /**
4900 * Determine if UID is holding permissions required to access {@link Uri} in
4901 * the given {@link ProviderInfo}. Final permission checking is always done
4902 * in {@link ContentProvider}.
4903 */
4904 private final boolean checkHoldingPermissionsLocked(
4905 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004906 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4907 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004908
4909 if (pi.applicationInfo.uid == uid) {
4910 return true;
4911 } else if (!pi.exported) {
4912 return false;
4913 }
4914
4915 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4916 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004917 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004918 // check if target holds top-level <provider> permissions
4919 if (!readMet && pi.readPermission != null
4920 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4921 readMet = true;
4922 }
4923 if (!writeMet && pi.writePermission != null
4924 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4925 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004927
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004928 // track if unprotected read/write is allowed; any denied
4929 // <path-permission> below removes this ability
4930 boolean allowDefaultRead = pi.readPermission == null;
4931 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004932
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004933 // check if target holds any <path-permission> that match uri
4934 final PathPermission[] pps = pi.pathPermissions;
4935 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004936 final String path = uri.getPath();
4937 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004938 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004939 i--;
4940 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004941 if (pp.match(path)) {
4942 if (!readMet) {
4943 final String pprperm = pp.getReadPermission();
4944 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4945 + pprperm + " for " + pp.getPath()
4946 + ": match=" + pp.match(path)
4947 + " check=" + pm.checkUidPermission(pprperm, uid));
4948 if (pprperm != null) {
4949 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4950 readMet = true;
4951 } else {
4952 allowDefaultRead = false;
4953 }
4954 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004955 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004956 if (!writeMet) {
4957 final String ppwperm = pp.getWritePermission();
4958 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4959 + ppwperm + " for " + pp.getPath()
4960 + ": match=" + pp.match(path)
4961 + " check=" + pm.checkUidPermission(ppwperm, uid));
4962 if (ppwperm != null) {
4963 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4964 writeMet = true;
4965 } else {
4966 allowDefaultWrite = false;
4967 }
4968 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004969 }
4970 }
4971 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004972 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004973
4974 // grant unprotected <provider> read/write, if not blocked by
4975 // <path-permission> above
4976 if (allowDefaultRead) readMet = true;
4977 if (allowDefaultWrite) writeMet = true;
4978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004979 } catch (RemoteException e) {
4980 return false;
4981 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004982
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004983 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984 }
4985
4986 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4987 int modeFlags) {
4988 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004989 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 return true;
4991 }
4992 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4993 if (perms == null) return false;
4994 UriPermission perm = perms.get(uri);
4995 if (perm == null) return false;
4996 return (modeFlags&perm.modeFlags) == modeFlags;
4997 }
4998
4999 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005000 enforceNotIsolatedCaller("checkUriPermission");
5001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 // Another redirected-binder-call permissions check as in
5003 // {@link checkComponentPermission}.
5004 Identity tlsIdentity = sCallerIdentity.get();
5005 if (tlsIdentity != null) {
5006 uid = tlsIdentity.uid;
5007 pid = tlsIdentity.pid;
5008 }
5009
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005010 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005011 // Our own process gets to do everything.
5012 if (pid == MY_PID) {
5013 return PackageManager.PERMISSION_GRANTED;
5014 }
5015 synchronized(this) {
5016 return checkUriPermissionLocked(uri, uid, modeFlags)
5017 ? PackageManager.PERMISSION_GRANTED
5018 : PackageManager.PERMISSION_DENIED;
5019 }
5020 }
5021
Dianne Hackborn39792d22010-08-19 18:01:52 -07005022 /**
5023 * Check if the targetPkg can be granted permission to access uri by
5024 * the callingUid using the given modeFlags. Throws a security exception
5025 * if callingUid is not allowed to do this. Returns the uid of the target
5026 * if the URI permission grant should be performed; returns -1 if it is not
5027 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005028 * If you already know the uid of the target, you can supply it in
5029 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005030 */
5031 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005032 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005033 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5034 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5035 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005036 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 }
5038
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005039 if (targetPkg != null) {
5040 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5041 "Checking grant " + targetPkg + " permission to " + uri);
5042 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005043
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005044 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045
5046 // If this is not a content: uri, we can't do anything with it.
5047 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005048 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005049 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005050 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005051 }
5052
5053 String name = uri.getAuthority();
5054 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005055 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005056 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 if (cpr != null) {
5058 pi = cpr.info;
5059 } else {
5060 try {
5061 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005062 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005063 } catch (RemoteException ex) {
5064 }
5065 }
5066 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005067 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
5070
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005071 int targetUid = lastTargetUid;
5072 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005073 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005074 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005075 if (targetUid < 0) {
5076 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5077 "Can't grant URI permission no uid for: " + targetPkg);
5078 return -1;
5079 }
5080 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
5084
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005085 if (targetUid >= 0) {
5086 // First... does the target actually need this permission?
5087 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5088 // No need to grant the target this permission.
5089 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5090 "Target " + targetPkg + " already has full permission to " + uri);
5091 return -1;
5092 }
5093 } else {
5094 // First... there is no target package, so can anyone access it?
5095 boolean allowed = pi.exported;
5096 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5097 if (pi.readPermission != null) {
5098 allowed = false;
5099 }
5100 }
5101 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5102 if (pi.writePermission != null) {
5103 allowed = false;
5104 }
5105 }
5106 if (allowed) {
5107 return -1;
5108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 }
5110
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005111 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 if (!pi.grantUriPermissions) {
5113 throw new SecurityException("Provider " + pi.packageName
5114 + "/" + pi.name
5115 + " does not allow granting of Uri permissions (uri "
5116 + uri + ")");
5117 }
5118 if (pi.uriPermissionPatterns != null) {
5119 final int N = pi.uriPermissionPatterns.length;
5120 boolean allowed = false;
5121 for (int i=0; i<N; i++) {
5122 if (pi.uriPermissionPatterns[i] != null
5123 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5124 allowed = true;
5125 break;
5126 }
5127 }
5128 if (!allowed) {
5129 throw new SecurityException("Provider " + pi.packageName
5130 + "/" + pi.name
5131 + " does not allow granting of permission to path of Uri "
5132 + uri);
5133 }
5134 }
5135
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005136 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005138 if (callingUid != Process.myUid()) {
5139 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5140 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5141 throw new SecurityException("Uid " + callingUid
5142 + " does not have permission to uri " + uri);
5143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145 }
5146
Dianne Hackborn39792d22010-08-19 18:01:52 -07005147 return targetUid;
5148 }
5149
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005150 public int checkGrantUriPermission(int callingUid, String targetPkg,
5151 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005152 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005153 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005154 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005155 }
5156 }
5157
Dianne Hackborn39792d22010-08-19 18:01:52 -07005158 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5159 Uri uri, int modeFlags, UriPermissionOwner owner) {
5160 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5161 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5162 if (modeFlags == 0) {
5163 return;
5164 }
5165
5166 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005167 // to the uri, and the target doesn't. Let's now give this to
5168 // the target.
5169
Joe Onorato8a9b2202010-02-26 18:56:32 -08005170 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005171 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 HashMap<Uri, UriPermission> targetUris
5174 = mGrantedUriPermissions.get(targetUid);
5175 if (targetUris == null) {
5176 targetUris = new HashMap<Uri, UriPermission>();
5177 mGrantedUriPermissions.put(targetUid, targetUris);
5178 }
5179
5180 UriPermission perm = targetUris.get(uri);
5181 if (perm == null) {
5182 perm = new UriPermission(targetUid, uri);
5183 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005186 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005187 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005189 } else {
5190 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5191 perm.readOwners.add(owner);
5192 owner.addReadPermission(perm);
5193 }
5194 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5195 perm.writeOwners.add(owner);
5196 owner.addWritePermission(perm);
5197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 }
5199 }
5200
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005201 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5202 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005203 if (targetPkg == null) {
5204 throw new NullPointerException("targetPkg");
5205 }
5206
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005207 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005208 if (targetUid < 0) {
5209 return;
5210 }
5211
5212 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5213 }
5214
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005215 static class NeededUriGrants extends ArrayList<Uri> {
5216 final String targetPkg;
5217 final int targetUid;
5218 final int flags;
5219
5220 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5221 targetPkg = _targetPkg;
5222 targetUid = _targetUid;
5223 flags = _flags;
5224 }
5225 }
5226
Dianne Hackborn39792d22010-08-19 18:01:52 -07005227 /**
5228 * Like checkGrantUriPermissionLocked, but takes an Intent.
5229 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005230 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5231 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005232 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005233 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5234 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005235 + " from " + intent + "; flags=0x"
5236 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5237
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005238 if (targetPkg == null) {
5239 throw new NullPointerException("targetPkg");
5240 }
5241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005243 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 }
5245 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005246 ClipData clip = intent.getClipData();
5247 if (data == null && clip == null) {
5248 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005249 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005250 if (data != null) {
5251 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5252 mode, needed != null ? needed.targetUid : -1);
5253 if (target > 0) {
5254 if (needed == null) {
5255 needed = new NeededUriGrants(targetPkg, target, mode);
5256 }
5257 needed.add(data);
5258 }
5259 }
5260 if (clip != null) {
5261 for (int i=0; i<clip.getItemCount(); i++) {
5262 Uri uri = clip.getItemAt(i).getUri();
5263 if (uri != null) {
5264 int target = -1;
5265 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5266 mode, needed != null ? needed.targetUid : -1);
5267 if (target > 0) {
5268 if (needed == null) {
5269 needed = new NeededUriGrants(targetPkg, target, mode);
5270 }
5271 needed.add(uri);
5272 }
5273 } else {
5274 Intent clipIntent = clip.getItemAt(i).getIntent();
5275 if (clipIntent != null) {
5276 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5277 callingUid, targetPkg, clipIntent, mode, needed);
5278 if (newNeeded != null) {
5279 needed = newNeeded;
5280 }
5281 }
5282 }
5283 }
5284 }
5285
5286 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005287 }
5288
5289 /**
5290 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5291 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005292 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5293 UriPermissionOwner owner) {
5294 if (needed != null) {
5295 for (int i=0; i<needed.size(); i++) {
5296 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5297 needed.get(i), needed.flags, owner);
5298 }
5299 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005300 }
5301
5302 void grantUriPermissionFromIntentLocked(int callingUid,
5303 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005304 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005305 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005306 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 return;
5308 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005309
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005310 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 }
5312
5313 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5314 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005315 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 synchronized(this) {
5317 final ProcessRecord r = getRecordForAppLocked(caller);
5318 if (r == null) {
5319 throw new SecurityException("Unable to find app for caller "
5320 + caller
5321 + " when granting permission to uri " + uri);
5322 }
5323 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005324 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325 }
5326 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005327 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005328 }
5329
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005330 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 null);
5332 }
5333 }
5334
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005335 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5337 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5338 HashMap<Uri, UriPermission> perms
5339 = mGrantedUriPermissions.get(perm.uid);
5340 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005341 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005342 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 perms.remove(perm.uri);
5344 if (perms.size() == 0) {
5345 mGrantedUriPermissions.remove(perm.uid);
5346 }
5347 }
5348 }
5349 }
5350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005351 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5352 int modeFlags) {
5353 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5354 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5355 if (modeFlags == 0) {
5356 return;
5357 }
5358
Joe Onorato8a9b2202010-02-26 18:56:32 -08005359 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005360 "Revoking all granted permissions to " + uri);
5361
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005362 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363
5364 final String authority = uri.getAuthority();
5365 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005366 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005367 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 if (cpr != null) {
5369 pi = cpr.info;
5370 } else {
5371 try {
5372 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005373 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005374 } catch (RemoteException ex) {
5375 }
5376 }
5377 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005378 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005379 return;
5380 }
5381
5382 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005383 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 // Right now, if you are not the original owner of the permission,
5385 // you are not allowed to revoke it.
5386 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5387 throw new SecurityException("Uid " + callingUid
5388 + " does not have permission to uri " + uri);
5389 //}
5390 }
5391
5392 // Go through all of the permissions and remove any that match.
5393 final List<String> SEGMENTS = uri.getPathSegments();
5394 if (SEGMENTS != null) {
5395 final int NS = SEGMENTS.size();
5396 int N = mGrantedUriPermissions.size();
5397 for (int i=0; i<N; i++) {
5398 HashMap<Uri, UriPermission> perms
5399 = mGrantedUriPermissions.valueAt(i);
5400 Iterator<UriPermission> it = perms.values().iterator();
5401 toploop:
5402 while (it.hasNext()) {
5403 UriPermission perm = it.next();
5404 Uri targetUri = perm.uri;
5405 if (!authority.equals(targetUri.getAuthority())) {
5406 continue;
5407 }
5408 List<String> targetSegments = targetUri.getPathSegments();
5409 if (targetSegments == null) {
5410 continue;
5411 }
5412 if (targetSegments.size() < NS) {
5413 continue;
5414 }
5415 for (int j=0; j<NS; j++) {
5416 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5417 continue toploop;
5418 }
5419 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005420 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005421 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 perm.clearModes(modeFlags);
5423 if (perm.modeFlags == 0) {
5424 it.remove();
5425 }
5426 }
5427 if (perms.size() == 0) {
5428 mGrantedUriPermissions.remove(
5429 mGrantedUriPermissions.keyAt(i));
5430 N--;
5431 i--;
5432 }
5433 }
5434 }
5435 }
5436
5437 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5438 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005439 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 synchronized(this) {
5441 final ProcessRecord r = getRecordForAppLocked(caller);
5442 if (r == null) {
5443 throw new SecurityException("Unable to find app for caller "
5444 + caller
5445 + " when revoking permission to uri " + uri);
5446 }
5447 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005448 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 return;
5450 }
5451
5452 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5453 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5454 if (modeFlags == 0) {
5455 return;
5456 }
5457
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005458 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459
5460 final String authority = uri.getAuthority();
5461 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005462 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 if (cpr != null) {
5464 pi = cpr.info;
5465 } else {
5466 try {
5467 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005468 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 } catch (RemoteException ex) {
5470 }
5471 }
5472 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005473 Slog.w(TAG, "No content provider found for permission revoke: "
5474 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 return;
5476 }
5477
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005478 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 }
5480 }
5481
Dianne Hackborn7e269642010-08-25 19:50:20 -07005482 @Override
5483 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005484 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005485 synchronized(this) {
5486 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5487 return owner.getExternalTokenLocked();
5488 }
5489 }
5490
5491 @Override
5492 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5493 Uri uri, int modeFlags) {
5494 synchronized(this) {
5495 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5496 if (owner == null) {
5497 throw new IllegalArgumentException("Unknown owner: " + token);
5498 }
5499 if (fromUid != Binder.getCallingUid()) {
5500 if (Binder.getCallingUid() != Process.myUid()) {
5501 // Only system code can grant URI permissions on behalf
5502 // of other users.
5503 throw new SecurityException("nice try");
5504 }
5505 }
5506 if (targetPkg == null) {
5507 throw new IllegalArgumentException("null target");
5508 }
5509 if (uri == null) {
5510 throw new IllegalArgumentException("null uri");
5511 }
5512
5513 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5514 }
5515 }
5516
5517 @Override
5518 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5519 synchronized(this) {
5520 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5521 if (owner == null) {
5522 throw new IllegalArgumentException("Unknown owner: " + token);
5523 }
5524
5525 if (uri == null) {
5526 owner.removeUriPermissionsLocked(mode);
5527 } else {
5528 owner.removeUriPermissionLocked(uri, mode);
5529 }
5530 }
5531 }
5532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5534 synchronized (this) {
5535 ProcessRecord app =
5536 who != null ? getRecordForAppLocked(who) : null;
5537 if (app == null) return;
5538
5539 Message msg = Message.obtain();
5540 msg.what = WAIT_FOR_DEBUGGER_MSG;
5541 msg.obj = app;
5542 msg.arg1 = waiting ? 1 : 0;
5543 mHandler.sendMessage(msg);
5544 }
5545 }
5546
5547 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005548 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5549 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005551 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005552 outInfo.threshold = homeAppMem;
5553 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5554 outInfo.hiddenAppThreshold = hiddenAppMem;
5555 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005556 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005557 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5558 ProcessList.VISIBLE_APP_ADJ);
5559 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5560 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 }
5562
5563 // =========================================================
5564 // TASK MANAGEMENT
5565 // =========================================================
5566
5567 public List getTasks(int maxNum, int flags,
5568 IThumbnailReceiver receiver) {
5569 ArrayList list = new ArrayList();
5570
5571 PendingThumbnailsRecord pending = null;
5572 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005573 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574
5575 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005576 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5578 + ", receiver=" + receiver);
5579
5580 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5581 != PackageManager.PERMISSION_GRANTED) {
5582 if (receiver != null) {
5583 // If the caller wants to wait for pending thumbnails,
5584 // it ain't gonna get them.
5585 try {
5586 receiver.finished();
5587 } catch (RemoteException ex) {
5588 }
5589 }
5590 String msg = "Permission Denial: getTasks() from pid="
5591 + Binder.getCallingPid()
5592 + ", uid=" + Binder.getCallingUid()
5593 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005594 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 throw new SecurityException(msg);
5596 }
5597
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005598 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005599 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005600 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005601 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 TaskRecord curTask = null;
5603 int numActivities = 0;
5604 int numRunning = 0;
5605 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005606 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005608 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609
5610 // Initialize state for next task if needed.
5611 if (top == null ||
5612 (top.state == ActivityState.INITIALIZING
5613 && top.task == r.task)) {
5614 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 curTask = r.task;
5616 numActivities = numRunning = 0;
5617 }
5618
5619 // Add 'r' into the current task.
5620 numActivities++;
5621 if (r.app != null && r.app.thread != null) {
5622 numRunning++;
5623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624
Joe Onorato8a9b2202010-02-26 18:56:32 -08005625 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 TAG, r.intent.getComponent().flattenToShortString()
5627 + ": task=" + r.task);
5628
5629 // If the next one is a different task, generate a new
5630 // TaskInfo entry for what we have.
5631 if (next == null || next.task != curTask) {
5632 ActivityManager.RunningTaskInfo ci
5633 = new ActivityManager.RunningTaskInfo();
5634 ci.id = curTask.taskId;
5635 ci.baseActivity = r.intent.getComponent();
5636 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005637 if (top.thumbHolder != null) {
5638 ci.description = top.thumbHolder.lastDescription;
5639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 ci.numActivities = numActivities;
5641 ci.numRunning = numRunning;
5642 //System.out.println(
5643 // "#" + maxNum + ": " + " descr=" + ci.description);
5644 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005645 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 TAG, "State=" + top.state + "Idle=" + top.idle
5647 + " app=" + top.app
5648 + " thr=" + (top.app != null ? top.app.thread : null));
5649 if (top.state == ActivityState.RESUMED
5650 || top.state == ActivityState.PAUSING) {
5651 if (top.idle && top.app != null
5652 && top.app.thread != null) {
5653 topRecord = top;
5654 topThumbnail = top.app.thread;
5655 } else {
5656 top.thumbnailNeeded = true;
5657 }
5658 }
5659 if (pending == null) {
5660 pending = new PendingThumbnailsRecord(receiver);
5661 }
5662 pending.pendingRecords.add(top);
5663 }
5664 list.add(ci);
5665 maxNum--;
5666 top = null;
5667 }
5668 }
5669
5670 if (pending != null) {
5671 mPendingThumbnails.add(pending);
5672 }
5673 }
5674
Joe Onorato8a9b2202010-02-26 18:56:32 -08005675 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676
5677 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005678 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005680 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005682 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005683 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 }
5685 }
5686
5687 if (pending == null && receiver != null) {
5688 // In this case all thumbnails were available and the client
5689 // is being asked to be told when the remaining ones come in...
5690 // which is unusually, since the top-most currently running
5691 // activity should never have a canned thumbnail! Oh well.
5692 try {
5693 receiver.finished();
5694 } catch (RemoteException ex) {
5695 }
5696 }
5697
5698 return list;
5699 }
5700
5701 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005702 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005703 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005704 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005705 // Check if the caller is holding permissions for cross-user requests.
5706 if (checkComponentPermission(
5707 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5708 Binder.getCallingPid(), callingUid, -1, true)
5709 != PackageManager.PERMISSION_GRANTED) {
5710 String msg = "Permission Denial: "
5711 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005712 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005713 + "; this requires "
5714 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5715 Slog.w(TAG, msg);
5716 throw new SecurityException(msg);
5717 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005718 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005719 userId = mCurrentUserId;
5720 }
5721 }
5722 }
5723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 synchronized (this) {
5725 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5726 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005727 final boolean detailed = checkCallingPermission(
5728 android.Manifest.permission.GET_DETAILED_TASKS)
5729 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005731 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 final int N = mRecentTasks.size();
5734 ArrayList<ActivityManager.RecentTaskInfo> res
5735 = new ArrayList<ActivityManager.RecentTaskInfo>(
5736 maxNum < N ? maxNum : N);
5737 for (int i=0; i<N && maxNum > 0; i++) {
5738 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005739 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005740 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005741 // Return the entry if desired by the caller. We always return
5742 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005743 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005744 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5745 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005746
Dianne Hackborn905577f2011-09-07 18:31:28 -07005747 if (i == 0
5748 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 || (tr.intent == null)
5750 || ((tr.intent.getFlags()
5751 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5752 ActivityManager.RecentTaskInfo rti
5753 = new ActivityManager.RecentTaskInfo();
5754 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005755 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 rti.baseIntent = new Intent(
5757 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005758 if (!detailed) {
5759 rti.baseIntent.replaceExtras((Bundle)null);
5760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005762 rti.description = tr.lastDescription;
5763
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005764 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5765 // Check whether this activity is currently available.
5766 try {
5767 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005768 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005769 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005770 continue;
5771 }
5772 } else if (rti.baseIntent != null) {
5773 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005774 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005775 continue;
5776 }
5777 }
5778 } catch (RemoteException e) {
5779 // Will never happen.
5780 }
5781 }
5782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 res.add(rti);
5784 maxNum--;
5785 }
5786 }
5787 return res;
5788 }
5789 }
5790
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005791 private TaskRecord taskForIdLocked(int id) {
5792 final int N = mRecentTasks.size();
5793 for (int i=0; i<N; i++) {
5794 TaskRecord tr = mRecentTasks.get(i);
5795 if (tr.taskId == id) {
5796 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005797 }
5798 }
5799 return null;
5800 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005801
5802 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5803 synchronized (this) {
5804 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5805 "getTaskThumbnails()");
5806 TaskRecord tr = taskForIdLocked(id);
5807 if (tr != null) {
5808 return mMainStack.getTaskThumbnailsLocked(tr);
5809 }
5810 }
5811 return null;
5812 }
5813
5814 public boolean removeSubTask(int taskId, int subTaskIndex) {
5815 synchronized (this) {
5816 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5817 "removeSubTask()");
5818 long ident = Binder.clearCallingIdentity();
5819 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005820 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5821 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005822 } finally {
5823 Binder.restoreCallingIdentity(ident);
5824 }
5825 }
5826 }
5827
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005828 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5829 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005830 Intent baseIntent = new Intent(
5831 tr.intent != null ? tr.intent : tr.affinityIntent);
5832 ComponentName component = baseIntent.getComponent();
5833 if (component == null) {
5834 Slog.w(TAG, "Now component for base intent of task: " + tr);
5835 return;
5836 }
5837
5838 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005839 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005840
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005841 if (killProcesses) {
5842 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005843 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005844 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005845 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5846 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5847 for (int i=0; i<uids.size(); i++) {
5848 ProcessRecord proc = uids.valueAt(i);
5849 if (proc.userId != tr.userId) {
5850 continue;
5851 }
5852 if (!proc.pkgList.contains(pkg)) {
5853 continue;
5854 }
5855 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005856 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005857 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005859 // Kill the running processes.
5860 for (int i=0; i<procs.size(); i++) {
5861 ProcessRecord pr = procs.get(i);
5862 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5863 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5864 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5865 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005866 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005867 Process.killProcessQuiet(pr.pid);
5868 } else {
5869 pr.waitingToKill = "remove task";
5870 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005871 }
5872 }
5873 }
5874
5875 public boolean removeTask(int taskId, int flags) {
5876 synchronized (this) {
5877 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5878 "removeTask()");
5879 long ident = Binder.clearCallingIdentity();
5880 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005881 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5882 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005883 if (r != null) {
5884 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005885 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005886 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005887 } else {
5888 TaskRecord tr = null;
5889 int i=0;
5890 while (i < mRecentTasks.size()) {
5891 TaskRecord t = mRecentTasks.get(i);
5892 if (t.taskId == taskId) {
5893 tr = t;
5894 break;
5895 }
5896 i++;
5897 }
5898 if (tr != null) {
5899 if (tr.numActivities <= 0) {
5900 // Caller is just removing a recent task that is
5901 // not actively running. That is easy!
5902 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005903 cleanUpRemovedTaskLocked(tr, flags);
5904 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005905 } else {
5906 Slog.w(TAG, "removeTask: task " + taskId
5907 + " does not have activities to remove, "
5908 + " but numActivities=" + tr.numActivities
5909 + ": " + tr);
5910 }
5911 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005912 }
5913 } finally {
5914 Binder.restoreCallingIdentity(ident);
5915 }
5916 }
5917 return false;
5918 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005920 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5921 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005922 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 TaskRecord jt = startTask;
5924
5925 // First look backwards
5926 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005927 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 if (r.task != jt) {
5929 jt = r.task;
5930 if (affinity.equals(jt.affinity)) {
5931 return j;
5932 }
5933 }
5934 }
5935
5936 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005937 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 jt = startTask;
5939 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005940 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 if (r.task != jt) {
5942 if (affinity.equals(jt.affinity)) {
5943 return j;
5944 }
5945 jt = r.task;
5946 }
5947 }
5948
5949 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005950 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 return N-1;
5952 }
5953
5954 return -1;
5955 }
5956
5957 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005958 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005960 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5962 "moveTaskToFront()");
5963
5964 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005965 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5966 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005967 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005968 return;
5969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 final long origId = Binder.clearCallingIdentity();
5971 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005972 TaskRecord tr = taskForIdLocked(task);
5973 if (tr != null) {
5974 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5975 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005977 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5978 // Caller wants the home activity moved with it. To accomplish this,
5979 // we'll just move the home task to the top first.
5980 mMainStack.moveHomeToFrontLocked();
5981 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005982 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005983 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005985 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5986 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005988 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5989 mMainStack.mUserLeaving = true;
5990 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005991 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5992 // Caller wants the home activity moved with it. To accomplish this,
5993 // we'll just move the home task to the top first.
5994 mMainStack.moveHomeToFrontLocked();
5995 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005996 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 return;
5998 }
5999 }
6000 } finally {
6001 Binder.restoreCallingIdentity(origId);
6002 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07006003 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 }
6005 }
6006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 public void moveTaskToBack(int task) {
6008 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6009 "moveTaskToBack()");
6010
6011 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006012 if (mMainStack.mResumedActivity != null
6013 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006014 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6015 Binder.getCallingUid(), "Task to back")) {
6016 return;
6017 }
6018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006020 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 Binder.restoreCallingIdentity(origId);
6022 }
6023 }
6024
6025 /**
6026 * Moves an activity, and all of the other activities within the same task, to the bottom
6027 * of the history stack. The activity's order within the task is unchanged.
6028 *
6029 * @param token A reference to the activity we wish to move
6030 * @param nonRoot If false then this only works if the activity is the root
6031 * of a task; if true it will work for any activity in a task.
6032 * @return Returns true if the move completed, false if not.
6033 */
6034 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006035 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 synchronized(this) {
6037 final long origId = Binder.clearCallingIdentity();
6038 int taskId = getTaskForActivityLocked(token, !nonRoot);
6039 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006040 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 }
6042 Binder.restoreCallingIdentity(origId);
6043 }
6044 return false;
6045 }
6046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 public void moveTaskBackwards(int task) {
6048 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6049 "moveTaskBackwards()");
6050
6051 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006052 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6053 Binder.getCallingUid(), "Task backwards")) {
6054 return;
6055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 final long origId = Binder.clearCallingIdentity();
6057 moveTaskBackwardsLocked(task);
6058 Binder.restoreCallingIdentity(origId);
6059 }
6060 }
6061
6062 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006063 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
6065
6066 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6067 synchronized(this) {
6068 return getTaskForActivityLocked(token, onlyRoot);
6069 }
6070 }
6071
6072 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006073 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 TaskRecord lastTask = null;
6075 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006076 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006077 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 if (!onlyRoot || lastTask != r.task) {
6079 return r.task.taskId;
6080 }
6081 return -1;
6082 }
6083 lastTask = r.task;
6084 }
6085
6086 return -1;
6087 }
6088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 // =========================================================
6090 // THUMBNAILS
6091 // =========================================================
6092
6093 public void reportThumbnail(IBinder token,
6094 Bitmap thumbnail, CharSequence description) {
6095 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6096 final long origId = Binder.clearCallingIdentity();
6097 sendPendingThumbnail(null, token, thumbnail, description, true);
6098 Binder.restoreCallingIdentity(origId);
6099 }
6100
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006101 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 Bitmap thumbnail, CharSequence description, boolean always) {
6103 TaskRecord task = null;
6104 ArrayList receivers = null;
6105
6106 //System.out.println("Send pending thumbnail: " + r);
6107
6108 synchronized(this) {
6109 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006110 r = mMainStack.isInStackLocked(token);
6111 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 return;
6113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006115 if (thumbnail == null && r.thumbHolder != null) {
6116 thumbnail = r.thumbHolder.lastThumbnail;
6117 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 }
6119 if (thumbnail == null && !always) {
6120 // If there is no thumbnail, and this entry is not actually
6121 // going away, then abort for now and pick up the next
6122 // thumbnail we get.
6123 return;
6124 }
6125 task = r.task;
6126
6127 int N = mPendingThumbnails.size();
6128 int i=0;
6129 while (i<N) {
6130 PendingThumbnailsRecord pr =
6131 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6132 //System.out.println("Looking in " + pr.pendingRecords);
6133 if (pr.pendingRecords.remove(r)) {
6134 if (receivers == null) {
6135 receivers = new ArrayList();
6136 }
6137 receivers.add(pr);
6138 if (pr.pendingRecords.size() == 0) {
6139 pr.finished = true;
6140 mPendingThumbnails.remove(i);
6141 N--;
6142 continue;
6143 }
6144 }
6145 i++;
6146 }
6147 }
6148
6149 if (receivers != null) {
6150 final int N = receivers.size();
6151 for (int i=0; i<N; i++) {
6152 try {
6153 PendingThumbnailsRecord pr =
6154 (PendingThumbnailsRecord)receivers.get(i);
6155 pr.receiver.newThumbnail(
6156 task != null ? task.taskId : -1, thumbnail, description);
6157 if (pr.finished) {
6158 pr.receiver.finished();
6159 }
6160 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006161 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 }
6163 }
6164 }
6165 }
6166
6167 // =========================================================
6168 // CONTENT PROVIDERS
6169 // =========================================================
6170
Jeff Brown10e89712011-07-08 18:52:57 -07006171 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6172 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006174 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006175 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006176 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 } catch (RemoteException ex) {
6178 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006179 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006180 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6181 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006183 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 for (int i=0; i<N; i++) {
6185 ProviderInfo cpi =
6186 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006187 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6188 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006189 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006190 // This is a singleton provider, but a user besides the
6191 // default user is asking to initialize a process it runs
6192 // in... well, no, it doesn't actually run in this process,
6193 // it runs in the process of the default user. Get rid of it.
6194 providers.remove(i);
6195 N--;
6196 continue;
6197 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006198
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006199 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006200 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006202 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006203 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006205 if (DEBUG_MU)
6206 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 app.pubProviders.put(cpi.name, cpr);
6208 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006209 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 }
6211 }
6212 return providers;
6213 }
6214
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006215 /**
6216 * Check if {@link ProcessRecord} has a possible chance at accessing the
6217 * given {@link ProviderInfo}. Final permission checking is always done
6218 * in {@link ContentProvider}.
6219 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006221 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006223 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006225 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006226 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 return null;
6228 }
6229 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006230 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 == PackageManager.PERMISSION_GRANTED) {
6232 return null;
6233 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006234
6235 PathPermission[] pps = cpi.pathPermissions;
6236 if (pps != null) {
6237 int i = pps.length;
6238 while (i > 0) {
6239 i--;
6240 PathPermission pp = pps[i];
6241 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006242 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006243 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006244 return null;
6245 }
6246 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006247 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006248 == PackageManager.PERMISSION_GRANTED) {
6249 return null;
6250 }
6251 }
6252 }
6253
Dianne Hackbornb424b632010-08-18 15:59:05 -07006254 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6255 if (perms != null) {
6256 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6257 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6258 return null;
6259 }
6260 }
6261 }
6262
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006263 String msg;
6264 if (!cpi.exported) {
6265 msg = "Permission Denial: opening provider " + cpi.name
6266 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6267 + ", uid=" + callingUid + ") that is not exported from uid "
6268 + cpi.applicationInfo.uid;
6269 } else {
6270 msg = "Permission Denial: opening provider " + cpi.name
6271 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6272 + ", uid=" + callingUid + ") requires "
6273 + cpi.readPermission + " or " + cpi.writePermission;
6274 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006275 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return msg;
6277 }
6278
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006279 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6280 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006281 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006282 for (int i=0; i<r.conProviders.size(); i++) {
6283 ContentProviderConnection conn = r.conProviders.get(i);
6284 if (conn.provider == cpr) {
6285 if (DEBUG_PROVIDER) Slog.v(TAG,
6286 "Adding provider requested by "
6287 + r.processName + " from process "
6288 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6289 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6290 if (stable) {
6291 conn.stableCount++;
6292 conn.numStableIncs++;
6293 } else {
6294 conn.unstableCount++;
6295 conn.numUnstableIncs++;
6296 }
6297 return conn;
6298 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006299 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006300 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6301 if (stable) {
6302 conn.stableCount = 1;
6303 conn.numStableIncs = 1;
6304 } else {
6305 conn.unstableCount = 1;
6306 conn.numUnstableIncs = 1;
6307 }
6308 cpr.connections.add(conn);
6309 r.conProviders.add(conn);
6310 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006311 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 cpr.addExternalProcessHandleLocked(externalProcessToken);
6313 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006314 }
6315
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006316 boolean decProviderCountLocked(ContentProviderConnection conn,
6317 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6318 if (conn != null) {
6319 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006320 if (DEBUG_PROVIDER) Slog.v(TAG,
6321 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006323 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006324 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6325 if (stable) {
6326 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006327 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006328 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006329 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006330 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6331 cpr.connections.remove(conn);
6332 conn.client.conProviders.remove(conn);
6333 return true;
6334 }
6335 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006336 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006337 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006338 return false;
6339 }
6340
Amith Yamasani742a6712011-05-04 14:49:28 -07006341 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006342 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006344 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 ProviderInfo cpi = null;
6346
6347 synchronized(this) {
6348 ProcessRecord r = null;
6349 if (caller != null) {
6350 r = getRecordForAppLocked(caller);
6351 if (r == null) {
6352 throw new SecurityException(
6353 "Unable to find app for caller " + caller
6354 + " (pid=" + Binder.getCallingPid()
6355 + ") when getting content provider " + name);
6356 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006357 if (r.userId != userId) {
6358 throw new SecurityException("Calling requested user " + userId
6359 + " but app is user " + r.userId);
6360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 }
6362
6363 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006364 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006365 boolean providerRunning = cpr != null;
6366 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006368 String msg;
6369 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6370 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 }
6372
6373 if (r != null && cpr.canRunHere(r)) {
6374 // This provider has been published or is in the process
6375 // of being published... but it is also allowed to run
6376 // in the caller's process, so don't make a connection
6377 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006378 ContentProviderHolder holder = cpr.newHolder(null);
6379 // don't give caller the provider object, it needs
6380 // to make its own.
6381 holder.provider = null;
6382 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 }
6384
6385 final long origId = Binder.clearCallingIdentity();
6386
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006387 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006389 conn = incProviderCountLocked(r, cpr, token, stable);
6390 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006391 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006392 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006393 // make sure to count it as being accessed and thus
6394 // back up on the LRU list. This is good because
6395 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006396 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006397 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006398 }
6399
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006400 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006401 if (false) {
6402 if (cpr.name.flattenToShortString().equals(
6403 "com.android.providers.calendar/.CalendarProvider2")) {
6404 Slog.v(TAG, "****************** KILLING "
6405 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006406 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006407 }
6408 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006409 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006410 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6411 // NOTE: there is still a race here where a signal could be
6412 // pending on the process even though we managed to update its
6413 // adj level. Not sure what to do about this, but at least
6414 // the race is now smaller.
6415 if (!success) {
6416 // Uh oh... it looks like the provider's process
6417 // has been killed on us. We need to wait for a new
6418 // process to be started, and make sure its death
6419 // doesn't kill our process.
6420 Slog.i(TAG,
6421 "Existing provider " + cpr.name.flattenToShortString()
6422 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006423 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006424 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006425 if (!lastRef) {
6426 // This wasn't the last ref our process had on
6427 // the provider... we have now been killed, bail.
6428 return null;
6429 }
6430 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006431 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 }
6434
6435 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006437
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006438 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006439 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006441 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006442 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006443 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 } catch (RemoteException ex) {
6445 }
6446 if (cpi == null) {
6447 return null;
6448 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006449 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6450 cpi.name, cpi.flags);
6451 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006452 userId = 0;
6453 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006454 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006455
Dianne Hackbornb424b632010-08-18 15:59:05 -07006456 String msg;
6457 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6458 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 }
6460
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006461 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006462 && !cpi.processName.equals("system")) {
6463 // If this content provider does not run in the system
6464 // process, and the system is not yet ready to run other
6465 // processes, then fail fast instead of hanging.
6466 throw new IllegalArgumentException(
6467 "Attempt to launch content provider before system ready");
6468 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006469
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006470 // Make sure that the user who owns this provider is started. If not,
6471 // we don't want to allow it to run.
6472 if (mStartedUsers.get(userId) == null) {
6473 Slog.w(TAG, "Unable to launch app "
6474 + cpi.applicationInfo.packageName + "/"
6475 + cpi.applicationInfo.uid + " for provider "
6476 + name + ": user " + userId + " is stopped");
6477 return null;
6478 }
6479
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006480 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006481 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 final boolean firstClass = cpr == null;
6483 if (firstClass) {
6484 try {
6485 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006486 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 getApplicationInfo(
6488 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006489 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006491 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 + cpi.name);
6493 return null;
6494 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006495 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006496 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 } catch (RemoteException ex) {
6498 // pm is in same process, this will never happen.
6499 }
6500 }
6501
6502 if (r != null && cpr.canRunHere(r)) {
6503 // If this is a multiprocess provider, then just return its
6504 // info and allow the caller to instantiate it. Only do
6505 // this if the provider is the same user as the caller's
6506 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006507 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 }
6509
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006510 if (DEBUG_PROVIDER) {
6511 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006512 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006513 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 }
6515
6516 // This is single process, and our app is now connecting to it.
6517 // See if we are already in the process of launching this
6518 // provider.
6519 final int N = mLaunchingProviders.size();
6520 int i;
6521 for (i=0; i<N; i++) {
6522 if (mLaunchingProviders.get(i) == cpr) {
6523 break;
6524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526
6527 // If the provider is not already being launched, then get it
6528 // started.
6529 if (i >= N) {
6530 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006531
6532 try {
6533 // Content provider is now in use, its package can't be stopped.
6534 try {
6535 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006536 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006537 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006538 } catch (IllegalArgumentException e) {
6539 Slog.w(TAG, "Failed trying to unstop package "
6540 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006541 }
6542
6543 ProcessRecord proc = startProcessLocked(cpi.processName,
6544 cpr.appInfo, false, 0, "content provider",
6545 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006546 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006547 if (proc == null) {
6548 Slog.w(TAG, "Unable to launch app "
6549 + cpi.applicationInfo.packageName + "/"
6550 + cpi.applicationInfo.uid + " for provider "
6551 + name + ": process is bad");
6552 return null;
6553 }
6554 cpr.launchingApp = proc;
6555 mLaunchingProviders.add(cpr);
6556 } finally {
6557 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 }
6560
6561 // Make sure the provider is published (the same provider class
6562 // may be published under multiple names).
6563 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006564 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006566
Amith Yamasani742a6712011-05-04 14:49:28 -07006567 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006568 conn = incProviderCountLocked(r, cpr, token, stable);
6569 if (conn != null) {
6570 conn.waiting = true;
6571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
6573 }
6574
6575 // Wait for the provider to be published...
6576 synchronized (cpr) {
6577 while (cpr.provider == null) {
6578 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006579 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 + cpi.applicationInfo.packageName + "/"
6581 + cpi.applicationInfo.uid + " for provider "
6582 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006583 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 cpi.applicationInfo.packageName,
6585 cpi.applicationInfo.uid, name);
6586 return null;
6587 }
6588 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006589 if (DEBUG_MU) {
6590 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6591 + cpr.launchingApp);
6592 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006593 if (conn != null) {
6594 conn.waiting = true;
6595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 cpr.wait();
6597 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006598 } finally {
6599 if (conn != null) {
6600 conn.waiting = false;
6601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 }
6603 }
6604 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006605 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607
6608 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006609 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006610 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 if (caller == null) {
6612 String msg = "null IApplicationThread when getting content provider "
6613 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006614 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 throw new SecurityException(msg);
6616 }
6617
Dianne Hackborn41203752012-08-31 14:05:51 -07006618 return getContentProviderImpl(caller, name, null, stable,
6619 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006622 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6623 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6624 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006625 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006626 }
6627
Dianne Hackborn41203752012-08-31 14:05:51 -07006628 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6629 IBinder token, int userId) {
6630 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 }
6632
6633 /**
6634 * Drop a content provider from a ProcessRecord's bookkeeping
6635 * @param cpr
6636 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006637 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006638 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006639 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006640 ContentProviderConnection conn;
6641 try {
6642 conn = (ContentProviderConnection)connection;
6643 } catch (ClassCastException e) {
6644 String msg ="removeContentProvider: " + connection
6645 + " not a ContentProviderConnection";
6646 Slog.w(TAG, msg);
6647 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006648 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006649 if (conn == null) {
6650 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006652 if (decProviderCountLocked(conn, null, null, stable)) {
6653 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006655 }
6656 }
6657
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006658 public void removeContentProviderExternal(String name, IBinder token) {
6659 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6660 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006661 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006662 }
6663
Dianne Hackborn41203752012-08-31 14:05:51 -07006664 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006666 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 if(cpr == null) {
6668 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006669 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 return;
6671 }
6672
6673 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006674 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006675 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006676 if (localCpr.hasExternalProcessHandles()) {
6677 if (localCpr.removeExternalProcessHandleLocked(token)) {
6678 updateOomAdjLocked();
6679 } else {
6680 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6681 + " with no external reference for token: "
6682 + token + ".");
6683 }
6684 } else {
6685 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6686 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 }
6689 }
6690
6691 public final void publishContentProviders(IApplicationThread caller,
6692 List<ContentProviderHolder> providers) {
6693 if (providers == null) {
6694 return;
6695 }
6696
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006697 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006698 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006700 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006701 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 if (r == null) {
6703 throw new SecurityException(
6704 "Unable to find app for caller " + caller
6705 + " (pid=" + Binder.getCallingPid()
6706 + ") when publishing content providers");
6707 }
6708
6709 final long origId = Binder.clearCallingIdentity();
6710
6711 final int N = providers.size();
6712 for (int i=0; i<N; i++) {
6713 ContentProviderHolder src = providers.get(i);
6714 if (src == null || src.info == null || src.provider == null) {
6715 continue;
6716 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006717 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006718 if (DEBUG_MU)
6719 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006721 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006722 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 String names[] = dst.info.authority.split(";");
6724 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006725 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 }
6727
6728 int NL = mLaunchingProviders.size();
6729 int j;
6730 for (j=0; j<NL; j++) {
6731 if (mLaunchingProviders.get(j) == dst) {
6732 mLaunchingProviders.remove(j);
6733 j--;
6734 NL--;
6735 }
6736 }
6737 synchronized (dst) {
6738 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006739 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 dst.notifyAll();
6741 }
6742 updateOomAdjLocked(r);
6743 }
6744 }
6745
6746 Binder.restoreCallingIdentity(origId);
6747 }
6748 }
6749
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006750 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6751 ContentProviderConnection conn;
6752 try {
6753 conn = (ContentProviderConnection)connection;
6754 } catch (ClassCastException e) {
6755 String msg ="refContentProvider: " + connection
6756 + " not a ContentProviderConnection";
6757 Slog.w(TAG, msg);
6758 throw new IllegalArgumentException(msg);
6759 }
6760 if (conn == null) {
6761 throw new NullPointerException("connection is null");
6762 }
6763
6764 synchronized (this) {
6765 if (stable > 0) {
6766 conn.numStableIncs += stable;
6767 }
6768 stable = conn.stableCount + stable;
6769 if (stable < 0) {
6770 throw new IllegalStateException("stableCount < 0: " + stable);
6771 }
6772
6773 if (unstable > 0) {
6774 conn.numUnstableIncs += unstable;
6775 }
6776 unstable = conn.unstableCount + unstable;
6777 if (unstable < 0) {
6778 throw new IllegalStateException("unstableCount < 0: " + unstable);
6779 }
6780
6781 if ((stable+unstable) <= 0) {
6782 throw new IllegalStateException("ref counts can't go to zero here: stable="
6783 + stable + " unstable=" + unstable);
6784 }
6785 conn.stableCount = stable;
6786 conn.unstableCount = unstable;
6787 return !conn.dead;
6788 }
6789 }
6790
6791 public void unstableProviderDied(IBinder connection) {
6792 ContentProviderConnection conn;
6793 try {
6794 conn = (ContentProviderConnection)connection;
6795 } catch (ClassCastException e) {
6796 String msg ="refContentProvider: " + connection
6797 + " not a ContentProviderConnection";
6798 Slog.w(TAG, msg);
6799 throw new IllegalArgumentException(msg);
6800 }
6801 if (conn == null) {
6802 throw new NullPointerException("connection is null");
6803 }
6804
6805 // Safely retrieve the content provider associated with the connection.
6806 IContentProvider provider;
6807 synchronized (this) {
6808 provider = conn.provider.provider;
6809 }
6810
6811 if (provider == null) {
6812 // Um, yeah, we're way ahead of you.
6813 return;
6814 }
6815
6816 // Make sure the caller is being honest with us.
6817 if (provider.asBinder().pingBinder()) {
6818 // Er, no, still looks good to us.
6819 synchronized (this) {
6820 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6821 + " says " + conn + " died, but we don't agree");
6822 return;
6823 }
6824 }
6825
6826 // Well look at that! It's dead!
6827 synchronized (this) {
6828 if (conn.provider.provider != provider) {
6829 // But something changed... good enough.
6830 return;
6831 }
6832
6833 ProcessRecord proc = conn.provider.proc;
6834 if (proc == null || proc.thread == null) {
6835 // Seems like the process is already cleaned up.
6836 return;
6837 }
6838
6839 // As far as we're concerned, this is just like receiving a
6840 // death notification... just a bit prematurely.
6841 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6842 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006843 final long ident = Binder.clearCallingIdentity();
6844 try {
6845 appDiedLocked(proc, proc.pid, proc.thread);
6846 } finally {
6847 Binder.restoreCallingIdentity(ident);
6848 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006849 }
6850 }
6851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006853 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006854 synchronized (mSelf) {
6855 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6856 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006857 if (providers != null) {
6858 for (int i=providers.size()-1; i>=0; i--) {
6859 ProviderInfo pi = (ProviderInfo)providers.get(i);
6860 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6861 Slog.w(TAG, "Not installing system proc provider " + pi.name
6862 + ": not system .apk");
6863 providers.remove(i);
6864 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006865 }
6866 }
6867 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006868 if (providers != null) {
6869 mSystemThread.installSystemProviders(providers);
6870 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006871
6872 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006873
6874 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 }
6876
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006877 /**
6878 * Allows app to retrieve the MIME type of a URI without having permission
6879 * to access its content provider.
6880 *
6881 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6882 *
6883 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6884 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6885 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006886 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006887 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006888 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6889 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006890 final String name = uri.getAuthority();
6891 final long ident = Binder.clearCallingIdentity();
6892 ContentProviderHolder holder = null;
6893
6894 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006895 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006896 if (holder != null) {
6897 return holder.provider.getType(uri);
6898 }
6899 } catch (RemoteException e) {
6900 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6901 return null;
6902 } finally {
6903 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006904 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006905 }
6906 Binder.restoreCallingIdentity(ident);
6907 }
6908
6909 return null;
6910 }
6911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006912 // =========================================================
6913 // GLOBAL MANAGEMENT
6914 // =========================================================
6915
6916 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006917 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 String proc = customProcess != null ? customProcess : info.processName;
6919 BatteryStatsImpl.Uid.Proc ps = null;
6920 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006921 int uid = info.uid;
6922 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006923 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006924 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6925 uid = 0;
6926 while (true) {
6927 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6928 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6929 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6930 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006931 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006932 mNextIsolatedProcessUid++;
6933 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6934 // No process for this uid, use it.
6935 break;
6936 }
6937 stepsLeft--;
6938 if (stepsLeft <= 0) {
6939 return null;
6940 }
6941 }
6942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943 synchronized (stats) {
6944 ps = stats.getProcessStatsLocked(info.uid, proc);
6945 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006946 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 }
6948
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006949 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6950 ProcessRecord app;
6951 if (!isolated) {
6952 app = getProcessRecordLocked(info.processName, info.uid);
6953 } else {
6954 app = null;
6955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006956
6957 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006958 app = newProcessRecordLocked(null, info, null, isolated);
6959 mProcessNames.put(info.processName, app.uid, app);
6960 if (isolated) {
6961 mIsolatedProcesses.put(app.uid, app);
6962 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006963 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 }
6965
Dianne Hackborne7f97212011-02-24 14:40:20 -08006966 // This package really, really can not be stopped.
6967 try {
6968 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006969 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006970 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006971 } catch (IllegalArgumentException e) {
6972 Slog.w(TAG, "Failed trying to unstop package "
6973 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006974 }
6975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006976 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6977 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6978 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006979 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 }
6981 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6982 mPersistentStartingProcesses.add(app);
6983 startProcessLocked(app, "added application", app.processName);
6984 }
6985
6986 return app;
6987 }
6988
6989 public void unhandledBack() {
6990 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6991 "unhandledBack()");
6992
6993 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006994 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006995 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 TAG, "Performing unhandledBack(): stack size = " + count);
6997 if (count > 1) {
6998 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006999 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007000 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 Binder.restoreCallingIdentity(origId);
7002 }
7003 }
7004 }
7005
7006 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007007 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07007008 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007009 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07007010 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 ParcelFileDescriptor pfd = null;
7012 if (cph != null) {
7013 // We record the binder invoker's uid in thread-local storage before
7014 // going to the content provider to open the file. Later, in the code
7015 // that handles all permissions checks, we look for this uid and use
7016 // that rather than the Activity Manager's own uid. The effect is that
7017 // we do the check against the caller's permissions even though it looks
7018 // to the content provider like the Activity Manager itself is making
7019 // the request.
7020 sCallerIdentity.set(new Identity(
7021 Binder.getCallingPid(), Binder.getCallingUid()));
7022 try {
7023 pfd = cph.provider.openFile(uri, "r");
7024 } catch (FileNotFoundException e) {
7025 // do nothing; pfd will be returned null
7026 } finally {
7027 // Ensure that whatever happens, we clean up the identity state
7028 sCallerIdentity.remove();
7029 }
7030
7031 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007032 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007034 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
7036 return pfd;
7037 }
7038
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007039 // Actually is sleeping or shutting down or whatever else in the future
7040 // is an inactive state.
7041 public boolean isSleeping() {
7042 return mSleeping || mShuttingDown;
7043 }
7044
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007045 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007046 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7047 != PackageManager.PERMISSION_GRANTED) {
7048 throw new SecurityException("Requires permission "
7049 + android.Manifest.permission.DEVICE_POWER);
7050 }
7051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007053 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007054 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007056 if (!mSleeping) {
7057 mSleeping = true;
7058 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007059
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007060 // Initialize the wake times of all processes.
7061 checkExcessivePowerUsageLocked(false);
7062 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7063 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7064 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 }
7067 }
7068
Dianne Hackborn55280a92009-05-07 15:53:46 -07007069 public boolean shutdown(int timeout) {
7070 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7071 != PackageManager.PERMISSION_GRANTED) {
7072 throw new SecurityException("Requires permission "
7073 + android.Manifest.permission.SHUTDOWN);
7074 }
7075
7076 boolean timedout = false;
7077
7078 synchronized(this) {
7079 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007080 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007081
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007082 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007083 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007084 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007085 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007086 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007087 long delay = endTime - System.currentTimeMillis();
7088 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007089 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007090 timedout = true;
7091 break;
7092 }
7093 try {
7094 this.wait();
7095 } catch (InterruptedException e) {
7096 }
7097 }
7098 }
7099 }
7100
7101 mUsageStatsService.shutdown();
7102 mBatteryStatsService.shutdown();
7103
7104 return timedout;
7105 }
7106
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007107 public final void activitySlept(IBinder token) {
7108 if (localLOGV) Slog.v(
7109 TAG, "Activity slept: token=" + token);
7110
7111 ActivityRecord r = null;
7112
7113 final long origId = Binder.clearCallingIdentity();
7114
7115 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007116 r = mMainStack.isInStackLocked(token);
7117 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007118 mMainStack.activitySleptLocked(r);
7119 }
7120 }
7121
7122 Binder.restoreCallingIdentity(origId);
7123 }
7124
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007125 private void comeOutOfSleepIfNeededLocked() {
7126 if (!mWentToSleep && !mLockScreenShown) {
7127 if (mSleeping) {
7128 mSleeping = false;
7129 mMainStack.awakeFromSleepingLocked();
7130 mMainStack.resumeTopActivityLocked(null);
7131 }
7132 }
7133 }
7134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007136 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7137 != PackageManager.PERMISSION_GRANTED) {
7138 throw new SecurityException("Requires permission "
7139 + android.Manifest.permission.DEVICE_POWER);
7140 }
7141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007143 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007144 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007145 comeOutOfSleepIfNeededLocked();
7146 }
7147 }
7148
Jeff Brownc042ee22012-05-08 13:03:42 -07007149 private void updateEventDispatchingLocked() {
7150 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7151 }
7152
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007153 public void setLockScreenShown(boolean shown) {
7154 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7155 != PackageManager.PERMISSION_GRANTED) {
7156 throw new SecurityException("Requires permission "
7157 + android.Manifest.permission.DEVICE_POWER);
7158 }
7159
7160 synchronized(this) {
7161 mLockScreenShown = shown;
7162 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 }
7164 }
7165
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007166 public void stopAppSwitches() {
7167 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7168 != PackageManager.PERMISSION_GRANTED) {
7169 throw new SecurityException("Requires permission "
7170 + android.Manifest.permission.STOP_APP_SWITCHES);
7171 }
7172
7173 synchronized(this) {
7174 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7175 + APP_SWITCH_DELAY_TIME;
7176 mDidAppSwitch = false;
7177 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7178 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7179 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7180 }
7181 }
7182
7183 public void resumeAppSwitches() {
7184 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7185 != PackageManager.PERMISSION_GRANTED) {
7186 throw new SecurityException("Requires permission "
7187 + android.Manifest.permission.STOP_APP_SWITCHES);
7188 }
7189
7190 synchronized(this) {
7191 // Note that we don't execute any pending app switches... we will
7192 // let those wait until either the timeout, or the next start
7193 // activity request.
7194 mAppSwitchesAllowedTime = 0;
7195 }
7196 }
7197
7198 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7199 String name) {
7200 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7201 return true;
7202 }
7203
7204 final int perm = checkComponentPermission(
7205 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007206 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007207 if (perm == PackageManager.PERMISSION_GRANTED) {
7208 return true;
7209 }
7210
Joe Onorato8a9b2202010-02-26 18:56:32 -08007211 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007212 return false;
7213 }
7214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 public void setDebugApp(String packageName, boolean waitForDebugger,
7216 boolean persistent) {
7217 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7218 "setDebugApp()");
7219
7220 // Note that this is not really thread safe if there are multiple
7221 // callers into it at the same time, but that's not a situation we
7222 // care about.
7223 if (persistent) {
7224 final ContentResolver resolver = mContext.getContentResolver();
7225 Settings.System.putString(
7226 resolver, Settings.System.DEBUG_APP,
7227 packageName);
7228 Settings.System.putInt(
7229 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7230 waitForDebugger ? 1 : 0);
7231 }
7232
7233 synchronized (this) {
7234 if (!persistent) {
7235 mOrigDebugApp = mDebugApp;
7236 mOrigWaitForDebugger = mWaitForDebugger;
7237 }
7238 mDebugApp = packageName;
7239 mWaitForDebugger = waitForDebugger;
7240 mDebugTransient = !persistent;
7241 if (packageName != null) {
7242 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007243 forceStopPackageLocked(packageName, -1, false, false, true, true,
7244 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 Binder.restoreCallingIdentity(origId);
7246 }
7247 }
7248 }
7249
Siva Velusamy92a8b222012-03-09 16:24:04 -08007250 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7251 synchronized (this) {
7252 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7253 if (!isDebuggable) {
7254 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7255 throw new SecurityException("Process not debuggable: " + app.packageName);
7256 }
7257 }
7258
7259 mOpenGlTraceApp = processName;
7260 }
7261 }
7262
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007263 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7264 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7265 synchronized (this) {
7266 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7267 if (!isDebuggable) {
7268 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7269 throw new SecurityException("Process not debuggable: " + app.packageName);
7270 }
7271 }
7272 mProfileApp = processName;
7273 mProfileFile = profileFile;
7274 if (mProfileFd != null) {
7275 try {
7276 mProfileFd.close();
7277 } catch (IOException e) {
7278 }
7279 mProfileFd = null;
7280 }
7281 mProfileFd = profileFd;
7282 mProfileType = 0;
7283 mAutoStopProfiler = autoStopProfiler;
7284 }
7285 }
7286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 public void setAlwaysFinish(boolean enabled) {
7288 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7289 "setAlwaysFinish()");
7290
7291 Settings.System.putInt(
7292 mContext.getContentResolver(),
7293 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7294
7295 synchronized (this) {
7296 mAlwaysFinishActivities = enabled;
7297 }
7298 }
7299
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007300 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007301 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007302 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007303 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007304 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 }
7306 }
7307
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007308 public boolean isUserAMonkey() {
7309 // For now the fact that there is a controller implies
7310 // we have a monkey.
7311 synchronized (this) {
7312 return mController != null;
7313 }
7314 }
7315
Jeff Sharkeya4620792011-05-20 15:29:23 -07007316 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007317 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7318 "registerProcessObserver()");
7319 synchronized (this) {
7320 mProcessObservers.register(observer);
7321 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007322 }
7323
7324 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007325 synchronized (this) {
7326 mProcessObservers.unregister(observer);
7327 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007328 }
7329
Daniel Sandler69a48172010-06-23 16:29:36 -04007330 public void setImmersive(IBinder token, boolean immersive) {
7331 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007332 ActivityRecord r = mMainStack.isInStackLocked(token);
7333 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007334 throw new IllegalArgumentException();
7335 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007336 r.immersive = immersive;
7337 }
7338 }
7339
7340 public boolean isImmersive(IBinder token) {
7341 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007342 ActivityRecord r = mMainStack.isInStackLocked(token);
7343 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007344 throw new IllegalArgumentException();
7345 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007346 return r.immersive;
7347 }
7348 }
7349
7350 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007351 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007352 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007353 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007354 return (r != null) ? r.immersive : false;
7355 }
7356 }
7357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007358 public final void enterSafeMode() {
7359 synchronized(this) {
7360 // It only makes sense to do this before the system is ready
7361 // and started launching other packages.
7362 if (!mSystemReady) {
7363 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007364 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007365 } catch (RemoteException e) {
7366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 }
7368 }
7369 }
7370
Jeff Brownb09abc12011-01-13 21:08:27 -08007371 public final void showSafeModeOverlay() {
7372 View v = LayoutInflater.from(mContext).inflate(
7373 com.android.internal.R.layout.safe_mode, null);
7374 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7375 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7376 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7377 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007378 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007379 lp.format = v.getBackground().getOpacity();
7380 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7381 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7382 ((WindowManager)mContext.getSystemService(
7383 Context.WINDOW_SERVICE)).addView(v, lp);
7384 }
7385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 public void noteWakeupAlarm(IIntentSender sender) {
7387 if (!(sender instanceof PendingIntentRecord)) {
7388 return;
7389 }
7390 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7391 synchronized (stats) {
7392 if (mBatteryStatsService.isOnBattery()) {
7393 mBatteryStatsService.enforceCallingPermission();
7394 PendingIntentRecord rec = (PendingIntentRecord)sender;
7395 int MY_UID = Binder.getCallingUid();
7396 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7397 BatteryStatsImpl.Uid.Pkg pkg =
7398 stats.getPackageStatsLocked(uid, rec.key.packageName);
7399 pkg.incWakeupsLocked();
7400 }
7401 }
7402 }
7403
Dianne Hackborn64825172011-03-02 21:32:58 -08007404 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007406 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007408 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007409 // XXX Note: don't acquire main activity lock here, because the window
7410 // manager calls in with its locks held.
7411
7412 boolean killed = false;
7413 synchronized (mPidsSelfLocked) {
7414 int[] types = new int[pids.length];
7415 int worstType = 0;
7416 for (int i=0; i<pids.length; i++) {
7417 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7418 if (proc != null) {
7419 int type = proc.setAdj;
7420 types[i] = type;
7421 if (type > worstType) {
7422 worstType = type;
7423 }
7424 }
7425 }
7426
Dianne Hackborn64825172011-03-02 21:32:58 -08007427 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007429 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7430 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007431 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007432 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007433
7434 // If this is not a secure call, don't let it kill processes that
7435 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007436 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7437 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007438 }
7439
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007440 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 for (int i=0; i<pids.length; i++) {
7442 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7443 if (proc == null) {
7444 continue;
7445 }
7446 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007447 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007448 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007449 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7450 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007452 proc.killedBackground = true;
7453 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007454 }
7455 }
7456 }
7457 return killed;
7458 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007459
7460 @Override
7461 public boolean killProcessesBelowForeground(String reason) {
7462 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7463 throw new SecurityException("killProcessesBelowForeground() only available to system");
7464 }
7465
7466 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7467 }
7468
7469 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7470 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7471 throw new SecurityException("killProcessesBelowAdj() only available to system");
7472 }
7473
7474 boolean killed = false;
7475 synchronized (mPidsSelfLocked) {
7476 final int size = mPidsSelfLocked.size();
7477 for (int i = 0; i < size; i++) {
7478 final int pid = mPidsSelfLocked.keyAt(i);
7479 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7480 if (proc == null) continue;
7481
7482 final int adj = proc.setAdj;
7483 if (adj > belowAdj && !proc.killedBackground) {
7484 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7485 EventLog.writeEvent(
7486 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7487 killed = true;
7488 proc.killedBackground = true;
7489 Process.killProcessQuiet(pid);
7490 }
7491 }
7492 }
7493 return killed;
7494 }
7495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 public final void startRunning(String pkg, String cls, String action,
7497 String data) {
7498 synchronized(this) {
7499 if (mStartRunning) {
7500 return;
7501 }
7502 mStartRunning = true;
7503 mTopComponent = pkg != null && cls != null
7504 ? new ComponentName(pkg, cls) : null;
7505 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7506 mTopData = data;
7507 if (!mSystemReady) {
7508 return;
7509 }
7510 }
7511
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007512 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007513 }
7514
7515 private void retrieveSettings() {
7516 final ContentResolver resolver = mContext.getContentResolver();
7517 String debugApp = Settings.System.getString(
7518 resolver, Settings.System.DEBUG_APP);
7519 boolean waitForDebugger = Settings.System.getInt(
7520 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7521 boolean alwaysFinishActivities = Settings.System.getInt(
7522 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7523
7524 Configuration configuration = new Configuration();
7525 Settings.System.getConfiguration(resolver, configuration);
7526
7527 synchronized (this) {
7528 mDebugApp = mOrigDebugApp = debugApp;
7529 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7530 mAlwaysFinishActivities = alwaysFinishActivities;
7531 // This happens before any activities are started, so we can
7532 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007533 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007534 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 }
7536 }
7537
7538 public boolean testIsSystemReady() {
7539 // no need to synchronize(this) just to read & return the value
7540 return mSystemReady;
7541 }
7542
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007543 private static File getCalledPreBootReceiversFile() {
7544 File dataDir = Environment.getDataDirectory();
7545 File systemDir = new File(dataDir, "system");
7546 File fname = new File(systemDir, "called_pre_boots.dat");
7547 return fname;
7548 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007549
7550 static final int LAST_DONE_VERSION = 10000;
7551
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007552 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7553 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7554 File file = getCalledPreBootReceiversFile();
7555 FileInputStream fis = null;
7556 try {
7557 fis = new FileInputStream(file);
7558 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007559 int fvers = dis.readInt();
7560 if (fvers == LAST_DONE_VERSION) {
7561 String vers = dis.readUTF();
7562 String codename = dis.readUTF();
7563 String build = dis.readUTF();
7564 if (android.os.Build.VERSION.RELEASE.equals(vers)
7565 && android.os.Build.VERSION.CODENAME.equals(codename)
7566 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7567 int num = dis.readInt();
7568 while (num > 0) {
7569 num--;
7570 String pkg = dis.readUTF();
7571 String cls = dis.readUTF();
7572 lastDoneReceivers.add(new ComponentName(pkg, cls));
7573 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007574 }
7575 }
7576 } catch (FileNotFoundException e) {
7577 } catch (IOException e) {
7578 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7579 } finally {
7580 if (fis != null) {
7581 try {
7582 fis.close();
7583 } catch (IOException e) {
7584 }
7585 }
7586 }
7587 return lastDoneReceivers;
7588 }
7589
7590 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7591 File file = getCalledPreBootReceiversFile();
7592 FileOutputStream fos = null;
7593 DataOutputStream dos = null;
7594 try {
7595 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7596 fos = new FileOutputStream(file);
7597 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007598 dos.writeInt(LAST_DONE_VERSION);
7599 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007600 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007601 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007602 dos.writeInt(list.size());
7603 for (int i=0; i<list.size(); i++) {
7604 dos.writeUTF(list.get(i).getPackageName());
7605 dos.writeUTF(list.get(i).getClassName());
7606 }
7607 } catch (IOException e) {
7608 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7609 file.delete();
7610 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007611 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007612 if (dos != null) {
7613 try {
7614 dos.close();
7615 } catch (IOException e) {
7616 // TODO Auto-generated catch block
7617 e.printStackTrace();
7618 }
7619 }
7620 }
7621 }
7622
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007623 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 synchronized(this) {
7625 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007626 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 return;
7628 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007629
7630 // Check to see if there are any update receivers to run.
7631 if (!mDidUpdate) {
7632 if (mWaitingUpdate) {
7633 return;
7634 }
7635 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7636 List<ResolveInfo> ris = null;
7637 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007638 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007639 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007640 } catch (RemoteException e) {
7641 }
7642 if (ris != null) {
7643 for (int i=ris.size()-1; i>=0; i--) {
7644 if ((ris.get(i).activityInfo.applicationInfo.flags
7645 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7646 ris.remove(i);
7647 }
7648 }
7649 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007650
7651 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7652
7653 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007654 for (int i=0; i<ris.size(); i++) {
7655 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007656 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7657 if (lastDoneReceivers.contains(comp)) {
7658 ris.remove(i);
7659 i--;
7660 }
7661 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007662
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007663 for (int i=0; i<ris.size(); i++) {
7664 ActivityInfo ai = ris.get(i).activityInfo;
7665 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7666 doneReceivers.add(comp);
7667 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007668 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007669 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007670 finisher = new IIntentReceiver.Stub() {
7671 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007672 String data, Bundle extras, boolean ordered,
Dianne Hackborn20e80982012-08-31 19:00:44 -07007673 boolean sticky, int sendingUser) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007674 // The raw IIntentReceiver interface is called
7675 // with the AM lock held, so redispatch to
7676 // execute our code without the lock.
7677 mHandler.post(new Runnable() {
7678 public void run() {
7679 synchronized (ActivityManagerService.this) {
7680 mDidUpdate = true;
7681 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007682 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007683 showBootMessage(mContext.getText(
7684 R.string.android_upgrading_complete),
7685 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007686 systemReady(goingCallback);
7687 }
7688 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007689 }
7690 };
7691 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007692 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007693 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007694 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007695 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007696 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007697 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007698 mWaitingUpdate = true;
7699 }
7700 }
7701 }
7702 if (mWaitingUpdate) {
7703 return;
7704 }
7705 mDidUpdate = true;
7706 }
7707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 mSystemReady = true;
7709 if (!mStartRunning) {
7710 return;
7711 }
7712 }
7713
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007714 ArrayList<ProcessRecord> procsToKill = null;
7715 synchronized(mPidsSelfLocked) {
7716 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7717 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7718 if (!isAllowedWhileBooting(proc.info)){
7719 if (procsToKill == null) {
7720 procsToKill = new ArrayList<ProcessRecord>();
7721 }
7722 procsToKill.add(proc);
7723 }
7724 }
7725 }
7726
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007727 synchronized(this) {
7728 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007729 for (int i=procsToKill.size()-1; i>=0; i--) {
7730 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007731 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007732 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007733 }
7734 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007735
7736 // Now that we have cleaned up any update processes, we
7737 // are ready to start launching real processes and know that
7738 // we won't trample on them any more.
7739 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007740 }
7741
Joe Onorato8a9b2202010-02-26 18:56:32 -08007742 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007743 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007744 SystemClock.uptimeMillis());
7745
7746 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007747 // Make sure we have no pre-ready processes sitting around.
7748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7750 ResolveInfo ri = mContext.getPackageManager()
7751 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007752 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 CharSequence errorMsg = null;
7754 if (ri != null) {
7755 ActivityInfo ai = ri.activityInfo;
7756 ApplicationInfo app = ai.applicationInfo;
7757 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7758 mTopAction = Intent.ACTION_FACTORY_TEST;
7759 mTopData = null;
7760 mTopComponent = new ComponentName(app.packageName,
7761 ai.name);
7762 } else {
7763 errorMsg = mContext.getResources().getText(
7764 com.android.internal.R.string.factorytest_not_system);
7765 }
7766 } else {
7767 errorMsg = mContext.getResources().getText(
7768 com.android.internal.R.string.factorytest_no_action);
7769 }
7770 if (errorMsg != null) {
7771 mTopAction = null;
7772 mTopData = null;
7773 mTopComponent = null;
7774 Message msg = Message.obtain();
7775 msg.what = SHOW_FACTORY_ERROR_MSG;
7776 msg.getData().putCharSequence("msg", errorMsg);
7777 mHandler.sendMessage(msg);
7778 }
7779 }
7780 }
7781
7782 retrieveSettings();
7783
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007784 if (goingCallback != null) goingCallback.run();
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 synchronized (this) {
7787 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7788 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007789 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007790 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 if (apps != null) {
7792 int N = apps.size();
7793 int i;
7794 for (i=0; i<N; i++) {
7795 ApplicationInfo info
7796 = (ApplicationInfo)apps.get(i);
7797 if (info != null &&
7798 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007799 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 }
7801 }
7802 }
7803 } catch (RemoteException ex) {
7804 // pm is in same process, this will never happen.
7805 }
7806 }
7807
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007808 // Start up initial activity.
7809 mBooting = true;
7810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007812 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 Message msg = Message.obtain();
7814 msg.what = SHOW_UID_ERROR_MSG;
7815 mHandler.sendMessage(msg);
7816 }
7817 } catch (RemoteException e) {
7818 }
7819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007820 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 }
7822 }
7823
Dan Egnorb7f03672009-12-09 16:22:32 -08007824 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007825 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007827 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007828 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 startAppProblemLocked(app);
7830 app.stopFreezingAllLocked();
7831 return handleAppCrashLocked(app);
7832 }
7833
Dan Egnorb7f03672009-12-09 16:22:32 -08007834 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007835 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007837 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007838 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7839 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 startAppProblemLocked(app);
7841 app.stopFreezingAllLocked();
7842 }
7843
7844 /**
7845 * Generate a process error record, suitable for attachment to a ProcessRecord.
7846 *
7847 * @param app The ProcessRecord in which the error occurred.
7848 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7849 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007850 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 * @param shortMsg Short message describing the crash.
7852 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007853 * @param stackTrace Full crash stack trace, may be null.
7854 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 * @return Returns a fully-formed AppErrorStateInfo record.
7856 */
7857 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007858 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 report.condition = condition;
7862 report.processName = app.processName;
7863 report.pid = app.pid;
7864 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007865 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 report.shortMsg = shortMsg;
7867 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007868 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869
7870 return report;
7871 }
7872
Dan Egnor42471dd2010-01-07 17:25:22 -08007873 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 synchronized (this) {
7875 app.crashing = false;
7876 app.crashingReport = null;
7877 app.notResponding = false;
7878 app.notRespondingReport = null;
7879 if (app.anrDialog == fromDialog) {
7880 app.anrDialog = null;
7881 }
7882 if (app.waitDialog == fromDialog) {
7883 app.waitDialog = null;
7884 }
7885 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007886 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007887 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007888 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7889 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007890 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 }
7893 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007894
Dan Egnorb7f03672009-12-09 16:22:32 -08007895 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007896 if (mHeadless) {
7897 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7898 return false;
7899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 long now = SystemClock.uptimeMillis();
7901
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007902 Long crashTime;
7903 if (!app.isolated) {
7904 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7905 } else {
7906 crashTime = null;
7907 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007908 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007910 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007912 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007913 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007914 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7915 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007917 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007919 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7920 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
7922 }
7923 if (!app.persistent) {
7924 // We don't want to start this process again until the user
7925 // explicitly does so... but for persistent process, we really
7926 // need to keep it running. If a persistent process is actually
7927 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007928 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007929 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007930 if (!app.isolated) {
7931 // XXX We don't have a way to mark isolated processes
7932 // as bad, since they don't have a peristent identity.
7933 mBadProcesses.put(app.info.processName, app.uid, now);
7934 mProcessCrashTimes.remove(app.info.processName, app.uid);
7935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007938 // Don't let services in this process be restarted and potentially
7939 // annoy the user repeatedly. Unless it is persistent, since those
7940 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007941 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007942 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 return false;
7944 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007945 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007946 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007947 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007948 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007949 // If the top running activity is from this crashing
7950 // process, then terminate it to avoid getting in a loop.
7951 Slog.w(TAG, " Force finishing activity "
7952 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007953 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007954 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007955 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08007956 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007957 // stopped, to avoid a situation where one will get
7958 // re-start our crashing activity once it gets resumed again.
7959 index--;
7960 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007961 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007962 if (r.state == ActivityState.RESUMED
7963 || r.state == ActivityState.PAUSING
7964 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007965 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007966 Slog.w(TAG, " Force finishing activity "
7967 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007968 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007969 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007970 }
7971 }
7972 }
7973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 }
7975
7976 // Bump up the crash count of any services currently running in the proc.
7977 if (app.services.size() != 0) {
7978 // Any services running in the application need to be placed
7979 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007980 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007982 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 sr.crashCount++;
7984 }
7985 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007986
7987 // If the crashing process is what we consider to be the "home process" and it has been
7988 // replaced by a third-party app, clear the package preferred activities from packages
7989 // with a home activity running in the process to prevent a repeatedly crashing app
7990 // from blocking the user to manually clear the list.
7991 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7992 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7993 Iterator it = mHomeProcess.activities.iterator();
7994 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007995 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007996 if (r.isHomeActivity) {
7997 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7998 try {
7999 ActivityThread.getPackageManager()
8000 .clearPackagePreferredActivities(r.packageName);
8001 } catch (RemoteException c) {
8002 // pm is in same process, this will never happen.
8003 }
8004 }
8005 }
8006 }
8007
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008008 if (!app.isolated) {
8009 // XXX Can't keep track of crash times for isolated processes,
8010 // because they don't have a perisistent identity.
8011 mProcessCrashTimes.put(app.info.processName, app.uid, now);
8012 }
8013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 return true;
8015 }
8016
8017 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008018 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8019 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 skipCurrentReceiverLocked(app);
8021 }
8022
8023 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008024 for (BroadcastQueue queue : mBroadcastQueues) {
8025 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 }
8027 }
8028
Dan Egnor60d87622009-12-16 16:32:58 -08008029 /**
8030 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8031 * The application process will exit immediately after this call returns.
8032 * @param app object of the crashing app, null for the system server
8033 * @param crashInfo describing the exception
8034 */
8035 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008036 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008037 final String processName = app == null ? "system_server"
8038 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008039
8040 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008041 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008042 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008043 crashInfo.exceptionClassName,
8044 crashInfo.exceptionMessage,
8045 crashInfo.throwFileName,
8046 crashInfo.throwLineNumber);
8047
Jeff Sharkeya353d262011-10-28 11:12:06 -07008048 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008049
8050 crashApplication(r, crashInfo);
8051 }
8052
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008053 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008054 IBinder app,
8055 int violationMask,
8056 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008057 ProcessRecord r = findAppProcess(app, "StrictMode");
8058 if (r == null) {
8059 return;
8060 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008061
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008062 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008063 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008064 boolean logIt = true;
8065 synchronized (mAlreadyLoggedViolatedStacks) {
8066 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8067 logIt = false;
8068 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008069 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008070 // the relative pain numbers, without logging all
8071 // the stack traces repeatedly. We'd want to do
8072 // likewise in the client code, which also does
8073 // dup suppression, before the Binder call.
8074 } else {
8075 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8076 mAlreadyLoggedViolatedStacks.clear();
8077 }
8078 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8079 }
8080 }
8081 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008082 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008083 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008084 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008085
8086 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8087 AppErrorResult result = new AppErrorResult();
8088 synchronized (this) {
8089 final long origId = Binder.clearCallingIdentity();
8090
8091 Message msg = Message.obtain();
8092 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8093 HashMap<String, Object> data = new HashMap<String, Object>();
8094 data.put("result", result);
8095 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008096 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008097 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008098 msg.obj = data;
8099 mHandler.sendMessage(msg);
8100
8101 Binder.restoreCallingIdentity(origId);
8102 }
8103 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008104 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008105 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008106 }
8107
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008108 // Depending on the policy in effect, there could be a bunch of
8109 // these in quick succession so we try to batch these together to
8110 // minimize disk writes, number of dropbox entries, and maximize
8111 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008112 private void logStrictModeViolationToDropBox(
8113 ProcessRecord process,
8114 StrictMode.ViolationInfo info) {
8115 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008116 return;
8117 }
8118 final boolean isSystemApp = process == null ||
8119 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8120 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008121 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008122 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8123 final DropBoxManager dbox = (DropBoxManager)
8124 mContext.getSystemService(Context.DROPBOX_SERVICE);
8125
8126 // Exit early if the dropbox isn't configured to accept this report type.
8127 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8128
8129 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008130 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008131 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8132 synchronized (sb) {
8133 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008134 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008135 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8136 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008137 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8138 if (info.violationNumThisLoop != 0) {
8139 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8140 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008141 if (info.numAnimationsRunning != 0) {
8142 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8143 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008144 if (info.broadcastIntentAction != null) {
8145 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8146 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008147 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008148 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008149 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008150 if (info.numInstances != -1) {
8151 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8152 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008153 if (info.tags != null) {
8154 for (String tag : info.tags) {
8155 sb.append("Span-Tag: ").append(tag).append("\n");
8156 }
8157 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008158 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008159 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8160 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008161 }
8162 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008163
8164 // Only buffer up to ~64k. Various logging bits truncate
8165 // things at 128k.
8166 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008167 }
8168
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008169 // Flush immediately if the buffer's grown too large, or this
8170 // is a non-system app. Non-system apps are isolated with a
8171 // different tag & policy and not batched.
8172 //
8173 // Batching is useful during internal testing with
8174 // StrictMode settings turned up high. Without batching,
8175 // thousands of separate files could be created on boot.
8176 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008177 new Thread("Error dump: " + dropboxTag) {
8178 @Override
8179 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008180 String report;
8181 synchronized (sb) {
8182 report = sb.toString();
8183 sb.delete(0, sb.length());
8184 sb.trimToSize();
8185 }
8186 if (report.length() != 0) {
8187 dbox.addText(dropboxTag, report);
8188 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008189 }
8190 }.start();
8191 return;
8192 }
8193
8194 // System app batching:
8195 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008196 // An existing dropbox-writing thread is outstanding, so
8197 // we don't need to start it up. The existing thread will
8198 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008199 return;
8200 }
8201
8202 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8203 // (After this point, we shouldn't access AMS internal data structures.)
8204 new Thread("Error dump: " + dropboxTag) {
8205 @Override
8206 public void run() {
8207 // 5 second sleep to let stacks arrive and be batched together
8208 try {
8209 Thread.sleep(5000); // 5 seconds
8210 } catch (InterruptedException e) {}
8211
8212 String errorReport;
8213 synchronized (mStrictModeBuffer) {
8214 errorReport = mStrictModeBuffer.toString();
8215 if (errorReport.length() == 0) {
8216 return;
8217 }
8218 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8219 mStrictModeBuffer.trimToSize();
8220 }
8221 dbox.addText(dropboxTag, errorReport);
8222 }
8223 }.start();
8224 }
8225
Dan Egnor60d87622009-12-16 16:32:58 -08008226 /**
8227 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8228 * @param app object of the crashing app, null for the system server
8229 * @param tag reported by the caller
8230 * @param crashInfo describing the context of the error
8231 * @return true if the process should exit immediately (WTF is fatal)
8232 */
8233 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008234 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008235 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008236 final String processName = app == null ? "system_server"
8237 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008238
8239 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008240 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008241 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008242 tag, crashInfo.exceptionMessage);
8243
Jeff Sharkeya353d262011-10-28 11:12:06 -07008244 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008245
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008246 if (r != null && r.pid != Process.myPid() &&
8247 Settings.Secure.getInt(mContext.getContentResolver(),
8248 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008249 crashApplication(r, crashInfo);
8250 return true;
8251 } else {
8252 return false;
8253 }
8254 }
8255
8256 /**
8257 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8258 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8259 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008260 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008261 if (app == null) {
8262 return null;
8263 }
8264
8265 synchronized (this) {
8266 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8267 final int NA = apps.size();
8268 for (int ia=0; ia<NA; ia++) {
8269 ProcessRecord p = apps.valueAt(ia);
8270 if (p.thread != null && p.thread.asBinder() == app) {
8271 return p;
8272 }
8273 }
8274 }
8275
Dianne Hackborncb44d962011-03-10 17:02:27 -08008276 Slog.w(TAG, "Can't find mystery application for " + reason
8277 + " from pid=" + Binder.getCallingPid()
8278 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008279 return null;
8280 }
8281 }
8282
8283 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008284 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8285 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008286 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008287 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8288 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008289 // Watchdog thread ends up invoking this function (with
8290 // a null ProcessRecord) to add the stack file to dropbox.
8291 // Do not acquire a lock on this (am) in such cases, as it
8292 // could cause a potential deadlock, if and when watchdog
8293 // is invoked due to unavailability of lock on am and it
8294 // would prevent watchdog from killing system_server.
8295 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008296 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008297 return;
8298 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008299 // Note: ProcessRecord 'process' is guarded by the service
8300 // instance. (notably process.pkgList, which could otherwise change
8301 // concurrently during execution of this method)
8302 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008303 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008304 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008305 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008306 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8307 for (String pkg : process.pkgList) {
8308 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008309 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008310 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008311 if (pi != null) {
8312 sb.append(" v").append(pi.versionCode);
8313 if (pi.versionName != null) {
8314 sb.append(" (").append(pi.versionName).append(")");
8315 }
8316 }
8317 } catch (RemoteException e) {
8318 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008319 }
Dan Egnora455d192010-03-12 08:52:28 -08008320 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008321 }
Dan Egnora455d192010-03-12 08:52:28 -08008322 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008323 }
8324
8325 private static String processClass(ProcessRecord process) {
8326 if (process == null || process.pid == MY_PID) {
8327 return "system_server";
8328 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8329 return "system_app";
8330 } else {
8331 return "data_app";
8332 }
8333 }
8334
8335 /**
8336 * Write a description of an error (crash, WTF, ANR) to the drop box.
8337 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8338 * @param process which caused the error, null means the system server
8339 * @param activity which triggered the error, null if unknown
8340 * @param parent activity related to the error, null if unknown
8341 * @param subject line related to the error, null if absent
8342 * @param report in long form describing the error, null if absent
8343 * @param logFile to include in the report, null if none
8344 * @param crashInfo giving an application stack trace, null if absent
8345 */
8346 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008347 ProcessRecord process, String processName, ActivityRecord activity,
8348 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008349 final String report, final File logFile,
8350 final ApplicationErrorReport.CrashInfo crashInfo) {
8351 // NOTE -- this must never acquire the ActivityManagerService lock,
8352 // otherwise the watchdog may be prevented from resetting the system.
8353
8354 final String dropboxTag = processClass(process) + "_" + eventType;
8355 final DropBoxManager dbox = (DropBoxManager)
8356 mContext.getSystemService(Context.DROPBOX_SERVICE);
8357
8358 // Exit early if the dropbox isn't configured to accept this report type.
8359 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8360
8361 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008362 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008363 if (activity != null) {
8364 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8365 }
8366 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8367 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8368 }
8369 if (parent != null && parent != activity) {
8370 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8371 }
8372 if (subject != null) {
8373 sb.append("Subject: ").append(subject).append("\n");
8374 }
8375 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008376 if (Debug.isDebuggerConnected()) {
8377 sb.append("Debugger: Connected\n");
8378 }
Dan Egnora455d192010-03-12 08:52:28 -08008379 sb.append("\n");
8380
8381 // Do the rest in a worker thread to avoid blocking the caller on I/O
8382 // (After this point, we shouldn't access AMS internal data structures.)
8383 Thread worker = new Thread("Error dump: " + dropboxTag) {
8384 @Override
8385 public void run() {
8386 if (report != null) {
8387 sb.append(report);
8388 }
8389 if (logFile != null) {
8390 try {
8391 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8392 } catch (IOException e) {
8393 Slog.e(TAG, "Error reading " + logFile, e);
8394 }
8395 }
8396 if (crashInfo != null && crashInfo.stackTrace != null) {
8397 sb.append(crashInfo.stackTrace);
8398 }
8399
8400 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8401 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8402 if (lines > 0) {
8403 sb.append("\n");
8404
8405 // Merge several logcat streams, and take the last N lines
8406 InputStreamReader input = null;
8407 try {
8408 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8409 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8410 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8411
8412 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8413 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8414 input = new InputStreamReader(logcat.getInputStream());
8415
8416 int num;
8417 char[] buf = new char[8192];
8418 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8419 } catch (IOException e) {
8420 Slog.e(TAG, "Error running logcat", e);
8421 } finally {
8422 if (input != null) try { input.close(); } catch (IOException e) {}
8423 }
8424 }
8425
8426 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008427 }
Dan Egnora455d192010-03-12 08:52:28 -08008428 };
8429
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008430 if (process == null) {
8431 // If process is null, we are being called from some internal code
8432 // and may be about to die -- run this synchronously.
8433 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008434 } else {
8435 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008436 }
8437 }
8438
8439 /**
8440 * Bring up the "unexpected error" dialog box for a crashing app.
8441 * Deal with edge cases (intercepts from instrumented applications,
8442 * ActivityController, error intent receivers, that sort of thing).
8443 * @param r the application crashing
8444 * @param crashInfo describing the failure
8445 */
8446 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008447 long timeMillis = System.currentTimeMillis();
8448 String shortMsg = crashInfo.exceptionClassName;
8449 String longMsg = crashInfo.exceptionMessage;
8450 String stackTrace = crashInfo.stackTrace;
8451 if (shortMsg != null && longMsg != null) {
8452 longMsg = shortMsg + ": " + longMsg;
8453 } else if (shortMsg != null) {
8454 longMsg = shortMsg;
8455 }
8456
Dan Egnor60d87622009-12-16 16:32:58 -08008457 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008459 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008460 try {
8461 String name = r != null ? r.processName : null;
8462 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008463 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008464 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008465 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 + " at watcher's request");
8467 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008468 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008469 }
8470 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008471 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008472 }
8473 }
8474
8475 final long origId = Binder.clearCallingIdentity();
8476
8477 // If this process is running instrumentation, finish it.
8478 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008479 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008481 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8482 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 Bundle info = new Bundle();
8484 info.putString("shortMsg", shortMsg);
8485 info.putString("longMsg", longMsg);
8486 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8487 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008488 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 }
8490
Dan Egnor60d87622009-12-16 16:32:58 -08008491 // If we can't identify the process or it's already exceeded its crash quota,
8492 // quit right away without showing a crash dialog.
8493 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008495 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 }
8497
8498 Message msg = Message.obtain();
8499 msg.what = SHOW_ERROR_MSG;
8500 HashMap data = new HashMap();
8501 data.put("result", result);
8502 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 msg.obj = data;
8504 mHandler.sendMessage(msg);
8505
8506 Binder.restoreCallingIdentity(origId);
8507 }
8508
8509 int res = result.get();
8510
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008511 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008513 if (r != null && !r.isolated) {
8514 // XXX Can't keep track of crash time for isolated processes,
8515 // since they don't have a persistent identity.
8516 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 SystemClock.uptimeMillis());
8518 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008519 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008520 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008521 }
8522 }
8523
8524 if (appErrorIntent != null) {
8525 try {
8526 mContext.startActivity(appErrorIntent);
8527 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008528 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008532
8533 Intent createAppErrorIntentLocked(ProcessRecord r,
8534 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8535 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008536 if (report == null) {
8537 return null;
8538 }
8539 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8540 result.setComponent(r.errorReportReceiver);
8541 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8542 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8543 return result;
8544 }
8545
Dan Egnorb7f03672009-12-09 16:22:32 -08008546 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8547 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008548 if (r.errorReportReceiver == null) {
8549 return null;
8550 }
8551
8552 if (!r.crashing && !r.notResponding) {
8553 return null;
8554 }
8555
Dan Egnorb7f03672009-12-09 16:22:32 -08008556 ApplicationErrorReport report = new ApplicationErrorReport();
8557 report.packageName = r.info.packageName;
8558 report.installerPackageName = r.errorReportReceiver.getPackageName();
8559 report.processName = r.processName;
8560 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008561 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008562
Dan Egnorb7f03672009-12-09 16:22:32 -08008563 if (r.crashing) {
8564 report.type = ApplicationErrorReport.TYPE_CRASH;
8565 report.crashInfo = crashInfo;
8566 } else if (r.notResponding) {
8567 report.type = ApplicationErrorReport.TYPE_ANR;
8568 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008569
Dan Egnorb7f03672009-12-09 16:22:32 -08008570 report.anrInfo.activity = r.notRespondingReport.tag;
8571 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8572 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008573 }
8574
Dan Egnorb7f03672009-12-09 16:22:32 -08008575 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008576 }
8577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008579 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 // assume our apps are happy - lazy create the list
8581 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8582
Dianne Hackborn0c380492012-08-20 17:23:30 -07008583 final boolean allUsers = ActivityManager.checkUidPermission(
8584 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8585 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8586 int userId = UserHandle.getUserId(Binder.getCallingUid());
8587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008588 synchronized (this) {
8589
8590 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008591 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8592 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008593 if (!allUsers && app.userId != userId) {
8594 continue;
8595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8597 // This one's in trouble, so we'll generate a report for it
8598 // crashes are higher priority (in case there's a crash *and* an anr)
8599 ActivityManager.ProcessErrorStateInfo report = null;
8600 if (app.crashing) {
8601 report = app.crashingReport;
8602 } else if (app.notResponding) {
8603 report = app.notRespondingReport;
8604 }
8605
8606 if (report != null) {
8607 if (errList == null) {
8608 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8609 }
8610 errList.add(report);
8611 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008612 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 " crashing = " + app.crashing +
8614 " notResponding = " + app.notResponding);
8615 }
8616 }
8617 }
8618 }
8619
8620 return errList;
8621 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008622
8623 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008624 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008625 if (currApp != null) {
8626 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8627 }
8628 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008629 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8630 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008631 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8632 if (currApp != null) {
8633 currApp.lru = 0;
8634 }
8635 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008636 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008637 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8638 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8639 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8640 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8641 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8642 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8643 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8644 } else {
8645 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8646 }
8647 }
8648
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008649 private void fillInProcMemInfo(ProcessRecord app,
8650 ActivityManager.RunningAppProcessInfo outInfo) {
8651 outInfo.pid = app.pid;
8652 outInfo.uid = app.info.uid;
8653 if (mHeavyWeightProcess == app) {
8654 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8655 }
8656 if (app.persistent) {
8657 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8658 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008659 if (app.hasActivities) {
8660 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8661 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008662 outInfo.lastTrimLevel = app.trimMemoryLevel;
8663 int adj = app.curAdj;
8664 outInfo.importance = oomAdjToImportance(adj, outInfo);
8665 outInfo.importanceReasonCode = app.adjTypeCode;
8666 }
8667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008669 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 // Lazy instantiation of list
8671 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008672 final boolean allUsers = ActivityManager.checkUidPermission(
8673 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8674 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8675 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008676 synchronized (this) {
8677 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008678 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8679 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008680 if (!allUsers && app.userId != userId) {
8681 continue;
8682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008683 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8684 // Generate process state info for running application
8685 ActivityManager.RunningAppProcessInfo currApp =
8686 new ActivityManager.RunningAppProcessInfo(app.processName,
8687 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008688 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008689 if (app.adjSource instanceof ProcessRecord) {
8690 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008691 currApp.importanceReasonImportance = oomAdjToImportance(
8692 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008693 } else if (app.adjSource instanceof ActivityRecord) {
8694 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008695 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8696 }
8697 if (app.adjTarget instanceof ComponentName) {
8698 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8699 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008700 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 // + " lru=" + currApp.lru);
8702 if (runList == null) {
8703 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8704 }
8705 runList.add(currApp);
8706 }
8707 }
8708 }
8709 return runList;
8710 }
8711
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008712 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008713 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008714 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8715 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8716 if (runningApps != null && runningApps.size() > 0) {
8717 Set<String> extList = new HashSet<String>();
8718 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8719 if (app.pkgList != null) {
8720 for (String pkg : app.pkgList) {
8721 extList.add(pkg);
8722 }
8723 }
8724 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008725 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008726 for (String pkg : extList) {
8727 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008728 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008729 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8730 retList.add(info);
8731 }
8732 } catch (RemoteException e) {
8733 }
8734 }
8735 }
8736 return retList;
8737 }
8738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008740 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8741 enforceNotIsolatedCaller("getMyMemoryState");
8742 synchronized (this) {
8743 ProcessRecord proc;
8744 synchronized (mPidsSelfLocked) {
8745 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8746 }
8747 fillInProcMemInfo(proc, outInfo);
8748 }
8749 }
8750
8751 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008752 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753 if (checkCallingPermission(android.Manifest.permission.DUMP)
8754 != PackageManager.PERMISSION_GRANTED) {
8755 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8756 + Binder.getCallingPid()
8757 + ", uid=" + Binder.getCallingUid()
8758 + " without permission "
8759 + android.Manifest.permission.DUMP);
8760 return;
8761 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008762
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008764 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008765 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008766
8767 int opti = 0;
8768 while (opti < args.length) {
8769 String opt = args[opti];
8770 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8771 break;
8772 }
8773 opti++;
8774 if ("-a".equals(opt)) {
8775 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008776 } else if ("-c".equals(opt)) {
8777 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 } else if ("-h".equals(opt)) {
8779 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008781 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008782 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8784 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8785 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008786 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008787 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008788 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008789 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008790 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008792 pw.println(" all: dump all activities");
8793 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008794 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008795 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8796 pw.println(" a partial substring in a component name, a");
8797 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008798 pw.println(" -a: include all available server state.");
8799 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008800 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008801 } else {
8802 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008803 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008804 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008805
8806 long origId = Binder.clearCallingIdentity();
8807 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 // Is the caller requesting to dump a particular piece of data?
8809 if (opti < args.length) {
8810 String cmd = args[opti];
8811 opti++;
8812 if ("activities".equals(cmd) || "a".equals(cmd)) {
8813 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008814 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008816 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008817 String[] newArgs;
8818 String name;
8819 if (opti >= args.length) {
8820 name = null;
8821 newArgs = EMPTY_STRING_ARRAY;
8822 } else {
8823 name = args[opti];
8824 opti++;
8825 newArgs = new String[args.length - opti];
8826 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8827 args.length - opti);
8828 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008829 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008830 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 String[] newArgs;
8834 String name;
8835 if (opti >= args.length) {
8836 name = null;
8837 newArgs = EMPTY_STRING_ARRAY;
8838 } else {
8839 name = args[opti];
8840 opti++;
8841 newArgs = new String[args.length - opti];
8842 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8843 args.length - opti);
8844 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008846 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008847 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008849 String[] newArgs;
8850 String name;
8851 if (opti >= args.length) {
8852 name = null;
8853 newArgs = EMPTY_STRING_ARRAY;
8854 } else {
8855 name = args[opti];
8856 opti++;
8857 newArgs = new String[args.length - opti];
8858 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8859 args.length - opti);
8860 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008861 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008863 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008864 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8865 synchronized (this) {
8866 dumpOomLocked(fd, pw, args, opti, true);
8867 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008868 } else if ("provider".equals(cmd)) {
8869 String[] newArgs;
8870 String name;
8871 if (opti >= args.length) {
8872 name = null;
8873 newArgs = EMPTY_STRING_ARRAY;
8874 } else {
8875 name = args[opti];
8876 opti++;
8877 newArgs = new String[args.length - opti];
8878 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8879 }
8880 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8881 pw.println("No providers match: " + name);
8882 pw.println("Use -h for help.");
8883 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8885 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008886 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008887 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008888 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 String[] newArgs;
8890 String name;
8891 if (opti >= args.length) {
8892 name = null;
8893 newArgs = EMPTY_STRING_ARRAY;
8894 } else {
8895 name = args[opti];
8896 opti++;
8897 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008898 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8899 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008900 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008901 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008902 pw.println("No services match: " + name);
8903 pw.println("Use -h for help.");
8904 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008905 } else if ("package".equals(cmd)) {
8906 String[] newArgs;
8907 if (opti >= args.length) {
8908 pw.println("package: no package name specified");
8909 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008910 } else {
8911 dumpPackage = args[opti];
8912 opti++;
8913 newArgs = new String[args.length - opti];
8914 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8915 args.length - opti);
8916 args = newArgs;
8917 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008918 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008919 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8921 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008922 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008923 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008924 } else {
8925 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008926 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8927 pw.println("Bad activity command, or no activities match: " + cmd);
8928 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008929 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008930 }
8931 if (!more) {
8932 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008933 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008936
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 // No piece of data specified, dump everything.
8938 synchronized (this) {
8939 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008940 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941 if (needSep) {
8942 pw.println(" ");
8943 }
8944 if (dumpAll) {
8945 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008946 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008947 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 if (needSep) {
8949 pw.println(" ");
8950 }
8951 if (dumpAll) {
8952 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008953 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008954 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008955 if (needSep) {
8956 pw.println(" ");
8957 }
8958 if (dumpAll) {
8959 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008961 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008962 if (needSep) {
8963 pw.println(" ");
8964 }
8965 if (dumpAll) {
8966 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008967 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008969 if (needSep) {
8970 pw.println(" ");
8971 }
8972 if (dumpAll) {
8973 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008974 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008976 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008977 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008979
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008980 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008982 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8983 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8985 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008986 pw.println(" ");
8987 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008988 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8989 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008990 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008993 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008994 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008995 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008996 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008998 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008999 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009000 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009001 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009002 if (mMainStack.mGoingToSleepActivities.size() > 0) {
9003 pw.println(" ");
9004 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009005 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009006 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08009007 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009008 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009009 pw.println(" ");
9010 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009011 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009012 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009016 if (mMainStack.mPausingActivity != null) {
9017 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009018 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009019 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 if (dumpAll) {
9022 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9023 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009024 pw.println(" mDismissKeyguardOnNextActivity: "
9025 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009028 if (mRecentTasks.size() > 0) {
9029 pw.println();
9030 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031
9032 final int N = mRecentTasks.size();
9033 for (int i=0; i<N; i++) {
9034 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 if (dumpPackage != null) {
9036 if (tr.realActivity == null ||
9037 !dumpPackage.equals(tr.realActivity)) {
9038 continue;
9039 }
9040 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009041 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9042 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009043 if (dumpAll) {
9044 mRecentTasks.get(i).dump(pw, " ");
9045 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 }
9047 }
9048
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 if (dumpAll) {
9050 pw.println(" ");
9051 pw.println(" mCurTask: " + mCurTask);
9052 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009053
9054 return true;
9055 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009056
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009058 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 boolean needSep = false;
9060 int numPers = 0;
9061
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009062 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9063
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9066 final int NA = procs.size();
9067 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009068 ProcessRecord r = procs.valueAt(ia);
9069 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9070 continue;
9071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 if (!needSep) {
9073 pw.println(" All known processes:");
9074 needSep = true;
9075 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009076 pw.print(r.persistent ? " *PERS*" : " *APP*");
9077 pw.print(" UID "); pw.print(procs.keyAt(ia));
9078 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009079 r.dump(pw, " ");
9080 if (r.persistent) {
9081 numPers++;
9082 }
9083 }
9084 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009086
9087 if (mIsolatedProcesses.size() > 0) {
9088 if (needSep) pw.println(" ");
9089 needSep = true;
9090 pw.println(" Isolated process list (sorted by uid):");
9091 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9092 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9093 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9094 continue;
9095 }
9096 pw.println(String.format("%sIsolated #%2d: %s",
9097 " ", i, r.toString()));
9098 }
9099 }
9100
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 if (mLruProcesses.size() > 0) {
9102 if (needSep) pw.println(" ");
9103 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009104 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009105 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009106 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 needSep = true;
9108 }
9109
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009110 if (dumpAll) {
9111 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009112 boolean printed = false;
9113 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9114 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9115 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9116 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009117 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009118 if (!printed) {
9119 if (needSep) pw.println(" ");
9120 needSep = true;
9121 pw.println(" PID mappings:");
9122 printed = true;
9123 }
9124 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9125 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009126 }
9127 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009128 }
9129
9130 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 synchronized (mPidsSelfLocked) {
9132 boolean printed = false;
9133 for (int i=0; i<mForegroundProcesses.size(); i++) {
9134 ProcessRecord r = mPidsSelfLocked.get(
9135 mForegroundProcesses.valueAt(i).pid);
9136 if (dumpPackage != null && (r == null
9137 || !dumpPackage.equals(r.info.packageName))) {
9138 continue;
9139 }
9140 if (!printed) {
9141 if (needSep) pw.println(" ");
9142 needSep = true;
9143 pw.println(" Foreground Processes:");
9144 printed = true;
9145 }
9146 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9147 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009150 }
9151
9152 if (mPersistentStartingProcesses.size() > 0) {
9153 if (needSep) pw.println(" ");
9154 needSep = true;
9155 pw.println(" Persisent processes that are starting:");
9156 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009157 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 if (mRemovedProcesses.size() > 0) {
9161 if (needSep) pw.println(" ");
9162 needSep = true;
9163 pw.println(" Processes that are being removed:");
9164 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009165 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009166 }
9167
9168 if (mProcessesOnHold.size() > 0) {
9169 if (needSep) pw.println(" ");
9170 needSep = true;
9171 pw.println(" Processes that are on old until the system is ready:");
9172 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009173 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009176 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009177
9178 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009179 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 long now = SystemClock.uptimeMillis();
9181 for (Map.Entry<String, SparseArray<Long>> procs
9182 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009183 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009184 SparseArray<Long> uids = procs.getValue();
9185 final int N = uids.size();
9186 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009187 int puid = uids.keyAt(i);
9188 ProcessRecord r = mProcessNames.get(pname, puid);
9189 if (dumpPackage != null && (r == null
9190 || !dumpPackage.equals(r.info.packageName))) {
9191 continue;
9192 }
9193 if (!printed) {
9194 if (needSep) pw.println(" ");
9195 needSep = true;
9196 pw.println(" Time since processes crashed:");
9197 printed = true;
9198 }
9199 pw.print(" Process "); pw.print(pname);
9200 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009201 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009202 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9203 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009204 }
9205 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009208 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210 for (Map.Entry<String, SparseArray<Long>> procs
9211 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009212 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213 SparseArray<Long> uids = procs.getValue();
9214 final int N = uids.size();
9215 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009216 int puid = uids.keyAt(i);
9217 ProcessRecord r = mProcessNames.get(pname, puid);
9218 if (dumpPackage != null && (r == null
9219 || !dumpPackage.equals(r.info.packageName))) {
9220 continue;
9221 }
9222 if (!printed) {
9223 if (needSep) pw.println(" ");
9224 needSep = true;
9225 pw.println(" Bad processes:");
9226 }
9227 pw.print(" Bad process "); pw.print(pname);
9228 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009229 pw.print(": crashed at time ");
9230 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 }
9232 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009234
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009235 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009236 pw.println(" mStartedUsers:");
9237 for (int i=0; i<mStartedUsers.size(); i++) {
9238 UserStartedState uss = mStartedUsers.valueAt(i);
9239 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009240 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009241 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009242 pw.print(" mUserLru: [");
9243 for (int i=0; i<mUserLru.size(); i++) {
9244 if (i > 0) pw.print(", ");
9245 pw.print(mUserLru.get(i));
9246 }
9247 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009249 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009250 if (dumpAll) {
9251 StringBuilder sb = new StringBuilder(128);
9252 sb.append(" mPreviousProcessVisibleTime: ");
9253 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9254 pw.println(sb);
9255 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009256 if (mHeavyWeightProcess != null) {
9257 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9258 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009259 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009260 if (dumpAll) {
9261 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009262 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009263 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009264 for (Map.Entry<String, Integer> entry
9265 : mCompatModePackages.getPackages().entrySet()) {
9266 String pkg = entry.getKey();
9267 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009268 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9269 continue;
9270 }
9271 if (!printed) {
9272 pw.println(" mScreenCompatPackages:");
9273 printed = true;
9274 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009275 pw.print(" "); pw.print(pkg); pw.print(": ");
9276 pw.print(mode); pw.println();
9277 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009278 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009280 if (mSleeping || mWentToSleep || mLockScreenShown) {
9281 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9282 + " mLockScreenShown " + mLockScreenShown);
9283 }
9284 if (mShuttingDown) {
9285 pw.println(" mShuttingDown=" + mShuttingDown);
9286 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009287 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9288 || mOrigWaitForDebugger) {
9289 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9290 + " mDebugTransient=" + mDebugTransient
9291 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9292 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009293 if (mOpenGlTraceApp != null) {
9294 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9295 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009296 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9297 || mProfileFd != null) {
9298 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9299 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9300 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9301 + mAutoStopProfiler);
9302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303 if (mAlwaysFinishActivities || mController != null) {
9304 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9305 + " mController=" + mController);
9306 }
9307 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009308 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009309 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009310 + " mProcessesReady=" + mProcessesReady
9311 + " mSystemReady=" + mSystemReady);
9312 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009313 + " mBooted=" + mBooted
9314 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009315 pw.print(" mLastPowerCheckRealtime=");
9316 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9317 pw.println("");
9318 pw.print(" mLastPowerCheckUptime=");
9319 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9320 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009321 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9322 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009323 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009324 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9325 + " mNumHiddenProcs=" + mNumHiddenProcs
9326 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009327 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009329
9330 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 }
9332
Dianne Hackborn287952c2010-09-22 22:34:31 -07009333 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009334 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009335 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009336 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009337 long now = SystemClock.uptimeMillis();
9338 for (int i=0; i<mProcessesToGc.size(); i++) {
9339 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009340 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9341 continue;
9342 }
9343 if (!printed) {
9344 if (needSep) pw.println(" ");
9345 needSep = true;
9346 pw.println(" Processes that are waiting to GC:");
9347 printed = true;
9348 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009349 pw.print(" Process "); pw.println(proc);
9350 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9351 pw.print(", last gced=");
9352 pw.print(now-proc.lastRequestedGc);
9353 pw.print(" ms ago, last lowMem=");
9354 pw.print(now-proc.lastLowMemory);
9355 pw.println(" ms ago");
9356
9357 }
9358 }
9359 return needSep;
9360 }
9361
9362 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9363 int opti, boolean dumpAll) {
9364 boolean needSep = false;
9365
9366 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009367 if (needSep) pw.println(" ");
9368 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009369 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009370 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009371 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009372 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9373 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9374 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9375 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9376 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009377 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009378 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009379 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009380 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009381 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009382 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009383
9384 if (needSep) pw.println(" ");
9385 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009386 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009387 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009388 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009389 needSep = true;
9390 }
9391
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009392 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009393
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009394 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009395 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009396 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009397 if (mHeavyWeightProcess != null) {
9398 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9399 }
9400
9401 return true;
9402 }
9403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404 /**
9405 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009406 * - no provider specified: dump all the providers
9407 * - a flattened component name that matched an existing provider was specified as the
9408 * first arg: dump that one provider
9409 * - the first arg isn't the flattened component name of an existing provider:
9410 * dump all providers whose component contains the first arg as a substring
9411 */
9412 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9413 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009414 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009415 }
9416
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009417 static class ItemMatcher {
9418 ArrayList<ComponentName> components;
9419 ArrayList<String> strings;
9420 ArrayList<Integer> objects;
9421 boolean all;
9422
9423 ItemMatcher() {
9424 all = true;
9425 }
9426
9427 void build(String name) {
9428 ComponentName componentName = ComponentName.unflattenFromString(name);
9429 if (componentName != null) {
9430 if (components == null) {
9431 components = new ArrayList<ComponentName>();
9432 }
9433 components.add(componentName);
9434 all = false;
9435 } else {
9436 int objectId = 0;
9437 // Not a '/' separated full component name; maybe an object ID?
9438 try {
9439 objectId = Integer.parseInt(name, 16);
9440 if (objects == null) {
9441 objects = new ArrayList<Integer>();
9442 }
9443 objects.add(objectId);
9444 all = false;
9445 } catch (RuntimeException e) {
9446 // Not an integer; just do string match.
9447 if (strings == null) {
9448 strings = new ArrayList<String>();
9449 }
9450 strings.add(name);
9451 all = false;
9452 }
9453 }
9454 }
9455
9456 int build(String[] args, int opti) {
9457 for (; opti<args.length; opti++) {
9458 String name = args[opti];
9459 if ("--".equals(name)) {
9460 return opti+1;
9461 }
9462 build(name);
9463 }
9464 return opti;
9465 }
9466
9467 boolean match(Object object, ComponentName comp) {
9468 if (all) {
9469 return true;
9470 }
9471 if (components != null) {
9472 for (int i=0; i<components.size(); i++) {
9473 if (components.get(i).equals(comp)) {
9474 return true;
9475 }
9476 }
9477 }
9478 if (objects != null) {
9479 for (int i=0; i<objects.size(); i++) {
9480 if (System.identityHashCode(object) == objects.get(i)) {
9481 return true;
9482 }
9483 }
9484 }
9485 if (strings != null) {
9486 String flat = comp.flattenToString();
9487 for (int i=0; i<strings.size(); i++) {
9488 if (flat.contains(strings.get(i))) {
9489 return true;
9490 }
9491 }
9492 }
9493 return false;
9494 }
9495 }
9496
Dianne Hackborn625ac272010-09-17 18:29:22 -07009497 /**
9498 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009499 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009500 * - the cmd arg isn't the flattened component name of an existing activity:
9501 * dump all activity whose component contains the cmd as a substring
9502 * - A hex number of the ActivityRecord object instance.
9503 */
9504 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9505 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009506 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009507
9508 if ("all".equals(name)) {
9509 synchronized (this) {
9510 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009511 activities.add(r1);
9512 }
9513 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009514 } else if ("top".equals(name)) {
9515 synchronized (this) {
9516 final int N = mMainStack.mHistory.size();
9517 if (N > 0) {
9518 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9519 }
9520 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009521 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009522 ItemMatcher matcher = new ItemMatcher();
9523 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009524
9525 synchronized (this) {
9526 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009527 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009528 activities.add(r1);
9529 }
9530 }
9531 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009532 }
9533
9534 if (activities.size() <= 0) {
9535 return false;
9536 }
9537
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009538 String[] newArgs = new String[args.length - opti];
9539 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9540
Dianne Hackborn30d71892010-12-11 10:37:55 -08009541 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009543 for (int i=activities.size()-1; i>=0; i--) {
9544 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009545 if (needSep) {
9546 pw.println();
9547 }
9548 needSep = true;
9549 synchronized (this) {
9550 if (lastTask != r.task) {
9551 lastTask = r.task;
9552 pw.print("TASK "); pw.print(lastTask.affinity);
9553 pw.print(" id="); pw.println(lastTask.taskId);
9554 if (dumpAll) {
9555 lastTask.dump(pw, " ");
9556 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009557 }
9558 }
9559 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009560 }
9561 return true;
9562 }
9563
9564 /**
9565 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9566 * there is a thread associated with the activity.
9567 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009568 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009569 final ActivityRecord r, String[] args, boolean dumpAll) {
9570 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009571 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009572 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9573 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9574 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009575 if (r.app != null) pw.println(r.app.pid);
9576 else pw.println("(not running)");
9577 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009579 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009580 }
9581 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 // flush anything that is already in the PrintWriter since the thread is going
9583 // to write to the file descriptor directly
9584 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009585 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 TransferPipe tp = new TransferPipe();
9587 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009588 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9589 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009590 tp.go(fd);
9591 } finally {
9592 tp.kill();
9593 }
9594 } catch (IOException e) {
9595 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009596 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009597 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009598 }
9599 }
9600 }
9601
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009602 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009603 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009604 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009605 boolean onlyHistory = false;
9606
9607 if ("history".equals(dumpPackage)) {
9608 onlyHistory = true;
9609 dumpPackage = null;
9610 }
9611
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009612 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009613 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009614 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009615 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 Iterator it = mRegisteredReceivers.values().iterator();
9617 while (it.hasNext()) {
9618 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009619 if (dumpPackage != null && (r.app == null ||
9620 !dumpPackage.equals(r.app.info.packageName))) {
9621 continue;
9622 }
9623 if (!printed) {
9624 pw.println(" Registered Receivers:");
9625 needSep = true;
9626 printed = true;
9627 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009628 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 r.dump(pw, " ");
9630 }
9631 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009632
9633 if (mReceiverResolver.dump(pw, needSep ?
9634 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9635 " ", dumpPackage, false)) {
9636 needSep = true;
9637 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009638 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009639
9640 for (BroadcastQueue q : mBroadcastQueues) {
9641 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009645
Dianne Hackborn786b4402012-08-27 15:14:02 -07009646 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009647 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9648 if (needSep) {
9649 pw.println();
9650 }
9651 needSep = true;
9652 pw.print(" Sticky broadcasts for user ");
9653 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9654 StringBuilder sb = new StringBuilder(128);
9655 for (Map.Entry<String, ArrayList<Intent>> ent
9656 : mStickyBroadcasts.valueAt(user).entrySet()) {
9657 pw.print(" * Sticky action "); pw.print(ent.getKey());
9658 if (dumpAll) {
9659 pw.println(":");
9660 ArrayList<Intent> intents = ent.getValue();
9661 final int N = intents.size();
9662 for (int i=0; i<N; i++) {
9663 sb.setLength(0);
9664 sb.append(" Intent: ");
9665 intents.get(i).toShortString(sb, false, true, false, false);
9666 pw.println(sb.toString());
9667 Bundle bundle = intents.get(i).getExtras();
9668 if (bundle != null) {
9669 pw.print(" ");
9670 pw.println(bundle.toString());
9671 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009672 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009673 } else {
9674 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 }
9676 }
9677 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009678 }
9679
Dianne Hackborn786b4402012-08-27 15:14:02 -07009680 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009681 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009682 for (BroadcastQueue queue : mBroadcastQueues) {
9683 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9684 + queue.mBroadcastsScheduled);
9685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009686 pw.println(" mHandler:");
9687 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009688 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009690
9691 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 }
9693
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009694 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009695 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009696 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009698 ItemMatcher matcher = new ItemMatcher();
9699 matcher.build(args, opti);
9700
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009702
9703 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009704
9705 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009706 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009707 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009708 ContentProviderRecord r = mLaunchingProviders.get(i);
9709 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9710 continue;
9711 }
9712 if (!printed) {
9713 if (needSep) pw.println(" ");
9714 needSep = true;
9715 pw.println(" Launching content providers:");
9716 printed = true;
9717 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009718 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009719 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009720 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009721 }
9722
9723 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009724 if (needSep) pw.println();
9725 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009726 pw.println("Granted Uri Permissions:");
9727 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9728 int uid = mGrantedUriPermissions.keyAt(i);
9729 HashMap<Uri, UriPermission> perms
9730 = mGrantedUriPermissions.valueAt(i);
9731 pw.print(" * UID "); pw.print(uid);
9732 pw.println(" holds:");
9733 for (UriPermission perm : perms.values()) {
9734 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009735 if (dumpAll) {
9736 perm.dump(pw, " ");
9737 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009738 }
9739 }
9740 needSep = true;
9741 }
9742
9743 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 }
9745
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009746 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009747 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009748 boolean needSep = false;
9749
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 if (mIntentSenderRecords.size() > 0) {
9751 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009752 Iterator<WeakReference<PendingIntentRecord>> it
9753 = mIntentSenderRecords.values().iterator();
9754 while (it.hasNext()) {
9755 WeakReference<PendingIntentRecord> ref = it.next();
9756 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009757 if (dumpPackage != null && (rec == null
9758 || !dumpPackage.equals(rec.key.packageName))) {
9759 continue;
9760 }
9761 if (!printed) {
9762 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9763 printed = true;
9764 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 needSep = true;
9766 if (rec != null) {
9767 pw.print(" * "); pw.println(rec);
9768 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009769 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009771 } else {
9772 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009773 }
9774 }
9775 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009776
9777 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009778 }
9779
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009780 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009781 String prefix, String label, boolean complete, boolean brief, boolean client,
9782 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009783 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009784 boolean needNL = false;
9785 final String innerPrefix = prefix + " ";
9786 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009787 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009788 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009789 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9790 continue;
9791 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009792 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009793 if (needNL) {
9794 pw.println(" ");
9795 needNL = false;
9796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009797 if (lastTask != r.task) {
9798 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009799 pw.print(prefix);
9800 pw.print(full ? "* " : " ");
9801 pw.println(lastTask);
9802 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009803 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009804 } else if (complete) {
9805 // Complete + brief == give a summary. Isn't that obvious?!?
9806 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009807 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009808 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009809 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009811 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009812 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9813 pw.print(" #"); pw.print(i); pw.print(": ");
9814 pw.println(r);
9815 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009816 r.dump(pw, innerPrefix);
9817 } else if (complete) {
9818 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009819 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009820 if (r.app != null) {
9821 pw.print(innerPrefix); pw.println(r.app);
9822 }
9823 }
9824 if (client && r.app != null && r.app.thread != null) {
9825 // flush anything that is already in the PrintWriter since the thread is going
9826 // to write to the file descriptor directly
9827 pw.flush();
9828 try {
9829 TransferPipe tp = new TransferPipe();
9830 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009831 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9832 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009833 // Short timeout, since blocking here can
9834 // deadlock with the application.
9835 tp.go(fd, 2000);
9836 } finally {
9837 tp.kill();
9838 }
9839 } catch (IOException e) {
9840 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9841 } catch (RemoteException e) {
9842 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9843 }
9844 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009846 }
9847 }
9848
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009849 private static String buildOomTag(String prefix, String space, int val, int base) {
9850 if (val == base) {
9851 if (space == null) return prefix;
9852 return prefix + " ";
9853 }
9854 return prefix + "+" + Integer.toString(val-base);
9855 }
9856
9857 private static final int dumpProcessList(PrintWriter pw,
9858 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009859 String prefix, String normalLabel, String persistentLabel,
9860 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009861 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009862 final int N = list.size()-1;
9863 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009865 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9866 continue;
9867 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009868 pw.println(String.format("%s%s #%2d: %s",
9869 prefix, (r.persistent ? persistentLabel : normalLabel),
9870 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009871 if (r.persistent) {
9872 numPers++;
9873 }
9874 }
9875 return numPers;
9876 }
9877
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009878 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009879 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009880 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009881 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009882
Dianne Hackborn905577f2011-09-07 18:31:28 -07009883 ArrayList<Pair<ProcessRecord, Integer>> list
9884 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9885 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009886 ProcessRecord r = origList.get(i);
9887 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9888 continue;
9889 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009890 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9891 }
9892
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009893 if (list.size() <= 0) {
9894 return false;
9895 }
9896
Dianne Hackborn905577f2011-09-07 18:31:28 -07009897 Comparator<Pair<ProcessRecord, Integer>> comparator
9898 = new Comparator<Pair<ProcessRecord, Integer>>() {
9899 @Override
9900 public int compare(Pair<ProcessRecord, Integer> object1,
9901 Pair<ProcessRecord, Integer> object2) {
9902 if (object1.first.setAdj != object2.first.setAdj) {
9903 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9904 }
9905 if (object1.second.intValue() != object2.second.intValue()) {
9906 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9907 }
9908 return 0;
9909 }
9910 };
9911
9912 Collections.sort(list, comparator);
9913
Dianne Hackborn287952c2010-09-22 22:34:31 -07009914 final long curRealtime = SystemClock.elapsedRealtime();
9915 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9916 final long curUptime = SystemClock.uptimeMillis();
9917 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9918
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009919 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009920 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009921 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009922 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009923 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009924 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9925 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009926 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9927 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009928 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9929 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009930 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9931 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009932 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009933 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009934 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9935 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9936 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9937 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9938 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9939 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9940 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9941 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009942 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9943 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009944 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9945 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009946 } else {
9947 oomAdj = Integer.toString(r.setAdj);
9948 }
9949 String schedGroup;
9950 switch (r.setSchedGroup) {
9951 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9952 schedGroup = "B";
9953 break;
9954 case Process.THREAD_GROUP_DEFAULT:
9955 schedGroup = "F";
9956 break;
9957 default:
9958 schedGroup = Integer.toString(r.setSchedGroup);
9959 break;
9960 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009961 String foreground;
9962 if (r.foregroundActivities) {
9963 foreground = "A";
9964 } else if (r.foregroundServices) {
9965 foreground = "S";
9966 } else {
9967 foreground = " ";
9968 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009969 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009970 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009971 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9972 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009973 if (r.adjSource != null || r.adjTarget != null) {
9974 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009975 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009976 if (r.adjTarget instanceof ComponentName) {
9977 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9978 } else if (r.adjTarget != null) {
9979 pw.print(r.adjTarget.toString());
9980 } else {
9981 pw.print("{null}");
9982 }
9983 pw.print("<=");
9984 if (r.adjSource instanceof ProcessRecord) {
9985 pw.print("Proc{");
9986 pw.print(((ProcessRecord)r.adjSource).toShortString());
9987 pw.println("}");
9988 } else if (r.adjSource != null) {
9989 pw.println(r.adjSource.toString());
9990 } else {
9991 pw.println("{null}");
9992 }
9993 }
9994 if (inclDetails) {
9995 pw.print(prefix);
9996 pw.print(" ");
9997 pw.print("oom: max="); pw.print(r.maxAdj);
9998 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009999 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010000 pw.print(" curRaw="); pw.print(r.curRawAdj);
10001 pw.print(" setRaw="); pw.print(r.setRawAdj);
10002 pw.print(" cur="); pw.print(r.curAdj);
10003 pw.print(" set="); pw.println(r.setAdj);
10004 pw.print(prefix);
10005 pw.print(" ");
10006 pw.print("keeping="); pw.print(r.keeping);
10007 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010008 pw.print(" empty="); pw.print(r.empty);
10009 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010010
10011 if (!r.keeping) {
10012 if (r.lastWakeTime != 0) {
10013 long wtime;
10014 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10015 synchronized (stats) {
10016 wtime = stats.getProcessWakeTime(r.info.uid,
10017 r.pid, curRealtime);
10018 }
10019 long timeUsed = wtime - r.lastWakeTime;
10020 pw.print(prefix);
10021 pw.print(" ");
10022 pw.print("keep awake over ");
10023 TimeUtils.formatDuration(realtimeSince, pw);
10024 pw.print(" used ");
10025 TimeUtils.formatDuration(timeUsed, pw);
10026 pw.print(" (");
10027 pw.print((timeUsed*100)/realtimeSince);
10028 pw.println("%)");
10029 }
10030 if (r.lastCpuTime != 0) {
10031 long timeUsed = r.curCpuTime - r.lastCpuTime;
10032 pw.print(prefix);
10033 pw.print(" ");
10034 pw.print("run cpu over ");
10035 TimeUtils.formatDuration(uptimeSince, pw);
10036 pw.print(" used ");
10037 TimeUtils.formatDuration(timeUsed, pw);
10038 pw.print(" (");
10039 pw.print((timeUsed*100)/uptimeSince);
10040 pw.println("%)");
10041 }
10042 }
10043 }
10044 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010045 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010046 }
10047
Dianne Hackbornb437e092011-08-05 17:50:29 -070010048 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010049 ArrayList<ProcessRecord> procs;
10050 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010051 if (args != null && args.length > start
10052 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010053 procs = new ArrayList<ProcessRecord>();
10054 int pid = -1;
10055 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 } catch (NumberFormatException e) {
10058
10059 }
10060 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10061 ProcessRecord proc = mLruProcesses.get(i);
10062 if (proc.pid == pid) {
10063 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010064 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010065 procs.add(proc);
10066 }
10067 }
10068 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010069 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010070 return null;
10071 }
10072 } else {
10073 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10074 }
10075 }
10076 return procs;
10077 }
10078
10079 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10080 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010081 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010082 if (procs == null) {
10083 return;
10084 }
10085
10086 long uptime = SystemClock.uptimeMillis();
10087 long realtime = SystemClock.elapsedRealtime();
10088 pw.println("Applications Graphics Acceleration Info:");
10089 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10090
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010091 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10092 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010093 if (r.thread != null) {
10094 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10095 pw.flush();
10096 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010097 TransferPipe tp = new TransferPipe();
10098 try {
10099 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10100 tp.go(fd);
10101 } finally {
10102 tp.kill();
10103 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010104 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010105 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010106 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010107 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010109 pw.flush();
10110 }
10111 }
10112 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010113 }
10114
Jeff Brown6754ba22011-12-14 20:20:01 -080010115 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10116 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10117 if (procs == null) {
10118 return;
10119 }
10120
10121 pw.println("Applications Database Info:");
10122
10123 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10124 ProcessRecord r = procs.get(i);
10125 if (r.thread != null) {
10126 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10127 pw.flush();
10128 try {
10129 TransferPipe tp = new TransferPipe();
10130 try {
10131 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10132 tp.go(fd);
10133 } finally {
10134 tp.kill();
10135 }
10136 } catch (IOException e) {
10137 pw.println("Failure while dumping the app: " + r);
10138 pw.flush();
10139 } catch (RemoteException e) {
10140 pw.println("Got a RemoteException while dumping the app " + r);
10141 pw.flush();
10142 }
10143 }
10144 }
10145 }
10146
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010147 final static class MemItem {
10148 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010149 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010150 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010151 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010152 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010153
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010154 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010155 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010156 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010157 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010158 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010159 }
10160 }
10161
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010162 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010163 boolean sort) {
10164 if (sort) {
10165 Collections.sort(items, new Comparator<MemItem>() {
10166 @Override
10167 public int compare(MemItem lhs, MemItem rhs) {
10168 if (lhs.pss < rhs.pss) {
10169 return 1;
10170 } else if (lhs.pss > rhs.pss) {
10171 return -1;
10172 }
10173 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010174 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010175 });
10176 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010177
10178 for (int i=0; i<items.size(); i++) {
10179 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010180 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010181 if (mi.subitems != null) {
10182 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10183 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010184 }
10185 }
10186
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010187 // These are in KB.
10188 static final long[] DUMP_MEM_BUCKETS = new long[] {
10189 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10190 120*1024, 160*1024, 200*1024,
10191 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10192 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10193 };
10194
Dianne Hackborn672342c2011-11-29 11:29:02 -080010195 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10196 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010197 int start = label.lastIndexOf('.');
10198 if (start >= 0) start++;
10199 else start = 0;
10200 int end = label.length();
10201 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10202 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10203 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10204 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010205 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010206 out.append(label, start, end);
10207 return;
10208 }
10209 }
10210 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010211 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 out.append(label, start, end);
10213 }
10214
10215 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10216 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10217 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10218 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10219 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10220 };
10221 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10222 "System", "Persistent", "Foreground",
10223 "Visible", "Perceptible", "Heavy Weight",
10224 "Backup", "A Services", "Home", "Previous",
10225 "B Services", "Background"
10226 };
10227
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010228 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010229 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010230 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010231 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010232 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010233
10234 int opti = 0;
10235 while (opti < args.length) {
10236 String opt = args[opti];
10237 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10238 break;
10239 }
10240 opti++;
10241 if ("-a".equals(opt)) {
10242 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010243 } else if ("--oom".equals(opt)) {
10244 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010245 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010246 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010247 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010248 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010249 pw.println("If [process] is specified it can be the name or ");
10250 pw.println("pid of a specific process to dump.");
10251 return;
10252 } else {
10253 pw.println("Unknown argument: " + opt + "; use -h for help");
10254 }
10255 }
10256
10257 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010258 if (procs == null) {
10259 return;
10260 }
10261
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010262 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010263 long uptime = SystemClock.uptimeMillis();
10264 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010265
10266 if (procs.size() == 1 || isCheckinRequest) {
10267 dumpAll = true;
10268 }
10269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 if (isCheckinRequest) {
10271 // short checkin version
10272 pw.println(uptime + "," + realtime);
10273 pw.flush();
10274 } else {
10275 pw.println("Applications Memory Usage (kB):");
10276 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10277 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010278
Dianne Hackbornb437e092011-08-05 17:50:29 -070010279 String[] innerArgs = new String[args.length-opti];
10280 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10281
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010282 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10283 long nativePss=0, dalvikPss=0, otherPss=0;
10284 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10285
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010286 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10287 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10288 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010289
10290 long totalPss = 0;
10291
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010292 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10293 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010294 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010295 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010296 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10297 pw.flush();
10298 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010299 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010300 if (dumpAll) {
10301 try {
10302 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10303 } catch (RemoteException e) {
10304 if (!isCheckinRequest) {
10305 pw.println("Got RemoteException!");
10306 pw.flush();
10307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010309 } else {
10310 mi = new Debug.MemoryInfo();
10311 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010312 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010313
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010314 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010315 long myTotalPss = mi.getTotalPss();
10316 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010317 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010318 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010319 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010320
10321 nativePss += mi.nativePss;
10322 dalvikPss += mi.dalvikPss;
10323 otherPss += mi.otherPss;
10324 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10325 long mem = mi.getOtherPss(j);
10326 miscPss[j] += mem;
10327 otherPss -= mem;
10328 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010329
10330 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010331 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10332 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010333 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010334 if (oomProcs[oomIndex] == null) {
10335 oomProcs[oomIndex] = new ArrayList<MemItem>();
10336 }
10337 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338 break;
10339 }
10340 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 }
10343 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010344
10345 if (!isCheckinRequest && procs.size() > 1) {
10346 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10347
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010348 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10349 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10350 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010351 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010352 String label = Debug.MemoryInfo.getOtherLabel(j);
10353 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010354 }
10355
Dianne Hackbornb437e092011-08-05 17:50:29 -070010356 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10357 for (int j=0; j<oomPss.length; j++) {
10358 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010359 String label = DUMP_MEM_OOM_LABEL[j];
10360 MemItem item = new MemItem(label, label, oomPss[j],
10361 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010362 item.subitems = oomProcs[j];
10363 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010364 }
10365 }
10366
Dianne Hackborn672342c2011-11-29 11:29:02 -080010367 if (outTag != null || outStack != null) {
10368 if (outTag != null) {
10369 appendMemBucket(outTag, totalPss, "total", false);
10370 }
10371 if (outStack != null) {
10372 appendMemBucket(outStack, totalPss, "total", true);
10373 }
10374 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010375 for (int i=0; i<oomMems.size(); i++) {
10376 MemItem miCat = oomMems.get(i);
10377 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10378 continue;
10379 }
10380 if (miCat.id < ProcessList.SERVICE_ADJ
10381 || miCat.id == ProcessList.HOME_APP_ADJ
10382 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010383 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10384 outTag.append(" / ");
10385 }
10386 if (outStack != null) {
10387 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10388 if (firstLine) {
10389 outStack.append(":");
10390 firstLine = false;
10391 }
10392 outStack.append("\n\t at ");
10393 } else {
10394 outStack.append("$");
10395 }
10396 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010397 for (int j=0; j<miCat.subitems.size(); j++) {
10398 MemItem mi = miCat.subitems.get(j);
10399 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010400 if (outTag != null) {
10401 outTag.append(" ");
10402 }
10403 if (outStack != null) {
10404 outStack.append("$");
10405 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010406 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010407 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10408 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10409 }
10410 if (outStack != null) {
10411 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10412 }
10413 }
10414 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10415 outStack.append("(");
10416 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10417 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10418 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10419 outStack.append(":");
10420 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10421 }
10422 }
10423 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010424 }
10425 }
10426 }
10427 }
10428
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010429 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010430 pw.println();
10431 pw.println("Total PSS by process:");
10432 dumpMemItems(pw, " ", procMems, true);
10433 pw.println();
10434 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010435 pw.println("Total PSS by OOM adjustment:");
10436 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010437 if (!oomOnly) {
10438 PrintWriter out = categoryPw != null ? categoryPw : pw;
10439 out.println();
10440 out.println("Total PSS by category:");
10441 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010442 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010443 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010444 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010445 final int[] SINGLE_LONG_FORMAT = new int[] {
10446 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10447 };
10448 long[] longOut = new long[1];
10449 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10450 SINGLE_LONG_FORMAT, null, longOut, null);
10451 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10452 longOut[0] = 0;
10453 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10454 SINGLE_LONG_FORMAT, null, longOut, null);
10455 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10456 longOut[0] = 0;
10457 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10458 SINGLE_LONG_FORMAT, null, longOut, null);
10459 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10460 longOut[0] = 0;
10461 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10462 SINGLE_LONG_FORMAT, null, longOut, null);
10463 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10464 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10465 pw.print(shared); pw.println(" kB");
10466 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10467 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010469 }
10470
10471 /**
10472 * Searches array of arguments for the specified string
10473 * @param args array of argument strings
10474 * @param value value to search for
10475 * @return true if the value is contained in the array
10476 */
10477 private static boolean scanArgs(String[] args, String value) {
10478 if (args != null) {
10479 for (String arg : args) {
10480 if (value.equals(arg)) {
10481 return true;
10482 }
10483 }
10484 }
10485 return false;
10486 }
10487
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010488 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10489 ContentProviderRecord cpr, boolean always) {
10490 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10491
10492 if (!inLaunching || always) {
10493 synchronized (cpr) {
10494 cpr.launchingApp = null;
10495 cpr.notifyAll();
10496 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010497 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010498 String names[] = cpr.info.authority.split(";");
10499 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010500 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010501 }
10502 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010503
10504 for (int i=0; i<cpr.connections.size(); i++) {
10505 ContentProviderConnection conn = cpr.connections.get(i);
10506 if (conn.waiting) {
10507 // If this connection is waiting for the provider, then we don't
10508 // need to mess with its process unless we are always removing
10509 // or for some reason the provider is not currently launching.
10510 if (inLaunching && !always) {
10511 continue;
10512 }
10513 }
10514 ProcessRecord capp = conn.client;
10515 conn.dead = true;
10516 if (conn.stableCount > 0) {
10517 if (!capp.persistent && capp.thread != null
10518 && capp.pid != 0
10519 && capp.pid != MY_PID) {
10520 Slog.i(TAG, "Kill " + capp.processName
10521 + " (pid " + capp.pid + "): provider " + cpr.info.name
10522 + " in dying process " + (proc != null ? proc.processName : "??"));
10523 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10524 capp.processName, capp.setAdj, "dying provider "
10525 + cpr.name.toShortString());
10526 Process.killProcessQuiet(capp.pid);
10527 }
10528 } else if (capp.thread != null && conn.provider.provider != null) {
10529 try {
10530 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10531 } catch (RemoteException e) {
10532 }
10533 // In the protocol here, we don't expect the client to correctly
10534 // clean up this connection, we'll just remove it.
10535 cpr.connections.remove(i);
10536 conn.client.conProviders.remove(conn);
10537 }
10538 }
10539
10540 if (inLaunching && always) {
10541 mLaunchingProviders.remove(cpr);
10542 }
10543 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 }
10545
10546 /**
10547 * Main code for cleaning up a process when it has gone away. This is
10548 * called both as a result of the process dying, or directly when stopping
10549 * a process when running in single process mode.
10550 */
10551 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010552 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010554 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010555 }
10556
Dianne Hackborn36124872009-10-08 16:22:03 -070010557 mProcessesToGc.remove(app);
10558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 // Dismiss any open dialogs.
10560 if (app.crashDialog != null) {
10561 app.crashDialog.dismiss();
10562 app.crashDialog = null;
10563 }
10564 if (app.anrDialog != null) {
10565 app.anrDialog.dismiss();
10566 app.anrDialog = null;
10567 }
10568 if (app.waitDialog != null) {
10569 app.waitDialog.dismiss();
10570 app.waitDialog = null;
10571 }
10572
10573 app.crashing = false;
10574 app.notResponding = false;
10575
10576 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010577 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 app.thread = null;
10579 app.forcingToForeground = null;
10580 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010581 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010582 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010583 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010585 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010586
10587 boolean restart = false;
10588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 // Remove published content providers.
10590 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010591 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010593 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010594
10595 final boolean always = app.bad || !allowRestart;
10596 if (removeDyingProviderLocked(app, cpr, always) || always) {
10597 // We left the provider in the launching list, need to
10598 // restart it.
10599 restart = true;
10600 }
10601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010603 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 }
10605 app.pubProviders.clear();
10606 }
10607
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010608 // Take care of any launching providers waiting for this process.
10609 if (checkAppInLaunchingProvidersLocked(app, false)) {
10610 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010613 // Unregister from connected content providers.
10614 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010615 for (int i=0; i<app.conProviders.size(); i++) {
10616 ContentProviderConnection conn = app.conProviders.get(i);
10617 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 }
10619 app.conProviders.clear();
10620 }
10621
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010622 // At this point there may be remaining entries in mLaunchingProviders
10623 // where we were the only one waiting, so they are no longer of use.
10624 // Look for these and clean up if found.
10625 // XXX Commented out for now. Trying to figure out a way to reproduce
10626 // the actual situation to identify what is actually going on.
10627 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010628 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010629 ContentProviderRecord cpr = (ContentProviderRecord)
10630 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010631 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010632 synchronized (cpr) {
10633 cpr.launchingApp = null;
10634 cpr.notifyAll();
10635 }
10636 }
10637 }
10638 }
10639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010640 skipCurrentReceiverLocked(app);
10641
10642 // Unregister any receivers.
10643 if (app.receivers.size() > 0) {
10644 Iterator<ReceiverList> it = app.receivers.iterator();
10645 while (it.hasNext()) {
10646 removeReceiverLocked(it.next());
10647 }
10648 app.receivers.clear();
10649 }
10650
Christopher Tate181fafa2009-05-14 11:12:14 -070010651 // If the app is undergoing backup, tell the backup manager about it
10652 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010653 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010654 try {
10655 IBackupManager bm = IBackupManager.Stub.asInterface(
10656 ServiceManager.getService(Context.BACKUP_SERVICE));
10657 bm.agentDisconnected(app.info.packageName);
10658 } catch (RemoteException e) {
10659 // can't happen; backup manager is local
10660 }
10661 }
10662
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010663 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10664 ProcessChangeItem item = mPendingProcessChanges.get(i);
10665 if (item.pid == app.pid) {
10666 mPendingProcessChanges.remove(i);
10667 mAvailProcessChanges.add(item);
10668 }
10669 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010670 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 // If the caller is restarting this app, then leave it in its
10673 // current lists and let the caller take care of it.
10674 if (restarting) {
10675 return;
10676 }
10677
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010678 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010679 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010680 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010681 mProcessNames.remove(app.processName, app.uid);
10682 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010683 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010684 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10685 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010686 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 } else if (!app.removed) {
10689 // This app is persistent, so we need to keep its record around.
10690 // If it is not already on the pending app list, add it there
10691 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10693 mPersistentStartingProcesses.add(app);
10694 restart = true;
10695 }
10696 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010697 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10698 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 mProcessesOnHold.remove(app);
10700
The Android Open Source Project4df24232009-03-05 14:34:35 -080010701 if (app == mHomeProcess) {
10702 mHomeProcess = null;
10703 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010704 if (app == mPreviousProcess) {
10705 mPreviousProcess = null;
10706 }
10707
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010708 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 // We have components that still need to be running in the
10710 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010711 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010712 startProcessLocked(app, "restart", app.processName);
10713 } else if (app.pid > 0 && app.pid != MY_PID) {
10714 // Goodbye!
10715 synchronized (mPidsSelfLocked) {
10716 mPidsSelfLocked.remove(app.pid);
10717 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10718 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010719 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010720 }
10721 }
10722
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010723 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10724 // Look through the content providers we are waiting to have launched,
10725 // and if any run in this process then either schedule a restart of
10726 // the process or kill the client waiting for it if this process has
10727 // gone bad.
10728 int NL = mLaunchingProviders.size();
10729 boolean restart = false;
10730 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010731 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010732 if (cpr.launchingApp == app) {
10733 if (!alwaysBad && !app.bad) {
10734 restart = true;
10735 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010736 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010737 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010738 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010739 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010740 }
10741 }
10742 }
10743 return restart;
10744 }
10745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010746 // =========================================================
10747 // SERVICES
10748 // =========================================================
10749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10751 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010752 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010754 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 }
10756 }
10757
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010758 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010759 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010760 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010761 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010762 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010763 }
10764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010765 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010766 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010767 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010768 // Refuse possible leaked file descriptors
10769 if (service != null && service.hasFileDescriptors() == true) {
10770 throw new IllegalArgumentException("File descriptors passed in Intent");
10771 }
10772
Amith Yamasani742a6712011-05-04 14:49:28 -070010773 if (DEBUG_SERVICE)
10774 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 synchronized(this) {
10776 final int callingPid = Binder.getCallingPid();
10777 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010778 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010780 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010781 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 Binder.restoreCallingIdentity(origId);
10783 return res;
10784 }
10785 }
10786
10787 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010788 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010790 if (DEBUG_SERVICE)
10791 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010793 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010794 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 Binder.restoreCallingIdentity(origId);
10796 return res;
10797 }
10798 }
10799
10800 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010801 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010802 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 // Refuse possible leaked file descriptors
10804 if (service != null && service.hasFileDescriptors() == true) {
10805 throw new IllegalArgumentException("File descriptors passed in Intent");
10806 }
10807
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010808 checkValidCaller(Binder.getCallingUid(), userId);
10809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010811 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 }
10814
10815 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010816 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 // Refuse possible leaked file descriptors
10818 if (service != null && service.hasFileDescriptors() == true) {
10819 throw new IllegalArgumentException("File descriptors passed in Intent");
10820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010822 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 }
10825
10826 public boolean stopServiceToken(ComponentName className, IBinder token,
10827 int startId) {
10828 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010829 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 }
10832
10833 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010834 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010836 mServices.setServiceForegroundLocked(className, token, id, notification,
10837 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 }
10839 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010840
Dianne Hackborn41203752012-08-31 14:05:51 -070010841 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10842 boolean requireFull, String name, String callerPackage) {
10843 synchronized(this) {
10844 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10845 requireFull, name, callerPackage);
10846 }
10847 }
10848
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010849 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10850 boolean requireFull, String name, String callerPackage) {
10851 final int callingUserId = UserHandle.getUserId(callingUid);
10852 if (callingUserId != userId) {
10853 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10854 if ((requireFull || checkComponentPermission(
10855 android.Manifest.permission.INTERACT_ACROSS_USERS,
10856 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10857 && checkComponentPermission(
10858 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10859 callingPid, callingUid, -1, true)
10860 != PackageManager.PERMISSION_GRANTED) {
10861 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10862 // In this case, they would like to just execute as their
10863 // owner user instead of failing.
10864 userId = callingUserId;
10865 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010866 StringBuilder builder = new StringBuilder(128);
10867 builder.append("Permission Denial: ");
10868 builder.append(name);
10869 if (callerPackage != null) {
10870 builder.append(" from ");
10871 builder.append(callerPackage);
10872 }
10873 builder.append(" asks to run as user ");
10874 builder.append(userId);
10875 builder.append(" but is calling from user ");
10876 builder.append(UserHandle.getUserId(callingUid));
10877 builder.append("; this requires ");
10878 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10879 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010880 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010881 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10882 }
10883 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010884 Slog.w(TAG, msg);
10885 throw new SecurityException(msg);
10886 }
10887 }
10888 }
10889 if (userId == UserHandle.USER_CURRENT
10890 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10891 userId = mCurrentUserId;
10892 }
10893 if (!allowAll && userId < 0) {
10894 throw new IllegalArgumentException(
10895 "Call does not support special user #" + userId);
10896 }
10897 }
10898 return userId;
10899 }
10900
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010901 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10902 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010903 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010904 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010905 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10906 if (ActivityManager.checkUidPermission(
10907 android.Manifest.permission.INTERACT_ACROSS_USERS,
10908 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10909 ComponentName comp = new ComponentName(aInfo.packageName, className);
10910 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10911 + " requests FLAG_SINGLE_USER, but app does not hold "
10912 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10913 Slog.w(TAG, msg);
10914 throw new SecurityException(msg);
10915 }
10916 result = true;
10917 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010918 } else if (componentProcessName == aInfo.packageName) {
10919 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10920 } else if ("system".equals(componentProcessName)) {
10921 result = true;
10922 }
10923 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010924 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10925 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010926 }
10927 return result;
10928 }
10929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010930 public int bindService(IApplicationThread caller, IBinder token,
10931 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010932 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010933 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 // Refuse possible leaked file descriptors
10935 if (service != null && service.hasFileDescriptors() == true) {
10936 throw new IllegalArgumentException("File descriptors passed in Intent");
10937 }
10938
10939 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010940 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10941 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010942 }
10943 }
10944
10945 public boolean unbindService(IServiceConnection connection) {
10946 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010947 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010949 }
10950
10951 public void publishService(IBinder token, Intent intent, IBinder service) {
10952 // Refuse possible leaked file descriptors
10953 if (intent != null && intent.hasFileDescriptors() == true) {
10954 throw new IllegalArgumentException("File descriptors passed in Intent");
10955 }
10956
10957 synchronized(this) {
10958 if (!(token instanceof ServiceRecord)) {
10959 throw new IllegalArgumentException("Invalid service token");
10960 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010961 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962 }
10963 }
10964
10965 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10966 // Refuse possible leaked file descriptors
10967 if (intent != null && intent.hasFileDescriptors() == true) {
10968 throw new IllegalArgumentException("File descriptors passed in Intent");
10969 }
10970
10971 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010972 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010973 }
10974 }
10975
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010976 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 synchronized(this) {
10978 if (!(token instanceof ServiceRecord)) {
10979 throw new IllegalArgumentException("Invalid service token");
10980 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010981 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983 }
10984
10985 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010986 // BACKUP AND RESTORE
10987 // =========================================================
10988
10989 // Cause the target app to be launched if necessary and its backup agent
10990 // instantiated. The backup agent will invoke backupAgentCreated() on the
10991 // activity manager to announce its creation.
10992 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010993 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010994 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10995
10996 synchronized(this) {
10997 // !!! TODO: currently no check here that we're already bound
10998 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10999 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11000 synchronized (stats) {
11001 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
11002 }
11003
Dianne Hackborne7f97212011-02-24 14:40:20 -080011004 // Backup agent is now in use, its package can't be stopped.
11005 try {
11006 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011007 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080011008 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011009 } catch (IllegalArgumentException e) {
11010 Slog.w(TAG, "Failed trying to unstop package "
11011 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011012 }
11013
Christopher Tate181fafa2009-05-14 11:12:14 -070011014 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011015 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11016 ? new ComponentName(app.packageName, app.backupAgentName)
11017 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011018 // startProcessLocked() returns existing proc's record if it's already running
11019 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011020 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011021 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011022 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011023 return false;
11024 }
11025
11026 r.app = proc;
11027 mBackupTarget = r;
11028 mBackupAppName = app.packageName;
11029
Christopher Tate6fa95972009-06-05 18:43:55 -070011030 // Try not to kill the process during backup
11031 updateOomAdjLocked(proc);
11032
Christopher Tate181fafa2009-05-14 11:12:14 -070011033 // If the process is already attached, schedule the creation of the backup agent now.
11034 // If it is not yet live, this will be done when it attaches to the framework.
11035 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011036 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011037 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011038 proc.thread.scheduleCreateBackupAgent(app,
11039 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011040 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011041 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011042 }
11043 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011044 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011045 }
11046 // Invariants: at this point, the target app process exists and the application
11047 // is either already running or in the process of coming up. mBackupTarget and
11048 // mBackupAppName describe the app, so that when it binds back to the AM we
11049 // know that it's scheduled for a backup-agent operation.
11050 }
11051
11052 return true;
11053 }
11054
11055 // A backup agent has just come up
11056 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011057 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011058 + " = " + agent);
11059
11060 synchronized(this) {
11061 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011062 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011063 return;
11064 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011065 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011066
Dianne Hackborn06740692010-09-22 22:46:21 -070011067 long oldIdent = Binder.clearCallingIdentity();
11068 try {
11069 IBackupManager bm = IBackupManager.Stub.asInterface(
11070 ServiceManager.getService(Context.BACKUP_SERVICE));
11071 bm.agentConnected(agentPackageName, agent);
11072 } catch (RemoteException e) {
11073 // can't happen; the backup manager service is local
11074 } catch (Exception e) {
11075 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11076 e.printStackTrace();
11077 } finally {
11078 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011079 }
11080 }
11081
11082 // done with this agent
11083 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011084 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011085 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011086 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011087 return;
11088 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011089
11090 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011091 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011092 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011093 return;
11094 }
11095
Christopher Tate181fafa2009-05-14 11:12:14 -070011096 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011097 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011098 return;
11099 }
11100
Christopher Tate6fa95972009-06-05 18:43:55 -070011101 ProcessRecord proc = mBackupTarget.app;
11102 mBackupTarget = null;
11103 mBackupAppName = null;
11104
11105 // Not backing this app up any more; reset its OOM adjustment
11106 updateOomAdjLocked(proc);
11107
Christopher Tatec7b31e32009-06-10 15:49:30 -070011108 // If the app crashed during backup, 'thread' will be null here
11109 if (proc.thread != null) {
11110 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011111 proc.thread.scheduleDestroyBackupAgent(appInfo,
11112 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011113 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011114 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011115 e.printStackTrace();
11116 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011117 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011118 }
11119 }
11120 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 // BROADCASTS
11122 // =========================================================
11123
Josh Bartel7f208742010-02-25 11:01:44 -060011124 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011125 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011127 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11128 if (stickies == null) {
11129 return cur;
11130 }
11131 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 if (list == null) {
11133 return cur;
11134 }
11135 int N = list.size();
11136 for (int i=0; i<N; i++) {
11137 Intent intent = list.get(i);
11138 if (filter.match(resolver, intent, true, TAG) >= 0) {
11139 if (cur == null) {
11140 cur = new ArrayList<Intent>();
11141 }
11142 cur.add(intent);
11143 }
11144 }
11145 return cur;
11146 }
11147
Christopher Tatef46723b2012-01-26 14:19:24 -080011148 boolean isPendingBroadcastProcessLocked(int pid) {
11149 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11150 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152
Christopher Tatef46723b2012-01-26 14:19:24 -080011153 void skipPendingBroadcastLocked(int pid) {
11154 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11155 for (BroadcastQueue queue : mBroadcastQueues) {
11156 queue.skipPendingBroadcastLocked(pid);
11157 }
11158 }
11159
11160 // The app just attached; send any pending broadcasts that it should receive
11161 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11162 boolean didSomething = false;
11163 for (BroadcastQueue queue : mBroadcastQueues) {
11164 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011166 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 }
11168
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011169 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011170 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011171 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011172 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011173 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 synchronized(this) {
11175 ProcessRecord callerApp = null;
11176 if (caller != null) {
11177 callerApp = getRecordForAppLocked(caller);
11178 if (callerApp == null) {
11179 throw new SecurityException(
11180 "Unable to find app for caller " + caller
11181 + " (pid=" + Binder.getCallingPid()
11182 + ") when registering receiver " + receiver);
11183 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011184 if (callerApp.info.uid != Process.SYSTEM_UID &&
11185 !callerApp.pkgList.contains(callerPackage)) {
11186 throw new SecurityException("Given caller package " + callerPackage
11187 + " is not running in process " + callerApp);
11188 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011189 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011190 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011191 } else {
11192 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011193 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011194 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 }
11196
Dianne Hackborn20e80982012-08-31 19:00:44 -070011197 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11198 true, true, "registerReceiver", callerPackage);
11199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 List allSticky = null;
11201
11202 // Look for any matching sticky broadcasts...
11203 Iterator actions = filter.actionsIterator();
11204 if (actions != null) {
11205 while (actions.hasNext()) {
11206 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011207 allSticky = getStickiesLocked(action, filter, allSticky,
11208 UserHandle.USER_ALL);
11209 allSticky = getStickiesLocked(action, filter, allSticky,
11210 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 }
11212 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011213 allSticky = getStickiesLocked(null, filter, allSticky,
11214 UserHandle.USER_ALL);
11215 allSticky = getStickiesLocked(null, filter, allSticky,
11216 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 }
11218
11219 // The first sticky in the list is returned directly back to
11220 // the client.
11221 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11222
Joe Onorato8a9b2202010-02-26 18:56:32 -080011223 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011224 + ": " + sticky);
11225
11226 if (receiver == null) {
11227 return sticky;
11228 }
11229
11230 ReceiverList rl
11231 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11232 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011233 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11234 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 if (rl.app != null) {
11236 rl.app.receivers.add(rl);
11237 } else {
11238 try {
11239 receiver.asBinder().linkToDeath(rl, 0);
11240 } catch (RemoteException e) {
11241 return sticky;
11242 }
11243 rl.linkedToDeath = true;
11244 }
11245 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011246 } else if (rl.uid != callingUid) {
11247 throw new IllegalArgumentException(
11248 "Receiver requested to register for uid " + callingUid
11249 + " was previously registered for uid " + rl.uid);
11250 } else if (rl.pid != callingPid) {
11251 throw new IllegalArgumentException(
11252 "Receiver requested to register for pid " + callingPid
11253 + " was previously registered for pid " + rl.pid);
11254 } else if (rl.userId != userId) {
11255 throw new IllegalArgumentException(
11256 "Receiver requested to register for user " + userId
11257 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011259 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011260 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 rl.add(bf);
11262 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011263 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 }
11265 mReceiverResolver.addFilter(bf);
11266
11267 // Enqueue broadcasts for all existing stickies that match
11268 // this filter.
11269 if (allSticky != null) {
11270 ArrayList receivers = new ArrayList();
11271 receivers.add(bf);
11272
11273 int N = allSticky.size();
11274 for (int i=0; i<N; i++) {
11275 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011276 BroadcastQueue queue = broadcastQueueForIntent(intent);
11277 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011279 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011280 queue.enqueueParallelBroadcastLocked(r);
11281 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 }
11283 }
11284
11285 return sticky;
11286 }
11287 }
11288
11289 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011290 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011291
Christopher Tatef46723b2012-01-26 14:19:24 -080011292 final long origId = Binder.clearCallingIdentity();
11293 try {
11294 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295
Christopher Tatef46723b2012-01-26 14:19:24 -080011296 synchronized(this) {
11297 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011298 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011299 if (rl != null) {
11300 if (rl.curBroadcast != null) {
11301 BroadcastRecord r = rl.curBroadcast;
11302 final boolean doNext = finishReceiverLocked(
11303 receiver.asBinder(), r.resultCode, r.resultData,
11304 r.resultExtras, r.resultAbort, true);
11305 if (doNext) {
11306 doTrim = true;
11307 r.queue.processNextBroadcast(false);
11308 }
11309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310
Christopher Tatef46723b2012-01-26 14:19:24 -080011311 if (rl.app != null) {
11312 rl.app.receivers.remove(rl);
11313 }
11314 removeReceiverLocked(rl);
11315 if (rl.linkedToDeath) {
11316 rl.linkedToDeath = false;
11317 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 }
11320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321
Christopher Tatef46723b2012-01-26 14:19:24 -080011322 // If we actually concluded any broadcasts, we might now be able
11323 // to trim the recipients' apps from our working set
11324 if (doTrim) {
11325 trimApplications();
11326 return;
11327 }
11328
11329 } finally {
11330 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 }
11333
11334 void removeReceiverLocked(ReceiverList rl) {
11335 mRegisteredReceivers.remove(rl.receiver.asBinder());
11336 int N = rl.size();
11337 for (int i=0; i<N; i++) {
11338 mReceiverResolver.removeFilter(rl.get(i));
11339 }
11340 }
11341
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011342 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011343 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11344 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011345 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011346 try {
11347 r.thread.dispatchPackageBroadcast(cmd, packages);
11348 } catch (RemoteException ex) {
11349 }
11350 }
11351 }
11352 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011353
11354 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11355 int[] users) {
11356 List<ResolveInfo> receivers = null;
11357 try {
11358 HashSet<ComponentName> singleUserReceivers = null;
11359 boolean scannedFirstReceivers = false;
11360 for (int user : users) {
11361 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11362 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11363 if (newReceivers != null && newReceivers.size() == 0) {
11364 newReceivers = null;
11365 }
11366 if (receivers == null) {
11367 receivers = newReceivers;
11368 } else if (newReceivers != null) {
11369 // We need to concatenate the additional receivers
11370 // found with what we have do far. This would be easy,
11371 // but we also need to de-dup any receivers that are
11372 // singleUser.
11373 if (!scannedFirstReceivers) {
11374 // Collect any single user receivers we had already retrieved.
11375 scannedFirstReceivers = true;
11376 for (int i=0; i<receivers.size(); i++) {
11377 ResolveInfo ri = receivers.get(i);
11378 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11379 ComponentName cn = new ComponentName(
11380 ri.activityInfo.packageName, ri.activityInfo.name);
11381 if (singleUserReceivers == null) {
11382 singleUserReceivers = new HashSet<ComponentName>();
11383 }
11384 singleUserReceivers.add(cn);
11385 }
11386 }
11387 }
11388 // Add the new results to the existing results, tracking
11389 // and de-dupping single user receivers.
11390 for (int i=0; i<newReceivers.size(); i++) {
11391 ResolveInfo ri = receivers.get(i);
11392 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11393 ComponentName cn = new ComponentName(
11394 ri.activityInfo.packageName, ri.activityInfo.name);
11395 if (singleUserReceivers == null) {
11396 singleUserReceivers = new HashSet<ComponentName>();
11397 }
11398 if (!singleUserReceivers.contains(cn)) {
11399 singleUserReceivers.add(cn);
11400 receivers.add(ri);
11401 }
11402 } else {
11403 receivers.add(ri);
11404 }
11405 }
11406 }
11407 }
11408 } catch (RemoteException ex) {
11409 // pm is in same process, this will never happen.
11410 }
11411 return receivers;
11412 }
11413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 private final int broadcastIntentLocked(ProcessRecord callerApp,
11415 String callerPackage, Intent intent, String resolvedType,
11416 IIntentReceiver resultTo, int resultCode, String resultData,
11417 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011418 boolean ordered, boolean sticky, int callingPid, int callingUid,
11419 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 intent = new Intent(intent);
11421
Dianne Hackborne7f97212011-02-24 14:40:20 -080011422 // By default broadcasts do not go to stopped apps.
11423 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11424
Joe Onorato8a9b2202010-02-26 18:56:32 -080011425 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011427 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011429 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011431
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011432 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11433 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011434
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011435 // Make sure that the user who is receiving this broadcast is started
11436 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011437 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011438 Slog.w(TAG, "Skipping broadcast of " + intent
11439 + ": user " + userId + " is stopped");
11440 return ActivityManager.BROADCAST_SUCCESS;
11441 }
11442
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011443 /*
11444 * Prevent non-system code (defined here to be non-persistent
11445 * processes) from sending protected broadcasts.
11446 */
11447 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11448 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11449 callingUid == 0) {
11450 // Always okay.
11451 } else if (callerApp == null || !callerApp.persistent) {
11452 try {
11453 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11454 intent.getAction())) {
11455 String msg = "Permission Denial: not allowed to send broadcast "
11456 + intent.getAction() + " from pid="
11457 + callingPid + ", uid=" + callingUid;
11458 Slog.w(TAG, msg);
11459 throw new SecurityException(msg);
11460 }
11461 } catch (RemoteException e) {
11462 Slog.w(TAG, "Remote exception", e);
11463 return ActivityManager.BROADCAST_SUCCESS;
11464 }
11465 }
11466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011467 // Handle special intents: if this broadcast is from the package
11468 // manager about a package being removed, we need to remove all of
11469 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011470 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011472 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11473 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011474 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 || uidRemoved) {
11476 if (checkComponentPermission(
11477 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011478 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479 == PackageManager.PERMISSION_GRANTED) {
11480 if (uidRemoved) {
11481 final Bundle intentExtras = intent.getExtras();
11482 final int uid = intentExtras != null
11483 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11484 if (uid >= 0) {
11485 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11486 synchronized (bs) {
11487 bs.removeUidStatsLocked(uid);
11488 }
11489 }
11490 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011491 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011492 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011493 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011494 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11495 if (list != null && (list.length > 0)) {
11496 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011497 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011498 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011499 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011501 }
11502 } else {
11503 Uri data = intent.getData();
11504 String ssp;
11505 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11506 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11507 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011508 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11509 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011510 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011511 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011512 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011513 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 }
11516 }
11517 }
11518 } else {
11519 String msg = "Permission Denial: " + intent.getAction()
11520 + " broadcast from " + callerPackage + " (pid=" + callingPid
11521 + ", uid=" + callingUid + ")"
11522 + " requires "
11523 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011524 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011525 throw new SecurityException(msg);
11526 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011527
11528 // Special case for adding a package: by default turn on compatibility
11529 // mode.
11530 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011531 Uri data = intent.getData();
11532 String ssp;
11533 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11534 mCompatModePackages.handlePackageAddedLocked(ssp,
11535 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011537 }
11538
11539 /*
11540 * If this is the time zone changed action, queue up a message that will reset the timezone
11541 * of all currently running processes. This message will get queued up before the broadcast
11542 * happens.
11543 */
11544 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11545 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11546 }
11547
Robert Greenwalt03595d02010-11-02 14:08:23 -070011548 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11549 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11550 }
11551
Robert Greenwalt434203a2010-10-11 16:00:27 -070011552 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11553 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11554 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11555 }
11556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 // Add to the sticky list if requested.
11558 if (sticky) {
11559 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11560 callingPid, callingUid)
11561 != PackageManager.PERMISSION_GRANTED) {
11562 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11563 + callingPid + ", uid=" + callingUid
11564 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011565 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011566 throw new SecurityException(msg);
11567 }
11568 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011569 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011571 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011572 }
11573 if (intent.getComponent() != null) {
11574 throw new SecurityException(
11575 "Sticky broadcasts can't target a specific component");
11576 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011577 // We use userId directly here, since the "all" target is maintained
11578 // as a separate set of sticky broadcasts.
11579 if (userId != UserHandle.USER_ALL) {
11580 // But first, if this is not a broadcast to all users, then
11581 // make sure it doesn't conflict with an existing broadcast to
11582 // all users.
11583 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11584 UserHandle.USER_ALL);
11585 if (stickies != null) {
11586 ArrayList<Intent> list = stickies.get(intent.getAction());
11587 if (list != null) {
11588 int N = list.size();
11589 int i;
11590 for (i=0; i<N; i++) {
11591 if (intent.filterEquals(list.get(i))) {
11592 throw new IllegalArgumentException(
11593 "Sticky broadcast " + intent + " for user "
11594 + userId + " conflicts with existing global broadcast");
11595 }
11596 }
11597 }
11598 }
11599 }
11600 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11601 if (stickies == null) {
11602 stickies = new HashMap<String, ArrayList<Intent>>();
11603 mStickyBroadcasts.put(userId, stickies);
11604 }
11605 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 if (list == null) {
11607 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011608 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 }
11610 int N = list.size();
11611 int i;
11612 for (i=0; i<N; i++) {
11613 if (intent.filterEquals(list.get(i))) {
11614 // This sticky already exists, replace it.
11615 list.set(i, new Intent(intent));
11616 break;
11617 }
11618 }
11619 if (i >= N) {
11620 list.add(new Intent(intent));
11621 }
11622 }
11623
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011624 int[] users;
11625 if (userId == UserHandle.USER_ALL) {
11626 // Caller wants broadcast to go to all started users.
11627 users = new int[mStartedUsers.size()];
11628 for (int i=0; i<mStartedUsers.size(); i++) {
11629 users[i] = mStartedUsers.keyAt(i);
11630 }
11631 } else {
11632 // Caller wants broadcast to go to one specific user.
11633 users = new int[] {userId};
11634 }
11635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 // Figure out who all will receive this broadcast.
11637 List receivers = null;
11638 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011639 // Need to resolve the intent to interested receivers...
11640 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11641 == 0) {
11642 receivers = collectReceiverComponents(intent, resolvedType, users);
11643 }
11644 if (intent.getComponent() == null) {
11645 registeredReceivers = mReceiverResolver.queryIntent(intent,
11646 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 }
11648
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011649 final boolean replacePending =
11650 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11651
Joe Onorato8a9b2202010-02-26 18:56:32 -080011652 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011653 + " replacePending=" + replacePending);
11654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11656 if (!ordered && NR > 0) {
11657 // If we are not serializing this broadcast, then send the
11658 // registered receivers separately so they don't wait for the
11659 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011660 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11661 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 callerPackage, callingPid, callingUid, requiredPermission,
11663 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011664 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011665 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011666 TAG, "Enqueueing parallel broadcast " + r);
11667 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011668 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011669 queue.enqueueParallelBroadcastLocked(r);
11670 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 registeredReceivers = null;
11673 NR = 0;
11674 }
11675
11676 // Merge into one list.
11677 int ir = 0;
11678 if (receivers != null) {
11679 // A special case for PACKAGE_ADDED: do not allow the package
11680 // being added to see this broadcast. This prevents them from
11681 // using this as a back door to get run as soon as they are
11682 // installed. Maybe in the future we want to have a special install
11683 // broadcast or such for apps, but we'd like to deliberately make
11684 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011685 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011686 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11687 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11688 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011689 Uri data = intent.getData();
11690 if (data != null) {
11691 String pkgName = data.getSchemeSpecificPart();
11692 if (pkgName != null) {
11693 skipPackages = new String[] { pkgName };
11694 }
11695 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011696 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011697 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011698 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011699 if (skipPackages != null && (skipPackages.length > 0)) {
11700 for (String skipPackage : skipPackages) {
11701 if (skipPackage != null) {
11702 int NT = receivers.size();
11703 for (int it=0; it<NT; it++) {
11704 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11705 if (curt.activityInfo.packageName.equals(skipPackage)) {
11706 receivers.remove(it);
11707 it--;
11708 NT--;
11709 }
11710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 }
11712 }
11713 }
11714
11715 int NT = receivers != null ? receivers.size() : 0;
11716 int it = 0;
11717 ResolveInfo curt = null;
11718 BroadcastFilter curr = null;
11719 while (it < NT && ir < NR) {
11720 if (curt == null) {
11721 curt = (ResolveInfo)receivers.get(it);
11722 }
11723 if (curr == null) {
11724 curr = registeredReceivers.get(ir);
11725 }
11726 if (curr.getPriority() >= curt.priority) {
11727 // Insert this broadcast record into the final list.
11728 receivers.add(it, curr);
11729 ir++;
11730 curr = null;
11731 it++;
11732 NT++;
11733 } else {
11734 // Skip to the next ResolveInfo in the final list.
11735 it++;
11736 curt = null;
11737 }
11738 }
11739 }
11740 while (ir < NR) {
11741 if (receivers == null) {
11742 receivers = new ArrayList();
11743 }
11744 receivers.add(registeredReceivers.get(ir));
11745 ir++;
11746 }
11747
11748 if ((receivers != null && receivers.size() > 0)
11749 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011750 BroadcastQueue queue = broadcastQueueForIntent(intent);
11751 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011753 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011754 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011755 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011757 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758 if (DEBUG_BROADCAST) {
11759 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011760 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011762 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011763 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011764 queue.enqueueOrderedBroadcastLocked(r);
11765 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 }
11768
Dianne Hackborna4972e92012-03-14 10:38:05 -070011769 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 }
11771
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011772 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773 // Refuse possible leaked file descriptors
11774 if (intent != null && intent.hasFileDescriptors() == true) {
11775 throw new IllegalArgumentException("File descriptors passed in Intent");
11776 }
11777
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011778 int flags = intent.getFlags();
11779
11780 if (!mProcessesReady) {
11781 // if the caller really truly claims to know what they're doing, go
11782 // ahead and allow the broadcast without launching any receivers
11783 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11784 intent = new Intent(intent);
11785 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11786 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11787 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11788 + " before boot completion");
11789 throw new IllegalStateException("Cannot broadcast before boot completed");
11790 }
11791 }
11792
11793 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11794 throw new IllegalArgumentException(
11795 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11796 }
11797
11798 return intent;
11799 }
11800
11801 public final int broadcastIntent(IApplicationThread caller,
11802 Intent intent, String resolvedType, IIntentReceiver resultTo,
11803 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011804 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011805 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011807 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11810 final int callingPid = Binder.getCallingPid();
11811 final int callingUid = Binder.getCallingUid();
11812 final long origId = Binder.clearCallingIdentity();
11813 int res = broadcastIntentLocked(callerApp,
11814 callerApp != null ? callerApp.info.packageName : null,
11815 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011816 resultCode, resultData, map, requiredPermission, serialized, sticky,
11817 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011818 Binder.restoreCallingIdentity(origId);
11819 return res;
11820 }
11821 }
11822
11823 int broadcastIntentInPackage(String packageName, int uid,
11824 Intent intent, String resolvedType, IIntentReceiver resultTo,
11825 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011826 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011828 intent = verifyBroadcastLocked(intent);
11829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 final long origId = Binder.clearCallingIdentity();
11831 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11832 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011833 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 Binder.restoreCallingIdentity(origId);
11835 return res;
11836 }
11837 }
11838
Amith Yamasani742a6712011-05-04 14:49:28 -070011839 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840 // Refuse possible leaked file descriptors
11841 if (intent != null && intent.hasFileDescriptors() == true) {
11842 throw new IllegalArgumentException("File descriptors passed in Intent");
11843 }
11844
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011845 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11846 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 synchronized(this) {
11849 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11850 != PackageManager.PERMISSION_GRANTED) {
11851 String msg = "Permission Denial: unbroadcastIntent() from pid="
11852 + Binder.getCallingPid()
11853 + ", uid=" + Binder.getCallingUid()
11854 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011855 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 throw new SecurityException(msg);
11857 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011858 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11859 if (stickies != null) {
11860 ArrayList<Intent> list = stickies.get(intent.getAction());
11861 if (list != null) {
11862 int N = list.size();
11863 int i;
11864 for (i=0; i<N; i++) {
11865 if (intent.filterEquals(list.get(i))) {
11866 list.remove(i);
11867 break;
11868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011869 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011870 if (list.size() <= 0) {
11871 stickies.remove(intent.getAction());
11872 }
11873 }
11874 if (stickies.size() <= 0) {
11875 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876 }
11877 }
11878 }
11879 }
11880
11881 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11882 String resultData, Bundle resultExtras, boolean resultAbort,
11883 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011884 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11885 if (r == null) {
11886 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 return false;
11888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011889
Christopher Tatef46723b2012-01-26 14:19:24 -080011890 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11891 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011892 }
11893
11894 public void finishReceiver(IBinder who, int resultCode, String resultData,
11895 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011896 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011897
11898 // Refuse possible leaked file descriptors
11899 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11900 throw new IllegalArgumentException("File descriptors passed in Bundle");
11901 }
11902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011903 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011904 try {
11905 boolean doNext = false;
11906 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011907
Christopher Tatef46723b2012-01-26 14:19:24 -080011908 synchronized(this) {
11909 r = broadcastRecordForReceiverLocked(who);
11910 if (r != null) {
11911 doNext = r.queue.finishReceiverLocked(r, resultCode,
11912 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011915
Christopher Tatef46723b2012-01-26 14:19:24 -080011916 if (doNext) {
11917 r.queue.processNextBroadcast(false);
11918 }
11919 trimApplications();
11920 } finally {
11921 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 // =========================================================
11926 // INSTRUMENTATION
11927 // =========================================================
11928
11929 public boolean startInstrumentation(ComponentName className,
11930 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011931 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011932 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011933 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11934 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 // Refuse possible leaked file descriptors
11936 if (arguments != null && arguments.hasFileDescriptors()) {
11937 throw new IllegalArgumentException("File descriptors passed in Bundle");
11938 }
11939
11940 synchronized(this) {
11941 InstrumentationInfo ii = null;
11942 ApplicationInfo ai = null;
11943 try {
11944 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011945 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011946 ai = AppGlobals.getPackageManager().getApplicationInfo(
11947 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011949 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011950 }
11951 if (ii == null) {
11952 reportStartInstrumentationFailure(watcher, className,
11953 "Unable to find instrumentation info for: " + className);
11954 return false;
11955 }
11956 if (ai == null) {
11957 reportStartInstrumentationFailure(watcher, className,
11958 "Unable to find instrumentation target package: " + ii.targetPackage);
11959 return false;
11960 }
11961
11962 int match = mContext.getPackageManager().checkSignatures(
11963 ii.targetPackage, ii.packageName);
11964 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11965 String msg = "Permission Denial: starting instrumentation "
11966 + className + " from pid="
11967 + Binder.getCallingPid()
11968 + ", uid=" + Binder.getCallingPid()
11969 + " not allowed because package " + ii.packageName
11970 + " does not have a signature matching the target "
11971 + ii.targetPackage;
11972 reportStartInstrumentationFailure(watcher, className, msg);
11973 throw new SecurityException(msg);
11974 }
11975
11976 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011977 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011978 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011979 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011980 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011981 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 app.instrumentationProfileFile = profileFile;
11983 app.instrumentationArguments = arguments;
11984 app.instrumentationWatcher = watcher;
11985 app.instrumentationResultClass = className;
11986 Binder.restoreCallingIdentity(origId);
11987 }
11988
11989 return true;
11990 }
11991
11992 /**
11993 * Report errors that occur while attempting to start Instrumentation. Always writes the
11994 * error to the logs, but if somebody is watching, send the report there too. This enables
11995 * the "am" command to report errors with more information.
11996 *
11997 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11998 * @param cn The component name of the instrumentation.
11999 * @param report The error report.
12000 */
12001 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12002 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012003 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 try {
12005 if (watcher != null) {
12006 Bundle results = new Bundle();
12007 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12008 results.putString("Error", report);
12009 watcher.instrumentationStatus(cn, -1, results);
12010 }
12011 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012012 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012013 }
12014 }
12015
12016 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12017 if (app.instrumentationWatcher != null) {
12018 try {
12019 // NOTE: IInstrumentationWatcher *must* be oneway here
12020 app.instrumentationWatcher.instrumentationFinished(
12021 app.instrumentationClass,
12022 resultCode,
12023 results);
12024 } catch (RemoteException e) {
12025 }
12026 }
12027 app.instrumentationWatcher = null;
12028 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012029 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 app.instrumentationProfileFile = null;
12031 app.instrumentationArguments = null;
12032
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012033 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 }
12035
12036 public void finishInstrumentation(IApplicationThread target,
12037 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012038 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012039 // Refuse possible leaked file descriptors
12040 if (results != null && results.hasFileDescriptors()) {
12041 throw new IllegalArgumentException("File descriptors passed in Intent");
12042 }
12043
12044 synchronized(this) {
12045 ProcessRecord app = getRecordForAppLocked(target);
12046 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 return;
12049 }
12050 final long origId = Binder.clearCallingIdentity();
12051 finishInstrumentationLocked(app, resultCode, results);
12052 Binder.restoreCallingIdentity(origId);
12053 }
12054 }
12055
12056 // =========================================================
12057 // CONFIGURATION
12058 // =========================================================
12059
12060 public ConfigurationInfo getDeviceConfigurationInfo() {
12061 ConfigurationInfo config = new ConfigurationInfo();
12062 synchronized (this) {
12063 config.reqTouchScreen = mConfiguration.touchscreen;
12064 config.reqKeyboardType = mConfiguration.keyboard;
12065 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012066 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12067 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012068 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12069 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012070 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12071 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12073 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012074 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076 return config;
12077 }
12078
12079 public Configuration getConfiguration() {
12080 Configuration ci;
12081 synchronized(this) {
12082 ci = new Configuration(mConfiguration);
12083 }
12084 return ci;
12085 }
12086
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012087 public void updatePersistentConfiguration(Configuration values) {
12088 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12089 "updateConfiguration()");
12090 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12091 "updateConfiguration()");
12092 if (values == null) {
12093 throw new NullPointerException("Configuration must not be null");
12094 }
12095
12096 synchronized(this) {
12097 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012098 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012099 Binder.restoreCallingIdentity(origId);
12100 }
12101 }
12102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 public void updateConfiguration(Configuration values) {
12104 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12105 "updateConfiguration()");
12106
12107 synchronized(this) {
12108 if (values == null && mWindowManager != null) {
12109 // sentinel: fetch the current configuration from the window manager
12110 values = mWindowManager.computeNewConfiguration();
12111 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012112
12113 if (mWindowManager != null) {
12114 mProcessList.applyDisplaySize(mWindowManager);
12115 }
12116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012118 if (values != null) {
12119 Settings.System.clearConfiguration(values);
12120 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012121 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 Binder.restoreCallingIdentity(origId);
12123 }
12124 }
12125
12126 /**
12127 * Do either or both things: (1) change the current configuration, and (2)
12128 * make sure the given activity is running with the (now) current
12129 * configuration. Returns true if the activity has been left running, or
12130 * false if <var>starting</var> is being destroyed to match the new
12131 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012132 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012133 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012134 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012135 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012136 // do nothing if we are headless
12137 if (mHeadless) return true;
12138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139 int changes = 0;
12140
12141 boolean kept = true;
12142
12143 if (values != null) {
12144 Configuration newConfig = new Configuration(mConfiguration);
12145 changes = newConfig.updateFrom(values);
12146 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012147 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012148 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012149 }
12150
Doug Zongker2bec3d42009-12-04 12:52:44 -080012151 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012152
Dianne Hackborn813075a62011-11-14 17:45:19 -080012153 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012154 saveLocaleLocked(values.locale,
12155 !values.locale.equals(mConfiguration.locale),
12156 values.userSetLocale);
12157 }
12158
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012159 mConfigurationSeq++;
12160 if (mConfigurationSeq <= 0) {
12161 mConfigurationSeq = 1;
12162 }
12163 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012164 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012165 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012166
12167 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012168
12169 // TODO: If our config changes, should we auto dismiss any currently
12170 // showing dialogs?
12171 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012172
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012173 AttributeCache ac = AttributeCache.instance();
12174 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012175 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012177
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012178 // Make sure all resources in our process are updated
12179 // right now, so that anyone who is going to retrieve
12180 // resource values after we return will be sure to get
12181 // the new ones. This is especially important during
12182 // boot, where the first config change needs to guarantee
12183 // all resources have that config before following boot
12184 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012185 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012186
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012187 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012188 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012189 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012190 mHandler.sendMessage(msg);
12191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012193 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12194 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012195 try {
12196 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012197 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012198 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012199 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012200 }
12201 } catch (Exception e) {
12202 }
12203 }
12204 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012205 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12206 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012207 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012208 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012209 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12210 broadcastIntentLocked(null, null,
12211 new Intent(Intent.ACTION_LOCALE_CHANGED),
12212 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012213 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 }
12216 }
12217
12218 if (changes != 0 && starting == null) {
12219 // If the configuration changed, and the caller is not already
12220 // in the process of starting an activity, then find the top
12221 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012222 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 }
12224
12225 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012226 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012227 // And we need to make sure at this point that all other activities
12228 // are made visible with the correct configuration.
12229 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012230 }
12231
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012232 if (values != null && mWindowManager != null) {
12233 mWindowManager.setNewConfiguration(mConfiguration);
12234 }
12235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 return kept;
12237 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012238
12239 /**
12240 * Decide based on the configuration whether we should shouw the ANR,
12241 * crash, etc dialogs. The idea is that if there is no affordnace to
12242 * press the on-screen buttons, we shouldn't show the dialog.
12243 *
12244 * A thought: SystemUI might also want to get told about this, the Power
12245 * dialog / global actions also might want different behaviors.
12246 */
12247 private static final boolean shouldShowDialogs(Configuration config) {
12248 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12249 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012251
12252 /**
12253 * Save the locale. You must be inside a synchronized (this) block.
12254 */
12255 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12256 if(isDiff) {
12257 SystemProperties.set("user.language", l.getLanguage());
12258 SystemProperties.set("user.region", l.getCountry());
12259 }
12260
12261 if(isPersist) {
12262 SystemProperties.set("persist.sys.language", l.getLanguage());
12263 SystemProperties.set("persist.sys.country", l.getCountry());
12264 SystemProperties.set("persist.sys.localevar", l.getVariant());
12265 }
12266 }
12267
Adam Powelldd8fab22012-03-22 17:47:27 -070012268 @Override
12269 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12270 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012271 return srec != null && srec.task.affinity != null &&
12272 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012273 }
12274
12275 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12276 Intent resultData) {
12277 ComponentName dest = destIntent.getComponent();
12278
12279 synchronized (this) {
12280 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012281 if (srec == null) {
12282 return false;
12283 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012284 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12285 final int start = history.indexOf(srec);
12286 if (start < 0) {
12287 // Current activity is not in history stack; do nothing.
12288 return false;
12289 }
12290 int finishTo = start - 1;
12291 ActivityRecord parent = null;
12292 boolean foundParentInTask = false;
12293 if (dest != null) {
12294 TaskRecord tr = srec.task;
12295 for (int i = start - 1; i >= 0; i--) {
12296 ActivityRecord r = history.get(i);
12297 if (tr != r.task) {
12298 // Couldn't find parent in the same task; stop at the one above this.
12299 // (Root of current task; in-app "home" behavior)
12300 // Always at least finish the current activity.
12301 finishTo = Math.min(start - 1, i + 1);
12302 parent = history.get(finishTo);
12303 break;
12304 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12305 r.info.name.equals(dest.getClassName())) {
12306 finishTo = i;
12307 parent = r;
12308 foundParentInTask = true;
12309 break;
12310 }
12311 }
12312 }
12313
12314 if (mController != null) {
12315 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12316 if (next != null) {
12317 // ask watcher if this is allowed
12318 boolean resumeOK = true;
12319 try {
12320 resumeOK = mController.activityResuming(next.packageName);
12321 } catch (RemoteException e) {
12322 mController = null;
12323 }
12324
12325 if (!resumeOK) {
12326 return false;
12327 }
12328 }
12329 }
12330 final long origId = Binder.clearCallingIdentity();
12331 for (int i = start; i > finishTo; i--) {
12332 ActivityRecord r = history.get(i);
12333 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012334 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012335 // Only return the supplied result for the first activity finished
12336 resultCode = Activity.RESULT_CANCELED;
12337 resultData = null;
12338 }
12339
12340 if (parent != null && foundParentInTask) {
12341 final int parentLaunchMode = parent.info.launchMode;
12342 final int destIntentFlags = destIntent.getFlags();
12343 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12344 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12345 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12346 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012347 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012348 } else {
12349 try {
12350 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012351 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012352 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12353 null, aInfo, parent.appToken, null,
12354 0, -1, parent.launchedFromUid, 0, null, true, null);
12355 foundParentInTask = res == ActivityManager.START_SUCCESS;
12356 } catch (RemoteException e) {
12357 foundParentInTask = false;
12358 }
12359 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012360 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012361 }
12362 }
12363 Binder.restoreCallingIdentity(origId);
12364 return foundParentInTask;
12365 }
12366 }
12367
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012368 public int getLaunchedFromUid(IBinder activityToken) {
12369 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12370 if (srec == null) {
12371 return -1;
12372 }
12373 return srec.launchedFromUid;
12374 }
12375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012376 // =========================================================
12377 // LIFETIME MANAGEMENT
12378 // =========================================================
12379
Christopher Tatef46723b2012-01-26 14:19:24 -080012380 // Returns which broadcast queue the app is the current [or imminent] receiver
12381 // on, or 'null' if the app is not an active broadcast recipient.
12382 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12383 BroadcastRecord r = app.curReceiver;
12384 if (r != null) {
12385 return r.queue;
12386 }
12387
12388 // It's not the current receiver, but it might be starting up to become one
12389 synchronized (this) {
12390 for (BroadcastQueue queue : mBroadcastQueues) {
12391 r = queue.mPendingBroadcast;
12392 if (r != null && r.curApp == app) {
12393 // found it; report which queue it's in
12394 return queue;
12395 }
12396 }
12397 }
12398
12399 return null;
12400 }
12401
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012402 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012403 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012405 // This adjustment has already been computed. If we are calling
12406 // from the top, we may have already computed our adjustment with
12407 // an earlier hidden adjustment that isn't really for us... if
12408 // so, use the new hidden adjustment.
12409 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012410 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12411 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012412 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012413 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012414 }
12415
12416 if (app.thread == null) {
12417 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012418 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012419 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012420 }
12421
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012422 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12423 app.adjSource = null;
12424 app.adjTarget = null;
12425 app.empty = false;
12426 app.hidden = false;
12427
12428 final int activitiesSize = app.activities.size();
12429
Dianne Hackborn7d608422011-08-07 16:24:18 -070012430 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012431 // The max adjustment doesn't allow this app to be anything
12432 // below foreground, so it is not worth doing work for it.
12433 app.adjType = "fixed";
12434 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012435 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012436 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012437 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012438 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012439 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012440 // System process can do UI, and when they do we want to have
12441 // them trim their memory after the user leaves the UI. To
12442 // facilitate this, here we need to determine whether or not it
12443 // is currently showing UI.
12444 app.systemNoUi = true;
12445 if (app == TOP_APP) {
12446 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012447 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012448 } else if (activitiesSize > 0) {
12449 for (int j = 0; j < activitiesSize; j++) {
12450 final ActivityRecord r = app.activities.get(j);
12451 if (r.visible) {
12452 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012453 }
12454 if (r.app == app) {
12455 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012456 }
12457 }
12458 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012459 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012460 }
12461
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012462 app.keeping = false;
12463 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012464 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465
The Android Open Source Project4df24232009-03-05 14:34:35 -080012466 // Determine the importance of the process, starting with most
12467 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012468 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012469 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012470 boolean foregroundActivities = false;
12471 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012472 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012473 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012475 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012476 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012477 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012478 foregroundActivities = true;
12479 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012480 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012481 } else if (app.instrumentationClass != null) {
12482 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012483 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012484 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012485 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012486 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012487 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012488 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012489 // counts as being in the foreground for OOM killer purposes.
12490 // It's placed in a sched group based on the nature of the
12491 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012492 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012493 schedGroup = (queue == mFgBroadcastQueue)
12494 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012495 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012496 } else if (app.executingServices.size() > 0) {
12497 // An app that is currently executing a service callback also
12498 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012499 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012500 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012501 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012502 } else {
12503 // Assume process is hidden (has activities); we will correct
12504 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012506 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012507 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012508 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012509 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012510
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012511 boolean hasStoppingActivities = false;
12512
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012513 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012514 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012515 for (int j = 0; j < activitiesSize; j++) {
12516 final ActivityRecord r = app.activities.get(j);
12517 if (r.visible) {
12518 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012519 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12520 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012521 app.adjType = "visible";
12522 }
12523 schedGroup = Process.THREAD_GROUP_DEFAULT;
12524 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012525 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012526 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012527 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012528 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012529 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12530 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012531 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012532 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012533 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012534 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012535 } else if (r.state == ActivityState.STOPPING) {
12536 // We will apply the actual adjustment later, because
12537 // we want to allow this process to immediately go through
12538 // any memory trimming that is in effect.
12539 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012540 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012541 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012542 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012543 if (r.app == app) {
12544 app.hasActivities = true;
12545 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012546 }
12547 }
12548
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012549 if (adj == hiddenAdj && !app.hasActivities) {
12550 // Whoops, this process is completely empty as far as we know
12551 // at this point.
12552 adj = emptyAdj;
12553 app.empty = true;
12554 app.adjType = "bg-empty";
12555 }
12556
Dianne Hackborn7d608422011-08-07 16:24:18 -070012557 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012558 if (app.foregroundServices) {
12559 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012560 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012561 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012562 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012563 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012564 } else if (app.forcingToForeground != null) {
12565 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012566 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012567 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012568 app.adjType = "force-foreground";
12569 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012570 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012571 }
12572 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012573
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012574 if (app.foregroundServices) {
12575 interesting = true;
12576 }
12577
Dianne Hackborn7d608422011-08-07 16:24:18 -070012578 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012579 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012580 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012581 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012582 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012583 app.adjType = "heavy";
12584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012585
Dianne Hackborn7d608422011-08-07 16:24:18 -070012586 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012587 // This process is hosting what we currently consider to be the
12588 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012589 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012590 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012591 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012592 app.adjType = "home";
12593 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012594
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012595 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12596 && app.activities.size() > 0) {
12597 // This was the previous process that showed UI to the user.
12598 // We want to try to keep it around more aggressively, to give
12599 // a good experience around switching between two apps.
12600 adj = ProcessList.PREVIOUS_APP_ADJ;
12601 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12602 app.hidden = false;
12603 app.adjType = "previous";
12604 }
12605
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012606 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12607 + " reason=" + app.adjType);
12608
The Android Open Source Project4df24232009-03-05 14:34:35 -080012609 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012610 // there are applications dependent on our services or providers, but
12611 // this gives us a baseline and makes sure we don't get into an
12612 // infinite recursion.
12613 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012614 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615
Christopher Tate6fa95972009-06-05 18:43:55 -070012616 if (mBackupTarget != null && app == mBackupTarget.app) {
12617 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012618 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012619 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012620 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012621 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012622 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012623 }
12624 }
12625
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012627 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 final long now = SystemClock.uptimeMillis();
12629 // This process is more important if the top activity is
12630 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012631 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012633 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012634 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012635 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012636 // If this process has shown some UI, let it immediately
12637 // go to the LRU list because it may be pretty heavy with
12638 // UI stuff. We'll tag it with a label just to help
12639 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012640 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012641 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012643 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012644 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012645 // This service has seen some activity within
12646 // recent memory, so we will keep its process ahead
12647 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012648 if (adj > ProcessList.SERVICE_ADJ) {
12649 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012650 app.adjType = "started-services";
12651 app.hidden = false;
12652 }
12653 }
12654 // If we have let the service slide into the background
12655 // state, still have some text describing what it is doing
12656 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012657 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012658 app.adjType = "started-bg-services";
12659 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012660 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012661 // Don't kill this process because it is doing work; it
12662 // has said it is doing work.
12663 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012665 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012666 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012667 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012668 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012669 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012670 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012671 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012672 // XXX should compute this based on the max of
12673 // all connected clients.
12674 ConnectionRecord cr = clist.get(i);
12675 if (cr.binding.client == app) {
12676 // Binding to ourself is not interesting.
12677 continue;
12678 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012679 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012680 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012681 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012682 int myHiddenAdj = hiddenAdj;
12683 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012684 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012685 myHiddenAdj = client.hiddenAdj;
12686 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012687 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012688 }
12689 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012690 int myEmptyAdj = emptyAdj;
12691 if (myEmptyAdj > client.emptyAdj) {
12692 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12693 myEmptyAdj = client.emptyAdj;
12694 } else {
12695 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12696 }
12697 }
12698 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12699 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012700 String adjType = null;
12701 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12702 // Not doing bind OOM management, so treat
12703 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012704 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012705 // If this process has shown some UI, let it immediately
12706 // go to the LRU list because it may be pretty heavy with
12707 // UI stuff. We'll tag it with a label just to help
12708 // debug and understand what is going on.
12709 if (adj > clientAdj) {
12710 adjType = "bound-bg-ui-services";
12711 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012712 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012713 clientAdj = adj;
12714 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012715 if (now >= (s.lastActivity
12716 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012717 // This service has not seen activity within
12718 // recent memory, so allow it to drop to the
12719 // LRU list if there is no other reason to keep
12720 // it around. We'll also tag it with a label just
12721 // to help debug and undertand what is going on.
12722 if (adj > clientAdj) {
12723 adjType = "bound-bg-services";
12724 }
12725 clientAdj = adj;
12726 }
12727 }
12728 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012729 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012730 // If this process has recently shown UI, and
12731 // the process that is binding to it is less
12732 // important than being visible, then we don't
12733 // care about the binding as much as we care
12734 // about letting this process get into the LRU
12735 // list to be killed and restarted if needed for
12736 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012737 if (app.hasShownUi && app != mHomeProcess
12738 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012739 adjType = "bound-bg-ui-services";
12740 } else {
12741 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12742 |Context.BIND_IMPORTANT)) != 0) {
12743 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012744 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12745 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12746 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12747 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12748 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012749 adj = clientAdj;
12750 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012751 app.pendingUiClean = true;
12752 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12753 adj = ProcessList.VISIBLE_APP_ADJ;
12754 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012755 }
12756 if (!client.hidden) {
12757 app.hidden = false;
12758 }
12759 if (client.keeping) {
12760 app.keeping = true;
12761 }
12762 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012763 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012764 }
12765 if (adjType != null) {
12766 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012767 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12768 .REASON_SERVICE_IN_USE;
12769 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012770 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012771 app.adjTarget = s.name;
12772 }
12773 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12774 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12775 schedGroup = Process.THREAD_GROUP_DEFAULT;
12776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012777 }
12778 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012779 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12780 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012781 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012782 (a.visible || a.state == ActivityState.RESUMED
12783 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012784 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012785 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12786 schedGroup = Process.THREAD_GROUP_DEFAULT;
12787 }
12788 app.hidden = false;
12789 app.adjType = "service";
12790 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12791 .REASON_SERVICE_IN_USE;
12792 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012793 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012794 app.adjTarget = s.name;
12795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012797 }
12798 }
12799 }
12800 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012801
Dianne Hackborn287952c2010-09-22 22:34:31 -070012802 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012803 // would like to avoid killing it unless it would prevent the current
12804 // application from running. By default we put the process in
12805 // with the rest of the background processes; as we scan through
12806 // its services we may bump it up from there.
12807 if (adj > hiddenAdj) {
12808 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012809 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012810 app.adjType = "bg-services";
12811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012812 }
12813
Dianne Hackborn7d608422011-08-07 16:24:18 -070012814 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012815 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012816 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012817 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012818 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012819 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012820 for (int i = cpr.connections.size()-1;
12821 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12822 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12823 i--) {
12824 ContentProviderConnection conn = cpr.connections.get(i);
12825 ProcessRecord client = conn.client;
12826 if (client == app) {
12827 // Being our own client is not interesting.
12828 continue;
12829 }
12830 int myHiddenAdj = hiddenAdj;
12831 if (myHiddenAdj > client.hiddenAdj) {
12832 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12833 myHiddenAdj = client.hiddenAdj;
12834 } else {
12835 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012836 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012837 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012838 int myEmptyAdj = emptyAdj;
12839 if (myEmptyAdj > client.emptyAdj) {
12840 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12841 myEmptyAdj = client.emptyAdj;
12842 } else {
12843 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12844 }
12845 }
12846 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12847 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012848 if (adj > clientAdj) {
12849 if (app.hasShownUi && app != mHomeProcess
12850 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12851 app.adjType = "bg-ui-provider";
12852 } else {
12853 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12854 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12855 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012857 if (!client.hidden) {
12858 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012860 if (client.keeping) {
12861 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012862 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012863 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12864 .REASON_PROVIDER_IN_USE;
12865 app.adjSource = client;
12866 app.adjSourceOom = clientAdj;
12867 app.adjTarget = cpr.name;
12868 }
12869 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12870 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012871 }
12872 }
12873 // If the provider has external (non-framework) process
12874 // dependencies, ensure that its adjustment is at least
12875 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012876 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012877 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12878 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012879 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012880 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012881 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012882 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012883 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012884 }
12885 }
12886 }
12887 }
12888
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012889 if (adj == ProcessList.SERVICE_ADJ) {
12890 if (doingAll) {
12891 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12892 mNewNumServiceProcs++;
12893 }
12894 if (app.serviceb) {
12895 adj = ProcessList.SERVICE_B_ADJ;
12896 }
12897 } else {
12898 app.serviceb = false;
12899 }
12900
12901 app.nonStoppingAdj = adj;
12902
12903 if (hasStoppingActivities) {
12904 // Only upgrade adjustment.
12905 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12906 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12907 app.adjType = "stopping";
12908 }
12909 }
12910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911 app.curRawAdj = adj;
12912
Joe Onorato8a9b2202010-02-26 18:56:32 -080012913 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12915 if (adj > app.maxAdj) {
12916 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012917 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012918 schedGroup = Process.THREAD_GROUP_DEFAULT;
12919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012920 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012921 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012922 app.keeping = true;
12923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012925 if (app.hasAboveClient) {
12926 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12927 // then we need to drop its adjustment to be lower than the service's
12928 // in order to honor the request. We want to drop it by one adjustment
12929 // level... but there is special meaning applied to various levels so
12930 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012931 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012932 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012933 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12934 adj = ProcessList.VISIBLE_APP_ADJ;
12935 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12936 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12937 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12938 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012939 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012940 adj++;
12941 }
12942 }
12943
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012944 int importance = app.memImportance;
12945 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12946 app.curAdj = adj;
12947 app.curSchedGroup = schedGroup;
12948 if (!interesting) {
12949 // For this reporting, if there is not something explicitly
12950 // interesting in this process then we will push it to the
12951 // background importance.
12952 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12953 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12954 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12955 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12956 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12957 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12958 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12959 } else if (adj >= ProcessList.SERVICE_ADJ) {
12960 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12961 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12962 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12963 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12964 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12965 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12966 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12967 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12968 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12969 } else {
12970 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12971 }
12972 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012973
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012974 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12975 if (foregroundActivities != app.foregroundActivities) {
12976 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12977 }
12978 if (changes != 0) {
12979 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12980 app.memImportance = importance;
12981 app.foregroundActivities = foregroundActivities;
12982 int i = mPendingProcessChanges.size()-1;
12983 ProcessChangeItem item = null;
12984 while (i >= 0) {
12985 item = mPendingProcessChanges.get(i);
12986 if (item.pid == app.pid) {
12987 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12988 break;
12989 }
12990 i--;
12991 }
12992 if (i < 0) {
12993 // No existing item in pending changes; need a new one.
12994 final int NA = mAvailProcessChanges.size();
12995 if (NA > 0) {
12996 item = mAvailProcessChanges.remove(NA-1);
12997 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12998 } else {
12999 item = new ProcessChangeItem();
13000 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
13001 }
13002 item.changes = 0;
13003 item.pid = app.pid;
13004 item.uid = app.info.uid;
13005 if (mPendingProcessChanges.size() == 0) {
13006 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
13007 "*** Enqueueing dispatch processes changed!");
13008 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
13009 }
13010 mPendingProcessChanges.add(item);
13011 }
13012 item.changes |= changes;
13013 item.importance = importance;
13014 item.foregroundActivities = foregroundActivities;
13015 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13016 + Integer.toHexString(System.identityHashCode(item))
13017 + " " + app.toShortString() + ": changes=" + item.changes
13018 + " importance=" + item.importance
13019 + " foreground=" + item.foregroundActivities
13020 + " type=" + app.adjType + " source=" + app.adjSource
13021 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013022 }
13023
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013024 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 }
13026
13027 /**
13028 * Ask a given process to GC right now.
13029 */
13030 final void performAppGcLocked(ProcessRecord app) {
13031 try {
13032 app.lastRequestedGc = SystemClock.uptimeMillis();
13033 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013034 if (app.reportLowMemory) {
13035 app.reportLowMemory = false;
13036 app.thread.scheduleLowMemory();
13037 } else {
13038 app.thread.processInBackground();
13039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013040 }
13041 } catch (Exception e) {
13042 // whatever.
13043 }
13044 }
13045
13046 /**
13047 * Returns true if things are idle enough to perform GCs.
13048 */
Josh Bartel7f208742010-02-25 11:01:44 -060013049 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013050 boolean processingBroadcasts = false;
13051 for (BroadcastQueue q : mBroadcastQueues) {
13052 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13053 processingBroadcasts = true;
13054 }
13055 }
13056 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013057 && (mSleeping || (mMainStack.mResumedActivity != null &&
13058 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013059 }
13060
13061 /**
13062 * Perform GCs on all processes that are waiting for it, but only
13063 * if things are idle.
13064 */
13065 final void performAppGcsLocked() {
13066 final int N = mProcessesToGc.size();
13067 if (N <= 0) {
13068 return;
13069 }
Josh Bartel7f208742010-02-25 11:01:44 -060013070 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013071 while (mProcessesToGc.size() > 0) {
13072 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013073 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013074 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13075 <= SystemClock.uptimeMillis()) {
13076 // To avoid spamming the system, we will GC processes one
13077 // at a time, waiting a few seconds between each.
13078 performAppGcLocked(proc);
13079 scheduleAppGcsLocked();
13080 return;
13081 } else {
13082 // It hasn't been long enough since we last GCed this
13083 // process... put it in the list to wait for its time.
13084 addProcessToGcListLocked(proc);
13085 break;
13086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013087 }
13088 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013089
13090 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013091 }
13092 }
13093
13094 /**
13095 * If all looks good, perform GCs on all processes waiting for them.
13096 */
13097 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013098 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 performAppGcsLocked();
13100 return;
13101 }
13102 // Still not idle, wait some more.
13103 scheduleAppGcsLocked();
13104 }
13105
13106 /**
13107 * Schedule the execution of all pending app GCs.
13108 */
13109 final void scheduleAppGcsLocked() {
13110 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013111
13112 if (mProcessesToGc.size() > 0) {
13113 // Schedule a GC for the time to the next process.
13114 ProcessRecord proc = mProcessesToGc.get(0);
13115 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13116
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013117 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013118 long now = SystemClock.uptimeMillis();
13119 if (when < (now+GC_TIMEOUT)) {
13120 when = now + GC_TIMEOUT;
13121 }
13122 mHandler.sendMessageAtTime(msg, when);
13123 }
13124 }
13125
13126 /**
13127 * Add a process to the array of processes waiting to be GCed. Keeps the
13128 * list in sorted order by the last GC time. The process can't already be
13129 * on the list.
13130 */
13131 final void addProcessToGcListLocked(ProcessRecord proc) {
13132 boolean added = false;
13133 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13134 if (mProcessesToGc.get(i).lastRequestedGc <
13135 proc.lastRequestedGc) {
13136 added = true;
13137 mProcessesToGc.add(i+1, proc);
13138 break;
13139 }
13140 }
13141 if (!added) {
13142 mProcessesToGc.add(0, proc);
13143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 }
13145
13146 /**
13147 * Set up to ask a process to GC itself. This will either do it
13148 * immediately, or put it on the list of processes to gc the next
13149 * time things are idle.
13150 */
13151 final void scheduleAppGcLocked(ProcessRecord app) {
13152 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013153 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013154 return;
13155 }
13156 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013157 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013158 scheduleAppGcsLocked();
13159 }
13160 }
13161
Dianne Hackborn287952c2010-09-22 22:34:31 -070013162 final void checkExcessivePowerUsageLocked(boolean doKills) {
13163 updateCpuStatsNow();
13164
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013165 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013166 boolean doWakeKills = doKills;
13167 boolean doCpuKills = doKills;
13168 if (mLastPowerCheckRealtime == 0) {
13169 doWakeKills = false;
13170 }
13171 if (mLastPowerCheckUptime == 0) {
13172 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013173 }
13174 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013175 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013176 }
13177 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013178 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13179 final long curUptime = SystemClock.uptimeMillis();
13180 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13181 mLastPowerCheckRealtime = curRealtime;
13182 mLastPowerCheckUptime = curUptime;
13183 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13184 doWakeKills = false;
13185 }
13186 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13187 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013188 }
13189 int i = mLruProcesses.size();
13190 while (i > 0) {
13191 i--;
13192 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013193 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013194 long wtime;
13195 synchronized (stats) {
13196 wtime = stats.getProcessWakeTime(app.info.uid,
13197 app.pid, curRealtime);
13198 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013199 long wtimeUsed = wtime - app.lastWakeTime;
13200 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13201 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013202 StringBuilder sb = new StringBuilder(128);
13203 sb.append("Wake for ");
13204 app.toShortString(sb);
13205 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013206 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013207 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013208 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013209 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013210 sb.append((wtimeUsed*100)/realtimeSince);
13211 sb.append("%)");
13212 Slog.i(TAG, sb.toString());
13213 sb.setLength(0);
13214 sb.append("CPU for ");
13215 app.toShortString(sb);
13216 sb.append(": over ");
13217 TimeUtils.formatDuration(uptimeSince, sb);
13218 sb.append(" used ");
13219 TimeUtils.formatDuration(cputimeUsed, sb);
13220 sb.append(" (");
13221 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013222 sb.append("%)");
13223 Slog.i(TAG, sb.toString());
13224 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013225 // If a process has held a wake lock for more
13226 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013227 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 if (doWakeKills && realtimeSince > 0
13229 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13230 synchronized (stats) {
13231 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13232 realtimeSince, wtimeUsed);
13233 }
13234 Slog.w(TAG, "Excessive wake lock in " + app.processName
13235 + " (pid " + app.pid + "): held " + wtimeUsed
13236 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013237 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13238 app.processName, app.setAdj, "excessive wake lock");
13239 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013240 } else if (doCpuKills && uptimeSince > 0
13241 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13242 synchronized (stats) {
13243 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13244 uptimeSince, cputimeUsed);
13245 }
13246 Slog.w(TAG, "Excessive CPU in " + app.processName
13247 + " (pid " + app.pid + "): used " + cputimeUsed
13248 + " during " + uptimeSince);
13249 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13250 app.processName, app.setAdj, "excessive cpu");
13251 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013252 } else {
13253 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013254 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013255 }
13256 }
13257 }
13258 }
13259
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013260 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13261 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013262 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013263 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013264
13265 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013266 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 }
13268
Dianne Hackborn287952c2010-09-22 22:34:31 -070013269 final boolean wasKeeping = app.keeping;
13270
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013271 boolean success = true;
13272
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013273 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013274
Jeff Brown10e89712011-07-08 18:52:57 -070013275 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013276 if (wasKeeping && !app.keeping) {
13277 // This app is no longer something we want to keep. Note
13278 // its current wake lock time to later know to kill it if
13279 // it is not behaving well.
13280 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13281 synchronized (stats) {
13282 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13283 app.pid, SystemClock.elapsedRealtime());
13284 }
13285 app.lastCpuTime = app.curCpuTime;
13286 }
13287
13288 app.setRawAdj = app.curRawAdj;
13289 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013290
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013291 if (app.curAdj != app.setAdj) {
13292 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013293 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013294 TAG, "Set " + app.pid + " " + app.processName +
13295 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013296 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013297 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013298 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013299 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013300 }
13301 }
13302 if (app.setSchedGroup != app.curSchedGroup) {
13303 app.setSchedGroup = app.curSchedGroup;
13304 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13305 "Setting process group of " + app.processName
13306 + " to " + app.curSchedGroup);
13307 if (app.waitingToKill != null &&
13308 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13309 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13310 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13311 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013312 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013313 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013314 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013315 } else {
13316 if (true) {
13317 long oldId = Binder.clearCallingIdentity();
13318 try {
13319 Process.setProcessGroup(app.pid, app.curSchedGroup);
13320 } catch (Exception e) {
13321 Slog.w(TAG, "Failed setting process group of " + app.pid
13322 + " to " + app.curSchedGroup);
13323 e.printStackTrace();
13324 } finally {
13325 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013326 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013327 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013328 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013329 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013330 app.thread.setSchedulingGroup(app.curSchedGroup);
13331 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013332 }
13333 }
13334 }
13335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013336 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013337 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 }
13339
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013340 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013341 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013342 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013343 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013345 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013346 }
13347 }
13348 return resumedActivity;
13349 }
13350
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013351 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013352 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13354 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013355 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13356 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013357
13358 mAdjSeq++;
13359
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013360 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13361 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013362 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13363 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013364 if (nowHidden != wasHidden) {
13365 // Changed to/from hidden state, so apps after it in the LRU
13366 // list may also be changed.
13367 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013369 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013370 }
13371
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013372 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013373 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13375
13376 if (false) {
13377 RuntimeException e = new RuntimeException();
13378 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013379 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013380 }
13381
13382 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013383 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013384
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013385 // Let's determine how many processes we have running vs.
13386 // how many slots we have for background processes; we may want
13387 // to put multiple processes in a slot of there are enough of
13388 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013389 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13390 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13391 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13392 if (emptyFactor < 1) emptyFactor = 1;
13393 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13394 if (hiddenFactor < 1) hiddenFactor = 1;
13395 int stepHidden = 0;
13396 int stepEmpty = 0;
13397 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13398 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013399 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013400 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013401 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013402
13403 mNumNonHiddenProcs = 0;
13404 mNumHiddenProcs = 0;
13405
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013406 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013408 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013409 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013410 int nextHiddenAdj = curHiddenAdj+1;
13411 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13412 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013413 while (i > 0) {
13414 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013415 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013416 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013417 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013418 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013419 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13420 // This process was assigned as a hidden process... step the
13421 // hidden level.
13422 mNumHiddenProcs++;
13423 if (curHiddenAdj != nextHiddenAdj) {
13424 stepHidden++;
13425 if (stepHidden >= hiddenFactor) {
13426 stepHidden = 0;
13427 curHiddenAdj = nextHiddenAdj;
13428 nextHiddenAdj += 2;
13429 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13430 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13431 }
13432 }
13433 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013434 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013435 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013436 Slog.i(TAG, "No longer want " + app.processName
13437 + " (pid " + app.pid + "): hidden #" + numHidden);
13438 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13439 app.processName, app.setAdj, "too many background");
13440 app.killedBackground = true;
13441 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013442 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013443 } else {
13444 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13445 // This process was assigned as an empty process... step the
13446 // empty level.
13447 if (curEmptyAdj != nextEmptyAdj) {
13448 stepEmpty++;
13449 if (stepEmpty >= emptyFactor) {
13450 stepEmpty = 0;
13451 curEmptyAdj = nextEmptyAdj;
13452 nextEmptyAdj += 2;
13453 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13454 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13455 }
13456 }
13457 }
13458 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13459 mNumNonHiddenProcs++;
13460 }
13461 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13462 numEmpty++;
13463 if (numEmpty > emptyProcessLimit) {
13464 Slog.i(TAG, "No longer want " + app.processName
13465 + " (pid " + app.pid + "): empty #" + numEmpty);
13466 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13467 app.processName, app.setAdj, "too many background");
13468 app.killedBackground = true;
13469 Process.killProcessQuiet(app.pid);
13470 }
13471 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013472 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013473 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013474 // If this is an isolated process, and there are no
13475 // services running in it, then the process is no longer
13476 // needed. We agressively kill these because we can by
13477 // definition not re-use the same process again, and it is
13478 // good to avoid having whatever code was running in them
13479 // left sitting around after no longer needed.
13480 Slog.i(TAG, "Isolated process " + app.processName
13481 + " (pid " + app.pid + ") no longer needed");
13482 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13483 app.processName, app.setAdj, "isolated not needed");
13484 app.killedBackground = true;
13485 Process.killProcessQuiet(app.pid);
13486 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013487 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13488 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13489 && !app.killedBackground) {
13490 numTrimming++;
13491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492 }
13493 }
13494
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013495 mNumServiceProcs = mNewNumServiceProcs;
13496
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013497 // Now determine the memory trimming level of background processes.
13498 // Unfortunately we need to start at the back of the list to do this
13499 // properly. We only do this if the number of background apps we
13500 // are managing to keep around is less than half the maximum we desire;
13501 // if we are keeping a good number around, we'll let them use whatever
13502 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013503 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13504 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13505 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013506 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013507 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013508 int minFactor = 2;
13509 if (mHomeProcess != null) minFactor++;
13510 if (mPreviousProcess != null) minFactor++;
13511 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013512 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013513 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013514 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013515 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013516 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013517 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13518 } else {
13519 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13520 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013521 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013522 for (i=0; i<N; i++) {
13523 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013524 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13525 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013526 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013527 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13528 try {
13529 app.thread.scheduleTrimMemory(curLevel);
13530 } catch (RemoteException e) {
13531 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013532 if (false) {
13533 // For now we won't do this; our memory trimming seems
13534 // to be good enough at this point that destroying
13535 // activities causes more harm than good.
13536 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13537 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013538 // Need to do this on its own message because the stack may not
13539 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013540 // For these apps we will also finish their activities
13541 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013542 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013543 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013544 }
13545 }
13546 app.trimMemoryLevel = curLevel;
13547 step++;
13548 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013549 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013550 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013551 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13552 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013553 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013554 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13555 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013556 break;
13557 }
13558 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013559 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013560 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013561 && app.thread != null) {
13562 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013563 app.thread.scheduleTrimMemory(
13564 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013565 } catch (RemoteException e) {
13566 }
13567 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013568 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013569 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013570 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013571 && app.pendingUiClean) {
13572 // If this application is now in the background and it
13573 // had done UI, then give it the special trim level to
13574 // have it free UI resources.
13575 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13576 if (app.trimMemoryLevel < level && app.thread != null) {
13577 try {
13578 app.thread.scheduleTrimMemory(level);
13579 } catch (RemoteException e) {
13580 }
13581 }
13582 app.pendingUiClean = false;
13583 }
13584 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013585 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013586 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013587 } catch (RemoteException e) {
13588 }
13589 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013590 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013591 }
13592 }
13593 } else {
13594 final int N = mLruProcesses.size();
13595 for (i=0; i<N; i++) {
13596 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013597 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013598 && app.pendingUiClean) {
13599 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13600 && app.thread != null) {
13601 try {
13602 app.thread.scheduleTrimMemory(
13603 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13604 } catch (RemoteException e) {
13605 }
13606 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013607 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013608 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013609 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013610 }
13611 }
13612
13613 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013614 // Need to do this on its own message because the stack may not
13615 // be in a consistent state at this point.
13616 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618 }
13619
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013620 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013621 synchronized (this) {
13622 int i;
13623
13624 // First remove any unused application processes whose package
13625 // has been removed.
13626 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13627 final ProcessRecord app = mRemovedProcesses.get(i);
13628 if (app.activities.size() == 0
13629 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013630 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 TAG, "Exiting empty application process "
13632 + app.processName + " ("
13633 + (app.thread != null ? app.thread.asBinder() : null)
13634 + ")\n");
13635 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013636 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13637 app.processName, app.setAdj, "empty");
13638 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 } else {
13640 try {
13641 app.thread.scheduleExit();
13642 } catch (Exception e) {
13643 // Ignore exceptions.
13644 }
13645 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013646 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013647 mRemovedProcesses.remove(i);
13648
13649 if (app.persistent) {
13650 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013651 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013652 }
13653 }
13654 }
13655 }
13656
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013657 // Now update the oom adj for all processes.
13658 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013659 }
13660 }
13661
13662 /** This method sends the specified signal to each of the persistent apps */
13663 public void signalPersistentProcesses(int sig) throws RemoteException {
13664 if (sig != Process.SIGNAL_USR1) {
13665 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13666 }
13667
13668 synchronized (this) {
13669 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13670 != PackageManager.PERMISSION_GRANTED) {
13671 throw new SecurityException("Requires permission "
13672 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13673 }
13674
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013675 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13676 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013677 if (r.thread != null && r.persistent) {
13678 Process.sendSignal(r.pid, sig);
13679 }
13680 }
13681 }
13682 }
13683
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013684 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13685 if (proc == null || proc == mProfileProc) {
13686 proc = mProfileProc;
13687 path = mProfileFile;
13688 profileType = mProfileType;
13689 clearProfilerLocked();
13690 }
13691 if (proc == null) {
13692 return;
13693 }
13694 try {
13695 proc.thread.profilerControl(false, path, null, profileType);
13696 } catch (RemoteException e) {
13697 throw new IllegalStateException("Process disappeared");
13698 }
13699 }
13700
13701 private void clearProfilerLocked() {
13702 if (mProfileFd != null) {
13703 try {
13704 mProfileFd.close();
13705 } catch (IOException e) {
13706 }
13707 }
13708 mProfileApp = null;
13709 mProfileProc = null;
13710 mProfileFile = null;
13711 mProfileType = 0;
13712 mAutoStopProfiler = false;
13713 }
13714
Dianne Hackborn1676c852012-09-10 14:52:30 -070013715 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013716 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013717
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013718 try {
13719 synchronized (this) {
13720 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13721 // its own permission.
13722 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13723 != PackageManager.PERMISSION_GRANTED) {
13724 throw new SecurityException("Requires permission "
13725 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013726 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013727
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013728 if (start && fd == null) {
13729 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013730 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013731
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013732 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013733 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013734 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013735 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013736
13737 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013738 throw new IllegalArgumentException("Unknown process: " + process);
13739 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013740
13741 if (start) {
13742 stopProfilerLocked(null, null, 0);
13743 setProfileApp(proc.info, proc.processName, path, fd, false);
13744 mProfileProc = proc;
13745 mProfileType = profileType;
13746 try {
13747 fd = fd.dup();
13748 } catch (IOException e) {
13749 fd = null;
13750 }
13751 proc.thread.profilerControl(start, path, fd, profileType);
13752 fd = null;
13753 mProfileFd = null;
13754 } else {
13755 stopProfilerLocked(proc, path, profileType);
13756 if (fd != null) {
13757 try {
13758 fd.close();
13759 } catch (IOException e) {
13760 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013761 }
13762 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013763
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013764 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013765 }
13766 } catch (RemoteException e) {
13767 throw new IllegalStateException("Process disappeared");
13768 } finally {
13769 if (fd != null) {
13770 try {
13771 fd.close();
13772 } catch (IOException e) {
13773 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013774 }
13775 }
13776 }
Andy McFadden824c5102010-07-09 16:26:57 -070013777
Dianne Hackborn1676c852012-09-10 14:52:30 -070013778 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
13779 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
13780 userId, true, true, callName, null);
13781 ProcessRecord proc = null;
13782 try {
13783 int pid = Integer.parseInt(process);
13784 synchronized (mPidsSelfLocked) {
13785 proc = mPidsSelfLocked.get(pid);
13786 }
13787 } catch (NumberFormatException e) {
13788 }
13789
13790 if (proc == null) {
13791 HashMap<String, SparseArray<ProcessRecord>> all
13792 = mProcessNames.getMap();
13793 SparseArray<ProcessRecord> procs = all.get(process);
13794 if (procs != null && procs.size() > 0) {
13795 proc = procs.valueAt(0);
13796 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13797 for (int i=1; i<procs.size(); i++) {
13798 ProcessRecord thisProc = procs.valueAt(i);
13799 if (thisProc.userId == userId) {
13800 proc = thisProc;
13801 break;
13802 }
13803 }
13804 }
13805 }
13806 }
13807
13808 return proc;
13809 }
13810
13811 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013812 String path, ParcelFileDescriptor fd) throws RemoteException {
13813
13814 try {
13815 synchronized (this) {
13816 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13817 // its own permission (same as profileControl).
13818 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13819 != PackageManager.PERMISSION_GRANTED) {
13820 throw new SecurityException("Requires permission "
13821 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13822 }
13823
13824 if (fd == null) {
13825 throw new IllegalArgumentException("null fd");
13826 }
13827
Dianne Hackborn1676c852012-09-10 14:52:30 -070013828 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013829 if (proc == null || proc.thread == null) {
13830 throw new IllegalArgumentException("Unknown process: " + process);
13831 }
13832
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013833 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13834 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013835 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13836 throw new SecurityException("Process not debuggable: " + proc);
13837 }
13838 }
13839
13840 proc.thread.dumpHeap(managed, path, fd);
13841 fd = null;
13842 return true;
13843 }
13844 } catch (RemoteException e) {
13845 throw new IllegalStateException("Process disappeared");
13846 } finally {
13847 if (fd != null) {
13848 try {
13849 fd.close();
13850 } catch (IOException e) {
13851 }
13852 }
13853 }
13854 }
13855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013856 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13857 public void monitor() {
13858 synchronized (this) { }
13859 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013860
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013861 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013862 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13863 ProcessRecord processRecord = mLruProcesses.get(i);
13864 try {
13865 if (processRecord.thread != null) {
13866 processRecord.thread.setCoreSettings(settings);
13867 }
13868 } catch (RemoteException re) {
13869 /* ignore */
13870 }
13871 }
13872 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013873
13874 // Multi-user methods
13875
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013876 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013877 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013878 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13879 != PackageManager.PERMISSION_GRANTED) {
13880 String msg = "Permission Denial: switchUser() from pid="
13881 + Binder.getCallingPid()
13882 + ", uid=" + Binder.getCallingUid()
13883 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13884 Slog.w(TAG, msg);
13885 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013886 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013887 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013888 if (mCurrentUserId == userId) {
13889 return true;
13890 }
13891
Dianne Hackborn9d9ece32012-09-10 15:33:52 -070013892 mWindowManager.startFreezingScreen(R.anim.screen_user_exit,
13893 R.anim.screen_user_enter);
13894
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013895 // If the user we are switching to is not currently started, then
13896 // we need to start it now.
13897 if (mStartedUsers.get(userId) == null) {
13898 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013899 }
13900
13901 mCurrentUserId = userId;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070013902 Integer userIdInt = Integer.valueOf(userId);
13903 mUserLru.remove(userIdInt);
13904 mUserLru.add(userIdInt);
Amith Yamasani742a6712011-05-04 14:49:28 -070013905 boolean haveActivities = mMainStack.switchUser(userId);
13906 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013907 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Dianne Hackborn9d9ece32012-09-10 15:33:52 -070013908 } else {
13909 mMainStack.addStartingUserLocked(mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013910 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013911 }
Amith Yamasani13593602012-03-22 16:16:17 -070013912
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013913 long ident = Binder.clearCallingIdentity();
13914 try {
13915 // Inform of user switch
13916 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13917 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013918 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13919 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013920 } finally {
13921 Binder.restoreCallingIdentity(ident);
13922 }
Amith Yamasani13593602012-03-22 16:16:17 -070013923
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013924 return true;
13925 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013926
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013927 void finishUserSwitch(UserStartedState uss) {
13928 synchronized (this) {
13929 if (uss.mState == UserStartedState.STATE_BOOTING
13930 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13931 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013932 final int userId = uss.mHandle.getIdentifier();
13933 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13934 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13935 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013936 null, null, 0, null, null,
13937 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013938 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013939 }
Dianne Hackborn9d9ece32012-09-10 15:33:52 -070013940 mWindowManager.stopFreezingScreen();
Amith Yamasani52f1d752012-03-28 18:19:29 -070013941 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013942 }
13943
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013944 @Override
13945 public int stopUser(final int userId, final IStopUserCallback callback) {
13946 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13947 != PackageManager.PERMISSION_GRANTED) {
13948 String msg = "Permission Denial: switchUser() from pid="
13949 + Binder.getCallingPid()
13950 + ", uid=" + Binder.getCallingUid()
13951 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13952 Slog.w(TAG, msg);
13953 throw new SecurityException(msg);
13954 }
13955 if (userId <= 0) {
13956 throw new IllegalArgumentException("Can't stop primary user " + userId);
13957 }
Amith Yamasani13593602012-03-22 16:16:17 -070013958 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013959 if (mCurrentUserId == userId) {
13960 return ActivityManager.USER_OP_IS_CURRENT;
13961 }
13962
13963 final UserStartedState uss = mStartedUsers.get(userId);
13964 if (uss == null) {
13965 // User is not started, nothing to do... but we do need to
13966 // callback if requested.
13967 if (callback != null) {
13968 mHandler.post(new Runnable() {
13969 @Override
13970 public void run() {
13971 try {
13972 callback.userStopped(userId);
13973 } catch (RemoteException e) {
13974 }
13975 }
13976 });
13977 }
13978 return ActivityManager.USER_OP_SUCCESS;
13979 }
13980
13981 if (callback != null) {
13982 uss.mStopCallbacks.add(callback);
13983 }
13984
13985 if (uss.mState != UserStartedState.STATE_STOPPING) {
13986 uss.mState = UserStartedState.STATE_STOPPING;
13987
13988 long ident = Binder.clearCallingIdentity();
13989 try {
13990 // Inform of user switch
13991 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13992 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13993 @Override
13994 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070013995 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013996 finishUserStop(uss);
13997 }
13998 };
13999 broadcastIntentLocked(null, null, intent,
14000 null, resultReceiver, 0, null, null, null,
14001 true, false, MY_PID, Process.SYSTEM_UID, userId);
14002 } finally {
14003 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070014004 }
14005 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014006 }
Amith Yamasani13593602012-03-22 16:16:17 -070014007
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014008 return ActivityManager.USER_OP_SUCCESS;
14009 }
14010
14011 void finishUserStop(UserStartedState uss) {
14012 final int userId = uss.mHandle.getIdentifier();
14013 boolean stopped;
14014 ArrayList<IStopUserCallback> callbacks;
14015 synchronized (this) {
14016 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
14017 if (uss.mState != UserStartedState.STATE_STOPPING
14018 || mStartedUsers.get(userId) != uss) {
14019 stopped = false;
14020 } else {
14021 stopped = true;
14022 // User can no longer run.
14023 mStartedUsers.remove(userId);
14024
14025 // Clean up all state and processes associated with the user.
14026 // Kill all the processes for the user.
14027 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014028 }
14029 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014030
14031 for (int i=0; i<callbacks.size(); i++) {
14032 try {
14033 if (stopped) callbacks.get(i).userStopped(userId);
14034 else callbacks.get(i).userStopAborted(userId);
14035 } catch (RemoteException e) {
14036 }
14037 }
14038 }
14039
14040 @Override
14041 public UserInfo getCurrentUser() {
14042 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14043 != PackageManager.PERMISSION_GRANTED) {
14044 String msg = "Permission Denial: getCurrentUser() from pid="
14045 + Binder.getCallingPid()
14046 + ", uid=" + Binder.getCallingUid()
14047 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14048 Slog.w(TAG, msg);
14049 throw new SecurityException(msg);
14050 }
14051 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014052 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014053 }
Amith Yamasani13593602012-03-22 16:16:17 -070014054 }
14055
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014056 @Override
14057 public boolean isUserRunning(int userId) {
14058 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14059 != PackageManager.PERMISSION_GRANTED) {
14060 String msg = "Permission Denial: isUserRunning() from pid="
14061 + Binder.getCallingPid()
14062 + ", uid=" + Binder.getCallingUid()
14063 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14064 Slog.w(TAG, msg);
14065 throw new SecurityException(msg);
14066 }
14067 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014068 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014069 }
14070 }
14071
Dianne Hackborn1676c852012-09-10 14:52:30 -070014072 boolean isUserRunningLocked(int userId) {
14073 UserStartedState state = mStartedUsers.get(userId);
14074 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014075 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014076
Dianne Hackborn1676c852012-09-10 14:52:30 -070014077 private boolean userExists(int userId) {
14078 if (userId == 0) {
14079 return true;
14080 }
14081 UserManagerService ums = getUserManagerLocked();
14082 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14083 }
14084
14085 int[] getUsersLocked() {
14086 UserManagerService ums = getUserManagerLocked();
14087 return ums != null ? ums.getUserIds() : new int[] { 0 };
14088 }
14089
14090 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014091 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014092 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14093 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014094 }
14095 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014096 }
14097
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014098 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014099 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014100
14101 throw new SecurityException("Caller uid=" + uid
14102 + " is not privileged to communicate with user=" + userId);
14103 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014104
14105 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014106 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014107 }
14108
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014109 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014110 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014111 ApplicationInfo newInfo = new ApplicationInfo(info);
14112 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014113 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14114 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014115 return newInfo;
14116 }
14117
14118 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014119 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014120 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014121 return aInfo;
14122 }
14123
14124 ActivityInfo info = new ActivityInfo(aInfo);
14125 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14126 return info;
14127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014128}