blob: ca903683e604c57258e7ed0c865e14f866df950f [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) {
2011 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002012 final PackageManager pm = mContext.getPackageManager();
2013 gids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002014
2015 if (Environment.isExternalStorageEmulated()) {
2016 if (pm.checkPermission(
2017 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2018 app.info.packageName) == PERMISSION_GRANTED) {
2019 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2020 } else {
2021 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2022 }
2023 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002024 } catch (PackageManager.NameNotFoundException e) {
2025 Slog.w(TAG, "Unable to retrieve gids", e);
2026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2029 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2030 && mTopComponent != null
2031 && app.processName.equals(mTopComponent.getPackageName())) {
2032 uid = 0;
2033 }
2034 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2035 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2036 uid = 0;
2037 }
2038 }
2039 int debugFlags = 0;
2040 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2041 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002042 // Also turn on CheckJNI for debuggable apps. It's quite
2043 // awkward to turn on otherwise.
2044 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002046 // Run the app in safe mode if its manifest requests so or the
2047 // system is booted in safe mode.
2048 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2049 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002050 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2053 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2054 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002055 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2056 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 if ("1".equals(SystemProperties.get("debug.assert"))) {
2059 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2060 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002061
2062 // Start the process. It will either succeed and return a result containing
2063 // the PID of the new process, or else throw a RuntimeException.
2064 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002065 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002066 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2069 synchronized (bs) {
2070 if (bs.isOnBattery()) {
2071 app.batteryStats.incStartsLocked();
2072 }
2073 }
2074
Jeff Brown3f9dd282011-07-08 20:02:19 -07002075 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 app.processName, hostingType,
2077 hostingNameStr != null ? hostingNameStr : "");
2078
2079 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002080 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002083 StringBuilder buf = mStringBuilder;
2084 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 buf.append("Start proc ");
2086 buf.append(app.processName);
2087 buf.append(" for ");
2088 buf.append(hostingType);
2089 if (hostingNameStr != null) {
2090 buf.append(" ");
2091 buf.append(hostingNameStr);
2092 }
2093 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002094 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 buf.append(" uid=");
2096 buf.append(uid);
2097 buf.append(" gids={");
2098 if (gids != null) {
2099 for (int gi=0; gi<gids.length; gi++) {
2100 if (gi != 0) buf.append(", ");
2101 buf.append(gids[gi]);
2102
2103 }
2104 }
2105 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002106 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002107 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002108 app.usingWrapper = startResult.usingWrapper;
2109 app.removed = false;
2110 synchronized (mPidsSelfLocked) {
2111 this.mPidsSelfLocked.put(startResult.pid, app);
2112 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2113 msg.obj = app;
2114 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2115 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 }
2117 } catch (RuntimeException e) {
2118 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002119 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002120 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 }
2122 }
2123
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 if (resumed) {
2126 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2127 } else {
2128 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2129 }
2130 }
2131
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002132 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002133 if (mHeadless) {
2134 // Added because none of the other calls to ensureBootCompleted seem to fire
2135 // when running headless.
2136 ensureBootCompleted();
2137 return false;
2138 }
2139
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002140 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2141 && mTopAction == null) {
2142 // We are running in factory test mode, but unable to find
2143 // the factory test app, so just sit around displaying the
2144 // error message and don't try to start anything.
2145 return false;
2146 }
2147 Intent intent = new Intent(
2148 mTopAction,
2149 mTopData != null ? Uri.parse(mTopData) : null);
2150 intent.setComponent(mTopComponent);
2151 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2152 intent.addCategory(Intent.CATEGORY_HOME);
2153 }
2154 ActivityInfo aInfo =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002155 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 if (aInfo != null) {
2157 intent.setComponent(new ComponentName(
2158 aInfo.applicationInfo.packageName, aInfo.name));
2159 // Don't do this if the home app is currently being
2160 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002161 aInfo = new ActivityInfo(aInfo);
2162 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002163 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2164 aInfo.applicationInfo.uid);
2165 if (app == null || app.instrumentationClass == null) {
2166 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002167 mMainStack.startActivityLocked(null, intent, null, aInfo,
2168 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002169 }
2170 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002171 if (startingUser != null) {
2172 mMainStack.addStartingUserLocked(startingUser);
2173 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002174
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002175 return true;
2176 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002177
Amith Yamasani259d5e52012-08-31 15:11:01 -07002178 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2179 ActivityInfo ai = null;
2180 ComponentName comp = intent.getComponent();
2181 try {
2182 if (comp != null) {
2183 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2184 } else {
2185 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2186 intent,
2187 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2188 flags, userId);
2189
2190 if (info != null) {
2191 ai = info.activityInfo;
2192 }
2193 }
2194 } catch (RemoteException e) {
2195 // ignore
2196 }
2197
2198 return ai;
2199 }
2200
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002201 /**
2202 * Starts the "new version setup screen" if appropriate.
2203 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002204 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002205 // Only do this once per boot.
2206 if (mCheckedForSetup) {
2207 return;
2208 }
2209
2210 // We will show this screen if the current one is a different
2211 // version than the last one shown, and we are not running in
2212 // low-level factory test mode.
2213 final ContentResolver resolver = mContext.getContentResolver();
2214 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2215 Settings.Secure.getInt(resolver,
2216 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2217 mCheckedForSetup = true;
2218
2219 // See if we should be showing the platform update setup UI.
2220 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2221 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2222 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2223
2224 // We don't allow third party apps to replace this.
2225 ResolveInfo ri = null;
2226 for (int i=0; ris != null && i<ris.size(); i++) {
2227 if ((ris.get(i).activityInfo.applicationInfo.flags
2228 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2229 ri = ris.get(i);
2230 break;
2231 }
2232 }
2233
2234 if (ri != null) {
2235 String vers = ri.activityInfo.metaData != null
2236 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2237 : null;
2238 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2239 vers = ri.activityInfo.applicationInfo.metaData.getString(
2240 Intent.METADATA_SETUP_VERSION);
2241 }
2242 String lastVers = Settings.Secure.getString(
2243 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2244 if (vers != null && !vers.equals(lastVers)) {
2245 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2246 intent.setComponent(new ComponentName(
2247 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002248 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2249 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002250 }
2251 }
2252 }
2253 }
2254
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002255 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002256 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002257 }
2258
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002259 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002260 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002261 throw new SecurityException("Isolated process not allowed to call " + caller);
2262 }
2263 }
2264
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002265 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002266 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002267 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002268 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2269 }
2270 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002271
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002272 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002273 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2274 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002275 synchronized (this) {
2276 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2277 }
2278 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002279
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002280 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002281 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002282 synchronized (this) {
2283 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2284 }
2285 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002286
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002287 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002288 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2289 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002290 synchronized (this) {
2291 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002292 }
2293 }
2294
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002295 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002296 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002297 synchronized (this) {
2298 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2299 }
2300 }
2301
2302 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002303 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2304 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002305 synchronized (this) {
2306 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2307 }
2308 }
2309
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002310 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002311 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002312 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002315 private void dispatchProcessesChanged() {
2316 int N;
2317 synchronized (this) {
2318 N = mPendingProcessChanges.size();
2319 if (mActiveProcessChanges.length < N) {
2320 mActiveProcessChanges = new ProcessChangeItem[N];
2321 }
2322 mPendingProcessChanges.toArray(mActiveProcessChanges);
2323 mAvailProcessChanges.addAll(mPendingProcessChanges);
2324 mPendingProcessChanges.clear();
2325 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2326 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002327 int i = mProcessObservers.beginBroadcast();
2328 while (i > 0) {
2329 i--;
2330 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2331 if (observer != null) {
2332 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002333 for (int j=0; j<N; j++) {
2334 ProcessChangeItem item = mActiveProcessChanges[j];
2335 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2336 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2337 + item.pid + " uid=" + item.uid + ": "
2338 + item.foregroundActivities);
2339 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2340 item.foregroundActivities);
2341 }
2342 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2343 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2344 + item.pid + " uid=" + item.uid + ": " + item.importance);
2345 observer.onImportanceChanged(item.pid, item.uid,
2346 item.importance);
2347 }
2348 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002349 } catch (RemoteException e) {
2350 }
2351 }
2352 }
2353 mProcessObservers.finishBroadcast();
2354 }
2355
2356 private void dispatchProcessDied(int pid, int uid) {
2357 int i = mProcessObservers.beginBroadcast();
2358 while (i > 0) {
2359 i--;
2360 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2361 if (observer != null) {
2362 try {
2363 observer.onProcessDied(pid, uid);
2364 } catch (RemoteException e) {
2365 }
2366 }
2367 }
2368 mProcessObservers.finishBroadcast();
2369 }
2370
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002371 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002372 final int N = mPendingActivityLaunches.size();
2373 if (N <= 0) {
2374 return;
2375 }
2376 for (int i=0; i<N; i++) {
2377 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002378 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002379 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002380 }
2381 mPendingActivityLaunches.clear();
2382 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002383
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002384 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 Intent intent, String resolvedType, IBinder resultTo,
2386 String resultWho, int requestCode, int startFlags,
2387 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002388 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002389 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002390 }
2391
2392 public final int startActivityAsUser(IApplicationThread caller,
2393 Intent intent, String resolvedType, IBinder resultTo,
2394 String resultWho, int requestCode, int startFlags,
2395 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002396 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornd8883992012-09-07 15:58:52 -07002397 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2398 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002400 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2401 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002402 }
2403
2404 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002405 Intent intent, String resolvedType, IBinder resultTo,
2406 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002407 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002408 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002409 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2410 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002411 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002412 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002413 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002414 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002415 return res;
2416 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002417
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002418 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002419 Intent intent, String resolvedType, IBinder resultTo,
2420 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002421 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002422 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002423 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2424 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002425 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002426 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002427 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002428 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002429 }
2430
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002431 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002432 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002433 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002435 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002436 // Refuse possible leaked file descriptors
2437 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2438 throw new IllegalArgumentException("File descriptors passed in Intent");
2439 }
2440
2441 IIntentSender sender = intent.getTarget();
2442 if (!(sender instanceof PendingIntentRecord)) {
2443 throw new IllegalArgumentException("Bad PendingIntent object");
2444 }
2445
2446 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002447
2448 synchronized (this) {
2449 // If this is coming from the currently resumed activity, it is
2450 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002451 if (mMainStack.mResumedActivity != null
2452 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002453 Binder.getCallingUid()) {
2454 mAppSwitchesAllowedTime = 0;
2455 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002456 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002457 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2458 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002459 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002460 }
2461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464 // Refuse possible leaked file descriptors
2465 if (intent != null && intent.hasFileDescriptors() == true) {
2466 throw new IllegalArgumentException("File descriptors passed in Intent");
2467 }
2468
2469 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002470 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2471 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002472 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 return false;
2474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 if (r.app == null || r.app.thread == null) {
2476 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002477 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 return false;
2479 }
2480 intent = new Intent(intent);
2481 // The caller is not allowed to change the data.
2482 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2483 // And we are resetting to find the next component...
2484 intent.setComponent(null);
2485
2486 ActivityInfo aInfo = null;
2487 try {
2488 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002489 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002491 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002492 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493
2494 // Look for the original activity in the list...
2495 final int N = resolves != null ? resolves.size() : 0;
2496 for (int i=0; i<N; i++) {
2497 ResolveInfo rInfo = resolves.get(i);
2498 if (rInfo.activityInfo.packageName.equals(r.packageName)
2499 && rInfo.activityInfo.name.equals(r.info.name)) {
2500 // We found the current one... the next matching is
2501 // after it.
2502 i++;
2503 if (i<N) {
2504 aInfo = resolves.get(i).activityInfo;
2505 }
2506 break;
2507 }
2508 }
2509 } catch (RemoteException e) {
2510 }
2511
2512 if (aInfo == null) {
2513 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002514 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 return false;
2516 }
2517
2518 intent.setComponent(new ComponentName(
2519 aInfo.applicationInfo.packageName, aInfo.name));
2520 intent.setFlags(intent.getFlags()&~(
2521 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2522 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2523 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2524 Intent.FLAG_ACTIVITY_NEW_TASK));
2525
2526 // Okay now we need to start the new activity, replacing the
2527 // currently running activity. This is a little tricky because
2528 // we want to start the new one as if the current one is finished,
2529 // but not finish the current one first so that there is no flicker.
2530 // And thus...
2531 final boolean wasFinishing = r.finishing;
2532 r.finishing = true;
2533
2534 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002535 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 final String resultWho = r.resultWho;
2537 final int requestCode = r.requestCode;
2538 r.resultTo = null;
2539 if (resultTo != null) {
2540 resultTo.removeResultsLocked(r, resultWho, requestCode);
2541 }
2542
2543 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002544 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002545 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2546 resultWho, requestCode, -1, r.launchedFromUid, 0,
2547 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 Binder.restoreCallingIdentity(origId);
2549
2550 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002551 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 return false;
2553 }
2554 return true;
2555 }
2556 }
2557
Dianne Hackborn41203752012-08-31 14:05:51 -07002558 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002560 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2561
2562 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2563 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564
Amith Yamasani742a6712011-05-04 14:49:28 -07002565 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002566 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002567 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002568 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002569 }
2570
2571 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002572 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002573 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002574 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002575 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002576 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002577 }
2578
Dianne Hackborn41203752012-08-31 14:05:51 -07002579 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002580 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002581 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002582
Dianne Hackborn41203752012-08-31 14:05:51 -07002583 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2584 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002585 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002586 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002587 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002590 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002592 // Quick case: check if the top-most recent task is the same.
2593 if (N > 0 && mRecentTasks.get(0) == task) {
2594 return;
2595 }
2596 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 for (int i=0; i<N; i++) {
2598 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002599 if (task.userId == tr.userId
2600 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2601 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 mRecentTasks.remove(i);
2603 i--;
2604 N--;
2605 if (task.intent == null) {
2606 // If the new recent task we are adding is not fully
2607 // specified, then replace it with the existing recent task.
2608 task = tr;
2609 }
2610 }
2611 }
2612 if (N >= MAX_RECENT_TASKS) {
2613 mRecentTasks.remove(N-1);
2614 }
2615 mRecentTasks.add(0, task);
2616 }
2617
2618 public void setRequestedOrientation(IBinder token,
2619 int requestedOrientation) {
2620 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002621 ActivityRecord r = mMainStack.isInStackLocked(token);
2622 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 return;
2624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002626 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002628 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002629 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002630 if (config != null) {
2631 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002632 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002633 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 }
2635 }
2636 Binder.restoreCallingIdentity(origId);
2637 }
2638 }
2639
2640 public int getRequestedOrientation(IBinder token) {
2641 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002642 ActivityRecord r = mMainStack.isInStackLocked(token);
2643 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2645 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002646 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
2649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 /**
2651 * This is the internal entry point for handling Activity.finish().
2652 *
2653 * @param token The Binder token referencing the Activity we want to finish.
2654 * @param resultCode Result code, if any, from this Activity.
2655 * @param resultData Result data (Intent), if any, from this Activity.
2656 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002657 * @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 -08002658 */
2659 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2660 // Refuse possible leaked file descriptors
2661 if (resultData != null && resultData.hasFileDescriptors() == true) {
2662 throw new IllegalArgumentException("File descriptors passed in Intent");
2663 }
2664
2665 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002666 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002668 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 if (next != null) {
2670 // ask watcher if this is allowed
2671 boolean resumeOK = true;
2672 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002673 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002675 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677
2678 if (!resumeOK) {
2679 return false;
2680 }
2681 }
2682 }
2683 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002685 resultData, "app-request", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 Binder.restoreCallingIdentity(origId);
2687 return res;
2688 }
2689 }
2690
Dianne Hackborn860755f2010-06-03 18:47:52 -07002691 public final void finishHeavyWeightApp() {
2692 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2693 != PackageManager.PERMISSION_GRANTED) {
2694 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2695 + Binder.getCallingPid()
2696 + ", uid=" + Binder.getCallingUid()
2697 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2698 Slog.w(TAG, msg);
2699 throw new SecurityException(msg);
2700 }
2701
2702 synchronized(this) {
2703 if (mHeavyWeightProcess == null) {
2704 return;
2705 }
2706
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002707 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002708 mHeavyWeightProcess.activities);
2709 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002710 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002711 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002712 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002713 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002714 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002715 null, "finish-heavy", true);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002716 }
2717 }
2718 }
2719
Dianne Hackborn41203752012-08-31 14:05:51 -07002720 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2721 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002722 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002723 }
2724 }
2725
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002726 public void crashApplication(int uid, int initialPid, String packageName,
2727 String message) {
2728 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2729 != PackageManager.PERMISSION_GRANTED) {
2730 String msg = "Permission Denial: crashApplication() from pid="
2731 + Binder.getCallingPid()
2732 + ", uid=" + Binder.getCallingUid()
2733 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2734 Slog.w(TAG, msg);
2735 throw new SecurityException(msg);
2736 }
2737
2738 synchronized(this) {
2739 ProcessRecord proc = null;
2740
2741 // Figure out which process to kill. We don't trust that initialPid
2742 // still has any relation to current pids, so must scan through the
2743 // list.
2744 synchronized (mPidsSelfLocked) {
2745 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2746 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002747 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002748 continue;
2749 }
2750 if (p.pid == initialPid) {
2751 proc = p;
2752 break;
2753 }
2754 for (String str : p.pkgList) {
2755 if (str.equals(packageName)) {
2756 proc = p;
2757 }
2758 }
2759 }
2760 }
2761
2762 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002763 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002764 + " initialPid=" + initialPid
2765 + " packageName=" + packageName);
2766 return;
2767 }
2768
2769 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002770 if (proc.pid == Process.myPid()) {
2771 Log.w(TAG, "crashApplication: trying to crash self!");
2772 return;
2773 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002774 long ident = Binder.clearCallingIdentity();
2775 try {
2776 proc.thread.scheduleCrash(message);
2777 } catch (RemoteException e) {
2778 }
2779 Binder.restoreCallingIdentity(ident);
2780 }
2781 }
2782 }
2783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 public final void finishSubActivity(IBinder token, String resultWho,
2785 int requestCode) {
2786 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002788 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 Binder.restoreCallingIdentity(origId);
2790 }
2791 }
2792
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002793 public boolean finishActivityAffinity(IBinder token) {
2794 synchronized(this) {
2795 final long origId = Binder.clearCallingIdentity();
2796 boolean res = mMainStack.finishActivityAffinityLocked(token);
2797 Binder.restoreCallingIdentity(origId);
2798 return res;
2799 }
2800 }
2801
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002802 public boolean willActivityBeVisible(IBinder token) {
2803 synchronized(this) {
2804 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002805 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2806 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002807 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002808 return true;
2809 }
2810 if (r.fullscreen && !r.finishing) {
2811 return false;
2812 }
2813 }
2814 return true;
2815 }
2816 }
2817
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002818 public void overridePendingTransition(IBinder token, String packageName,
2819 int enterAnim, int exitAnim) {
2820 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002821 ActivityRecord self = mMainStack.isInStackLocked(token);
2822 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002823 return;
2824 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002825
2826 final long origId = Binder.clearCallingIdentity();
2827
2828 if (self.state == ActivityState.RESUMED
2829 || self.state == ActivityState.PAUSING) {
2830 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002831 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002832 }
2833
2834 Binder.restoreCallingIdentity(origId);
2835 }
2836 }
2837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 * Main function for removing an existing process from the activity manager
2840 * as a result of that process going away. Clears out all connections
2841 * to the process.
2842 */
2843 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002844 boolean restarting, boolean allowRestart) {
2845 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002847 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
2849
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002850 if (mProfileProc == app) {
2851 clearProfilerLocked();
2852 }
2853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002855 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2856 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2857 mMainStack.mPausingActivity = null;
2858 }
2859 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2860 mMainStack.mLastPausedActivity = null;
2861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862
2863 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002864 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865
2866 boolean atTop = true;
2867 boolean hasVisibleActivities = false;
2868
2869 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002870 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002871 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 TAG, "Removing app " + app + " from history with " + i + " entries");
2873 while (i > 0) {
2874 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002876 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2878 if (r.app == app) {
2879 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002880 if (ActivityStack.DEBUG_ADD_REMOVE) {
2881 RuntimeException here = new RuntimeException("here");
2882 here.fillInStackTrace();
2883 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2884 + ": haveState=" + r.haveState
2885 + " stateNotNeeded=" + r.stateNotNeeded
2886 + " finishing=" + r.finishing
2887 + " state=" + r.state, here);
2888 }
2889 if (!r.finishing) {
2890 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002891 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2892 System.identityHashCode(r),
2893 r.task.taskId, r.shortComponentName,
2894 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002895 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002896 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897
2898 } else {
2899 // We have the current state for this activity, so
2900 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002901 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 TAG, "Keeping entry, setting app to null");
2903 if (r.visible) {
2904 hasVisibleActivities = true;
2905 }
2906 r.app = null;
2907 r.nowVisible = false;
2908 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002909 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2910 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002911 r.icicle = null;
2912 }
2913 }
2914
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002915 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917 atTop = false;
2918 }
2919
2920 app.activities.clear();
2921
2922 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002923 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 + " running instrumentation " + app.instrumentationClass);
2925 Bundle info = new Bundle();
2926 info.putString("shortMsg", "Process crashed.");
2927 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2928 }
2929
2930 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002931 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 // If there was nothing to resume, and we are not already
2933 // restarting this process, but there is a visible activity that
2934 // is hosted by the process... then make sure all visible
2935 // activities are running, taking care of restarting this
2936 // process.
2937 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002938 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 }
2940 }
2941 }
2942 }
2943
2944 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2945 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002947 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2948 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2950 return i;
2951 }
2952 }
2953 return -1;
2954 }
2955
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 IApplicationThread thread) {
2958 if (thread == null) {
2959 return null;
2960 }
2961
2962 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002963 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 }
2965
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002966 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 IApplicationThread thread) {
2968
2969 mProcDeaths[0]++;
2970
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002971 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2972 synchronized (stats) {
2973 stats.noteProcessDiedLocked(app.info.uid, pid);
2974 }
2975
Magnus Edlund7bb25812010-02-24 15:45:06 +01002976 // Clean up already done if the process has been re-started.
2977 if (app.pid == pid && app.thread != null &&
2978 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002979 if (!app.killedBackground) {
2980 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2981 + ") has died.");
2982 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002983 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002984 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 TAG, "Dying app: " + app + ", pid: " + pid
2986 + ", thread: " + thread.asBinder());
2987 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002988 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989
2990 if (doLowMem) {
2991 // If there are no longer any background processes running,
2992 // and the app that died was not running instrumentation,
2993 // then tell everyone we are now low on memory.
2994 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002995 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2996 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002997 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 haveBg = true;
2999 break;
3000 }
3001 }
3002
3003 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003004 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003005 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003006 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3007 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003008 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003009 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3010 // The low memory report is overriding any current
3011 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003012 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003013 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003014 rec.lastRequestedGc = 0;
3015 } else {
3016 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003018 rec.reportLowMemory = true;
3019 rec.lastLowMemory = now;
3020 mProcessesToGc.remove(rec);
3021 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 }
3023 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003024 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003025 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 }
3027 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003028 } else if (app.pid != pid) {
3029 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003030 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003031 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003032 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003033 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003034 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 + thread.asBinder());
3036 }
3037 }
3038
Dan Egnor42471dd2010-01-07 17:25:22 -08003039 /**
3040 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003041 * @param clearTraces causes the dump file to be erased prior to the new
3042 * traces being written, if true; when false, the new traces will be
3043 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003044 * @param firstPids of dalvik VM processes to dump stack traces for first
3045 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003046 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003047 * @return file containing stack traces, or null if no dump file is configured
3048 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003049 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003050 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003051 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3052 if (tracesPath == null || tracesPath.length() == 0) {
3053 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003055
3056 File tracesFile = new File(tracesPath);
3057 try {
3058 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003059 if (!tracesDir.exists()) {
3060 tracesFile.mkdirs();
3061 if (!SELinux.restorecon(tracesDir)) {
3062 return null;
3063 }
3064 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003065 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3066
Christopher Tate6ee412d2010-05-28 12:01:56 -07003067 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003068 tracesFile.createNewFile();
3069 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3070 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003071 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003072 return null;
3073 }
3074
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003075 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003076 return tracesFile;
3077 }
3078
3079 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003080 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003081 // Use a FileObserver to detect when traces finish writing.
3082 // The order of traces is considered important to maintain for legibility.
3083 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3084 public synchronized void onEvent(int event, String path) { notify(); }
3085 };
3086
3087 try {
3088 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003089
3090 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003091 if (firstPids != null) {
3092 try {
3093 int num = firstPids.size();
3094 for (int i = 0; i < num; i++) {
3095 synchronized (observer) {
3096 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3097 observer.wait(200); // Wait for write-close, give up after 200msec
3098 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003099 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003100 } catch (InterruptedException e) {
3101 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003102 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003103 }
3104
3105 // Next measure CPU usage.
3106 if (processStats != null) {
3107 processStats.init();
3108 System.gc();
3109 processStats.update();
3110 try {
3111 synchronized (processStats) {
3112 processStats.wait(500); // measure over 1/2 second.
3113 }
3114 } catch (InterruptedException e) {
3115 }
3116 processStats.update();
3117
3118 // We'll take the stack crawls of just the top apps using CPU.
3119 final int N = processStats.countWorkingStats();
3120 int numProcs = 0;
3121 for (int i=0; i<N && numProcs<5; i++) {
3122 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3123 if (lastPids.indexOfKey(stats.pid) >= 0) {
3124 numProcs++;
3125 try {
3126 synchronized (observer) {
3127 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3128 observer.wait(200); // Wait for write-close, give up after 200msec
3129 }
3130 } catch (InterruptedException e) {
3131 Log.wtf(TAG, e);
3132 }
3133
3134 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003135 }
3136 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003137
Dan Egnor42471dd2010-01-07 17:25:22 -08003138 } finally {
3139 observer.stopWatching();
3140 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003141
3142 if (nativeProcs != null) {
3143 int[] pids = Process.getPidsForCommands(nativeProcs);
3144 if (pids != null) {
3145 for (int pid : pids) {
3146 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3147 }
3148 }
3149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 }
3151
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003152 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003153 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003154 return;
3155 }
3156 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3157 if (tracesPath == null || tracesPath.length() == 0) {
3158 return;
3159 }
3160
3161 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3162 StrictMode.allowThreadDiskWrites();
3163 try {
3164 final File tracesFile = new File(tracesPath);
3165 final File tracesDir = tracesFile.getParentFile();
3166 final File tracesTmp = new File(tracesDir, "__tmp__");
3167 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003168 if (!tracesDir.exists()) {
3169 tracesFile.mkdirs();
3170 if (!SELinux.restorecon(tracesDir.getPath())) {
3171 return;
3172 }
3173 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003174 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3175
3176 if (tracesFile.exists()) {
3177 tracesTmp.delete();
3178 tracesFile.renameTo(tracesTmp);
3179 }
3180 StringBuilder sb = new StringBuilder();
3181 Time tobj = new Time();
3182 tobj.set(System.currentTimeMillis());
3183 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3184 sb.append(": ");
3185 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3186 sb.append(" since ");
3187 sb.append(msg);
3188 FileOutputStream fos = new FileOutputStream(tracesFile);
3189 fos.write(sb.toString().getBytes());
3190 if (app == null) {
3191 fos.write("\n*** No application process!".getBytes());
3192 }
3193 fos.close();
3194 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3195 } catch (IOException e) {
3196 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3197 return;
3198 }
3199
3200 if (app != null) {
3201 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3202 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003203 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003204 }
3205
3206 File lastTracesFile = null;
3207 File curTracesFile = null;
3208 for (int i=9; i>=0; i--) {
3209 String name = String.format("slow%02d.txt", i);
3210 curTracesFile = new File(tracesDir, name);
3211 if (curTracesFile.exists()) {
3212 if (lastTracesFile != null) {
3213 curTracesFile.renameTo(lastTracesFile);
3214 } else {
3215 curTracesFile.delete();
3216 }
3217 }
3218 lastTracesFile = curTracesFile;
3219 }
3220 tracesFile.renameTo(curTracesFile);
3221 if (tracesTmp.exists()) {
3222 tracesTmp.renameTo(tracesFile);
3223 }
3224 } finally {
3225 StrictMode.setThreadPolicy(oldPolicy);
3226 }
3227 }
3228
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003229 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3230 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003231 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3232 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3233
Dianne Hackborn287952c2010-09-22 22:34:31 -07003234 if (mController != null) {
3235 try {
3236 // 0 == continue, -1 = kill process immediately
3237 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3238 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3239 } catch (RemoteException e) {
3240 mController = null;
3241 }
3242 }
3243
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003244 long anrTime = SystemClock.uptimeMillis();
3245 if (MONITOR_CPU_USAGE) {
3246 updateCpuStatsNow();
3247 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003248
3249 synchronized (this) {
3250 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3251 if (mShuttingDown) {
3252 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3253 return;
3254 } else if (app.notResponding) {
3255 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3256 return;
3257 } else if (app.crashing) {
3258 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3259 return;
3260 }
3261
3262 // In case we come through here for the same app before completing
3263 // this one, mark as anring now so we will bail out.
3264 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003265
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003266 // Log the ANR to the event log.
3267 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3268 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003269
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003270 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003271 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003272
3273 int parentPid = app.pid;
3274 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003275 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003276
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003277 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003278
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003279 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3280 ProcessRecord r = mLruProcesses.get(i);
3281 if (r != null && r.thread != null) {
3282 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003283 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3284 if (r.persistent) {
3285 firstPids.add(pid);
3286 } else {
3287 lastPids.put(pid, Boolean.TRUE);
3288 }
3289 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 }
3292 }
3293
Dan Egnor42471dd2010-01-07 17:25:22 -08003294 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003295 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003296 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003297 info.append("ANR in ").append(app.processName);
3298 if (activity != null && activity.shortComponentName != null) {
3299 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003300 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003301 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003303 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003305 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003306 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308
Dianne Hackborn287952c2010-09-22 22:34:31 -07003309 final ProcessStats processStats = new ProcessStats(true);
3310
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003311 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003312
Dan Egnor42471dd2010-01-07 17:25:22 -08003313 String cpuInfo = null;
3314 if (MONITOR_CPU_USAGE) {
3315 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003316 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003317 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003318 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003319 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003320 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
3322
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003323 info.append(processStats.printCurrentState(anrTime));
3324
Joe Onorato8a9b2202010-02-26 18:56:32 -08003325 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003326 if (tracesFile == null) {
3327 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3328 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3329 }
3330
Jeff Sharkeya353d262011-10-28 11:12:06 -07003331 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3332 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003333
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003334 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003336 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3337 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003339 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3340 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
3342 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003343 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 }
3345 }
3346
Dan Egnor42471dd2010-01-07 17:25:22 -08003347 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3348 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3349 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003350
3351 synchronized (this) {
3352 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003353 Slog.w(TAG, "Killing " + app + ": background ANR");
3354 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3355 app.processName, app.setAdj, "background ANR");
3356 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003357 return;
3358 }
3359
3360 // Set the app's notResponding state, and look up the errorReportReceiver
3361 makeAppNotRespondingLocked(app,
3362 activity != null ? activity.shortComponentName : null,
3363 annotation != null ? "ANR " + annotation : "ANR",
3364 info.toString());
3365
3366 // Bring up the infamous App Not Responding dialog
3367 Message msg = Message.obtain();
3368 HashMap map = new HashMap();
3369 msg.what = SHOW_NOT_RESPONDING_MSG;
3370 msg.obj = map;
3371 map.put("app", app);
3372 if (activity != null) {
3373 map.put("activity", activity);
3374 }
3375
3376 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 }
3379
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003380 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3381 if (!mLaunchWarningShown) {
3382 mLaunchWarningShown = true;
3383 mHandler.post(new Runnable() {
3384 @Override
3385 public void run() {
3386 synchronized (ActivityManagerService.this) {
3387 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3388 d.show();
3389 mHandler.postDelayed(new Runnable() {
3390 @Override
3391 public void run() {
3392 synchronized (ActivityManagerService.this) {
3393 d.dismiss();
3394 mLaunchWarningShown = false;
3395 }
3396 }
3397 }, 4000);
3398 }
3399 }
3400 });
3401 }
3402 }
3403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 public boolean clearApplicationUserData(final String packageName,
Dianne Hackborn1676c852012-09-10 14:52:30 -07003405 final IPackageDataObserver observer, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003406 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 int uid = Binder.getCallingUid();
3408 int pid = Binder.getCallingPid();
Dianne Hackborn1676c852012-09-10 14:52:30 -07003409 userId = handleIncomingUserLocked(pid, uid,
3410 userId, false, true, "clearApplicationUserData", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 long callingId = Binder.clearCallingIdentity();
3412 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003413 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 int pkgUid = -1;
3415 synchronized(this) {
3416 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003417 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 } catch (RemoteException e) {
3419 }
3420 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003421 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 return false;
3423 }
3424 if (uid == pkgUid || checkComponentPermission(
3425 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003426 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003428 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 } else {
3430 throw new SecurityException(pid+" does not have permission:"+
3431 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3432 "for process:"+packageName);
3433 }
3434 }
3435
3436 try {
3437 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3440 Uri.fromParts("package", packageName, null));
3441 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003442 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003443 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 } catch (RemoteException e) {
3445 }
3446 } finally {
3447 Binder.restoreCallingIdentity(callingId);
3448 }
3449 return true;
3450 }
3451
Dianne Hackborn1676c852012-09-10 14:52:30 -07003452 public void killBackgroundProcesses(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003453 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3454 != PackageManager.PERMISSION_GRANTED &&
3455 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3456 != PackageManager.PERMISSION_GRANTED) {
3457 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 + Binder.getCallingPid()
3459 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003460 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003461 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 throw new SecurityException(msg);
3463 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003464
3465 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3466 userId, true, true, "killBackgroundProcesses", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 long callingId = Binder.clearCallingIdentity();
3468 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003469 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003471 int appId = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 try {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003473 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 } catch (RemoteException e) {
3475 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003476 if (appId == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003477 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 return;
3479 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003480 killPackageProcessesLocked(packageName, appId, userId,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003481 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3482 }
3483 } finally {
3484 Binder.restoreCallingIdentity(callingId);
3485 }
3486 }
3487
3488 public void killAllBackgroundProcesses() {
3489 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3490 != PackageManager.PERMISSION_GRANTED) {
3491 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3492 + Binder.getCallingPid()
3493 + ", uid=" + Binder.getCallingUid()
3494 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3495 Slog.w(TAG, msg);
3496 throw new SecurityException(msg);
3497 }
3498
3499 long callingId = Binder.clearCallingIdentity();
3500 try {
3501 synchronized(this) {
3502 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3503 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3504 final int NA = apps.size();
3505 for (int ia=0; ia<NA; ia++) {
3506 ProcessRecord app = apps.valueAt(ia);
3507 if (app.persistent) {
3508 // we don't kill persistent processes
3509 continue;
3510 }
3511 if (app.removed) {
3512 procs.add(app);
3513 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3514 app.removed = true;
3515 procs.add(app);
3516 }
3517 }
3518 }
3519
3520 int N = procs.size();
3521 for (int i=0; i<N; i++) {
3522 removeProcessLocked(procs.get(i), false, true, "kill all background");
3523 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003524 }
3525 } finally {
3526 Binder.restoreCallingIdentity(callingId);
3527 }
3528 }
3529
Dianne Hackborn1676c852012-09-10 14:52:30 -07003530 public void forceStopPackage(final String packageName, int userId) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003531 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3532 != PackageManager.PERMISSION_GRANTED) {
3533 String msg = "Permission Denial: forceStopPackage() from pid="
3534 + Binder.getCallingPid()
3535 + ", uid=" + Binder.getCallingUid()
3536 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003537 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003538 throw new SecurityException(msg);
3539 }
Dianne Hackborn1676c852012-09-10 14:52:30 -07003540 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
3541 userId, true, true, "forceStopPackage", null);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003542 long callingId = Binder.clearCallingIdentity();
3543 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003544 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003545 synchronized(this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003546 int[] users = userId == UserHandle.USER_ALL
3547 ? getUsersLocked() : new int[] { userId };
3548 for (int user : users) {
3549 int pkgUid = -1;
3550 try {
3551 pkgUid = pm.getPackageUid(packageName, user);
3552 } catch (RemoteException e) {
3553 }
3554 if (pkgUid == -1) {
3555 Slog.w(TAG, "Invalid packageName: " + packageName);
3556 continue;
3557 }
3558 try {
3559 pm.setPackageStoppedState(packageName, true, user);
3560 } catch (RemoteException e) {
3561 } catch (IllegalArgumentException e) {
3562 Slog.w(TAG, "Failed trying to unstop package "
3563 + packageName + ": " + e);
3564 }
3565 if (isUserRunningLocked(user)) {
3566 forceStopPackageLocked(packageName, pkgUid);
3567 }
Dianne Hackborne7f97212011-02-24 14:40:20 -08003568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 }
3570 } finally {
3571 Binder.restoreCallingIdentity(callingId);
3572 }
3573 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003574
3575 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003576 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003577 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003578 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003579 if (pkg == null) {
3580 return;
3581 }
3582 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003583 if (appid < 0) {
3584 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003585 return;
3586 }
3587 int callerUid = Binder.getCallingUid();
3588 // Only the system server can kill an application
3589 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003590 // Post an aysnc message to kill the application
3591 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003592 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003593 msg.arg2 = 0;
3594 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003595 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003596 } else {
3597 throw new SecurityException(callerUid + " cannot kill pkg: " +
3598 pkg);
3599 }
3600 }
3601
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003602 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003603 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003604
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003605 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003606 final int uid = Binder.getCallingUid();
3607 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003608 try {
3609 synchronized (this) {
3610 // Only allow this from foreground processes, so that background
3611 // applications can't abuse it to prevent system UI from being shown.
3612 if (uid >= Process.FIRST_APPLICATION_UID) {
3613 ProcessRecord proc;
3614 synchronized (mPidsSelfLocked) {
3615 proc = mPidsSelfLocked.get(pid);
3616 }
3617 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3618 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3619 + " from background process " + proc);
3620 return;
3621 }
3622 }
3623 closeSystemDialogsLocked(reason);
3624 }
3625 } finally {
3626 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003627 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003628 }
3629
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003630 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003631 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003632 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003633 if (reason != null) {
3634 intent.putExtra("reason", reason);
3635 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003636 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003637
Dianne Hackborne302a162012-05-15 14:58:32 -07003638 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3639 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003640 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003641 r.stack.finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003642 Activity.RESULT_CANCELED, null, "close-sys", true);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003643 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003644 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003645
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003646 broadcastIntentLocked(null, null, intent, null,
3647 null, 0, null, null, null, false, false, -1,
3648 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003649 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003650
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003651 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003652 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003653 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003654 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3655 for (int i=pids.length-1; i>=0; i--) {
3656 infos[i] = new Debug.MemoryInfo();
3657 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003658 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003659 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003660 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003661
Dianne Hackbornb437e092011-08-05 17:50:29 -07003662 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003663 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003664 long[] pss = new long[pids.length];
3665 for (int i=pids.length-1; i>=0; i--) {
3666 pss[i] = Debug.getPss(pids[i]);
3667 }
3668 return pss;
3669 }
3670
Christopher Tate5e1ab332009-09-01 20:32:49 -07003671 public void killApplicationProcess(String processName, int uid) {
3672 if (processName == null) {
3673 return;
3674 }
3675
3676 int callerUid = Binder.getCallingUid();
3677 // Only the system server can kill an application
3678 if (callerUid == Process.SYSTEM_UID) {
3679 synchronized (this) {
3680 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003681 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003682 try {
3683 app.thread.scheduleSuicide();
3684 } catch (RemoteException e) {
3685 // If the other end already died, then our work here is done.
3686 }
3687 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003688 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003689 + processName + " / " + uid);
3690 }
3691 }
3692 } else {
3693 throw new SecurityException(callerUid + " cannot kill app process: " +
3694 processName);
3695 }
3696 }
3697
Dianne Hackborn03abb812010-01-04 18:43:19 -08003698 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn1676c852012-09-10 14:52:30 -07003699 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
3700 false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003701 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3702 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003703 if (!mProcessesReady) {
3704 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003706 intent.putExtra(Intent.EXTRA_UID, uid);
3707 broadcastIntentLocked(null, null, intent,
3708 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003709 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003710 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003712
3713 private void forceStopUserLocked(int userId) {
3714 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3715 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3716 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3717 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3718 broadcastIntentLocked(null, null, intent,
3719 null, null, 0, null, null, null,
3720 false, false,
3721 MY_PID, Process.SYSTEM_UID, userId);
3722 }
3723
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003724 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003725 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3726 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003727 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728
Dianne Hackborn03abb812010-01-04 18:43:19 -08003729 // Remove all processes this package may have touched: all with the
3730 // same UID (except for the system or root user), and all whose name
3731 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003732 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003733 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3734 final int NA = apps.size();
3735 for (int ia=0; ia<NA; ia++) {
3736 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003737 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003738 // we don't kill persistent processes
3739 continue;
3740 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003741 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003742 if (doit) {
3743 procs.add(app);
3744 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003745 continue;
3746 }
3747
3748 // Skip process if it doesn't meet our oom adj requirement.
3749 if (app.setAdj < minOomAdj) {
3750 continue;
3751 }
3752
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003753 // If no package is specified, we call all processes under the
3754 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003755 if (packageName == null) {
3756 if (app.userId != userId) {
3757 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003758 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003759 // Package has been specified, we want to hit all processes
3760 // that match it. We need to qualify this by the processes
3761 // that are running under the specified app and user ID.
3762 } else {
3763 if (UserHandle.getAppId(app.uid) != appId) {
3764 continue;
3765 }
3766 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3767 continue;
3768 }
3769 if (!app.pkgList.contains(packageName)) {
3770 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003771 }
3772 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003773
3774 // Process has passed all conditions, kill it!
3775 if (!doit) {
3776 return true;
3777 }
3778 app.removed = true;
3779 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003780 }
3781 }
3782
3783 int N = procs.size();
3784 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003785 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003786 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003787 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003788 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003789
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003790 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003791 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003792 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003793 int i;
3794 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003796 if (userId == UserHandle.USER_ALL && name == null) {
3797 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3798 }
3799
3800 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003802 appId = UserHandle.getAppId(
3803 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 } catch (RemoteException e) {
3805 }
3806 }
3807
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003808 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003809 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003810 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3811 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003812 } else {
3813 Slog.i(TAG, "Force stopping user " + userId);
3814 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003815
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003816 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3817 while (badApps.hasNext()) {
3818 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003819 for (i=ba.size()-1; i>=0; i--) {
3820 boolean remove = false;
3821 final int entUid = ba.keyAt(i);
3822 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003823 if (userId == UserHandle.USER_ALL) {
3824 if (UserHandle.getAppId(entUid) == appId) {
3825 remove = true;
3826 }
3827 } else {
3828 if (entUid == UserHandle.getUid(userId, appId)) {
3829 remove = true;
3830 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003831 }
3832 } else if (UserHandle.getUserId(entUid) == userId) {
3833 remove = true;
3834 }
3835 if (remove) {
3836 ba.removeAt(i);
3837 }
3838 }
3839 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003840 badApps.remove();
3841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 }
3843 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003844
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003845 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3846 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003847 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003848
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003849 TaskRecord lastTask = null;
3850 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003851 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003852 final boolean samePackage = r.packageName.equals(name)
3853 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003854 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003855 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003856 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003857 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003858 if (r.finishing) {
3859 // If this activity is just finishing, then it is not
3860 // interesting as far as something to stop.
3861 continue;
3862 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003863 return true;
3864 }
3865 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003866 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003867 if (samePackage) {
3868 if (r.app != null) {
3869 r.app.removed = true;
3870 }
3871 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003873 lastTask = r.task;
3874 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003875 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003876 i--;
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
3879 }
3880
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003881 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3882 if (!doit) {
3883 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003885 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003886 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003887
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003888 if (name == null) {
3889 // Remove all sticky broadcasts from this user.
3890 mStickyBroadcasts.remove(userId);
3891 }
3892
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003893 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003894 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3895 userId, providers)) {
3896 if (!doit) {
3897 return true;
3898 }
3899 didSomething = true;
3900 }
3901 N = providers.size();
3902 for (i=0; i<N; i++) {
3903 removeDyingProviderLocked(null, providers.get(i), true);
3904 }
3905
3906 if (mIntentSenderRecords.size() > 0) {
3907 Iterator<WeakReference<PendingIntentRecord>> it
3908 = mIntentSenderRecords.values().iterator();
3909 while (it.hasNext()) {
3910 WeakReference<PendingIntentRecord> wpir = it.next();
3911 if (wpir == null) {
3912 it.remove();
3913 continue;
3914 }
3915 PendingIntentRecord pir = wpir.get();
3916 if (pir == null) {
3917 it.remove();
3918 continue;
3919 }
3920 if (name == null) {
3921 // Stopping user, remove all objects for the user.
3922 if (pir.key.userId != userId) {
3923 // Not the same user, skip it.
3924 continue;
3925 }
3926 } else {
3927 if (UserHandle.getAppId(pir.uid) != appId) {
3928 // Different app id, skip it.
3929 continue;
3930 }
3931 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3932 // Different user, skip it.
3933 continue;
3934 }
3935 if (!pir.key.packageName.equals(name)) {
3936 // Different package, skip it.
3937 continue;
3938 }
3939 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003940 if (!doit) {
3941 return true;
3942 }
3943 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003944 it.remove();
3945 pir.canceled = true;
3946 if (pir.key.activity != null) {
3947 pir.key.activity.pendingResults.remove(pir.ref);
3948 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003949 }
3950 }
3951
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003952 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003953 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003954 AttributeCache ac = AttributeCache.instance();
3955 if (ac != null) {
3956 ac.removePackage(name);
3957 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003958 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003959 if (mBooted) {
3960 mMainStack.resumeTopActivityLocked(null);
3961 mMainStack.scheduleIdleLocked();
3962 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003963 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003964
3965 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003966 }
3967
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003968 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003969 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003971 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003973 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 + "/" + uid + ")");
3975
3976 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003977 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003978 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003979 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3980 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003981 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 boolean needRestart = false;
3984 if (app.pid > 0 && app.pid != MY_PID) {
3985 int pid = app.pid;
3986 synchronized (mPidsSelfLocked) {
3987 mPidsSelfLocked.remove(pid);
3988 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3989 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003990 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003991 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003992 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003993 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003995 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003997 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 } else {
3999 needRestart = true;
4000 }
4001 }
4002 } else {
4003 mRemovedProcesses.add(app);
4004 }
4005
4006 return needRestart;
4007 }
4008
4009 private final void processStartTimedOutLocked(ProcessRecord app) {
4010 final int pid = app.pid;
4011 boolean gone = false;
4012 synchronized (mPidsSelfLocked) {
4013 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4014 if (knownApp != null && knownApp.thread == null) {
4015 mPidsSelfLocked.remove(pid);
4016 gone = true;
4017 }
4018 }
4019
4020 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004021 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004022 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004023 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004024 mProcessNames.remove(app.processName, app.uid);
4025 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004026 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004027 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4028 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004029 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004030 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004031 // Take care of any launching providers waiting for this process.
4032 checkAppInLaunchingProvidersLocked(app, true);
4033 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004034 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004035 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4036 app.processName, app.setAdj, "start timeout");
4037 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004038 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004040 try {
4041 IBackupManager bm = IBackupManager.Stub.asInterface(
4042 ServiceManager.getService(Context.BACKUP_SERVICE));
4043 bm.agentDisconnected(app.info.packageName);
4044 } catch (RemoteException e) {
4045 // Can't happen; the backup manager is local
4046 }
4047 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004048 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004049 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004050 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004053 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 }
4055 }
4056
4057 private final boolean attachApplicationLocked(IApplicationThread thread,
4058 int pid) {
4059
4060 // Find the application record that is being attached... either via
4061 // the pid if we are running in multiple processes, or just pull the
4062 // next app record if we are emulating process with anonymous threads.
4063 ProcessRecord app;
4064 if (pid != MY_PID && pid >= 0) {
4065 synchronized (mPidsSelfLocked) {
4066 app = mPidsSelfLocked.get(pid);
4067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 } else {
4069 app = null;
4070 }
4071
4072 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004073 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004075 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004077 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 } else {
4079 try {
4080 thread.scheduleExit();
4081 } catch (Exception e) {
4082 // Ignore exceptions.
4083 }
4084 }
4085 return false;
4086 }
4087
4088 // If this application record is still attached to a previous
4089 // process, clean it up now.
4090 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004091 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 }
4093
4094 // Tell the process all about itself.
4095
Joe Onorato8a9b2202010-02-26 18:56:32 -08004096 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 TAG, "Binding process pid " + pid + " to record " + app);
4098
4099 String processName = app.processName;
4100 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004101 AppDeathRecipient adr = new AppDeathRecipient(
4102 app, pid, thread);
4103 thread.asBinder().linkToDeath(adr, 0);
4104 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 } catch (RemoteException e) {
4106 app.resetPackageList();
4107 startProcessLocked(app, "link fail", processName);
4108 return false;
4109 }
4110
Doug Zongker2bec3d42009-12-04 12:52:44 -08004111 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004112
4113 app.thread = thread;
4114 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004115 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4116 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 app.forcingToForeground = null;
4118 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004119 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 app.debugging = false;
4121
4122 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4123
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004124 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004125 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004127 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004128 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 }
4130
Joe Onorato8a9b2202010-02-26 18:56:32 -08004131 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 TAG, "New app record " + app
4133 + " thread=" + thread.asBinder() + " pid=" + pid);
4134 try {
4135 int testMode = IApplicationThread.DEBUG_OFF;
4136 if (mDebugApp != null && mDebugApp.equals(processName)) {
4137 testMode = mWaitForDebugger
4138 ? IApplicationThread.DEBUG_WAIT
4139 : IApplicationThread.DEBUG_ON;
4140 app.debugging = true;
4141 if (mDebugTransient) {
4142 mDebugApp = mOrigDebugApp;
4143 mWaitForDebugger = mOrigWaitForDebugger;
4144 }
4145 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004146 String profileFile = app.instrumentationProfileFile;
4147 ParcelFileDescriptor profileFd = null;
4148 boolean profileAutoStop = false;
4149 if (mProfileApp != null && mProfileApp.equals(processName)) {
4150 mProfileProc = app;
4151 profileFile = mProfileFile;
4152 profileFd = mProfileFd;
4153 profileAutoStop = mAutoStopProfiler;
4154 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004155 boolean enableOpenGlTrace = false;
4156 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4157 enableOpenGlTrace = true;
4158 mOpenGlTraceApp = null;
4159 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004160
Christopher Tate181fafa2009-05-14 11:12:14 -07004161 // If the app is being launched for restore or full backup, set it up specially
4162 boolean isRestrictedBackupMode = false;
4163 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4164 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004165 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004166 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4167 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004169 ensurePackageDexOpt(app.instrumentationInfo != null
4170 ? app.instrumentationInfo.packageName
4171 : app.info.packageName);
4172 if (app.instrumentationClass != null) {
4173 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004174 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004175 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004176 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004177 ApplicationInfo appInfo = app.instrumentationInfo != null
4178 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004179 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004180 if (profileFd != null) {
4181 profileFd = profileFd.dup();
4182 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004183 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004184 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004185 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4186 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004187 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004188 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004189 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004190 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 } catch (Exception e) {
4192 // todo: Yikes! What should we do? For now we will try to
4193 // start another process, but that could easily get us in
4194 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004195 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196
4197 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004198 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 startProcessLocked(app, "bind fail", processName);
4200 return false;
4201 }
4202
4203 // Remove this record from the list of starting applications.
4204 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004205 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4206 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 mProcessesOnHold.remove(app);
4208
4209 boolean badApp = false;
4210 boolean didSomething = false;
4211
4212 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004213 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004214 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004215 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 && processName.equals(hr.processName)) {
4217 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004218 if (mHeadless) {
4219 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4220 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 didSomething = true;
4222 }
4223 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004224 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 + hr.intent.getComponent().flattenToShortString(), e);
4226 badApp = true;
4227 }
4228 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
4231 }
4232
4233 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004234 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004236 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004238 badApp = true;
4239 }
4240 }
4241
Christopher Tatef46723b2012-01-26 14:19:24 -08004242 // Check if a next-broadcast receiver is in this process...
4243 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004245 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004246 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004247 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 }
4250 }
4251
Christopher Tate181fafa2009-05-14 11:12:14 -07004252 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004253 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004254 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004255 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004256 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004257 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4258 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4259 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004260 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004261 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004262 e.printStackTrace();
4263 }
4264 }
4265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 if (badApp) {
4267 // todo: Also need to kill application to deal with all
4268 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004269 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 return false;
4271 }
4272
4273 if (!didSomething) {
4274 updateOomAdjLocked();
4275 }
4276
4277 return true;
4278 }
4279
4280 public final void attachApplication(IApplicationThread thread) {
4281 synchronized (this) {
4282 int callingPid = Binder.getCallingPid();
4283 final long origId = Binder.clearCallingIdentity();
4284 attachApplicationLocked(thread, callingPid);
4285 Binder.restoreCallingIdentity(origId);
4286 }
4287 }
4288
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004289 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004291 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4292 if (stopProfiling) {
4293 synchronized (this) {
4294 if (mProfileProc == r.app) {
4295 if (mProfileFd != null) {
4296 try {
4297 mProfileFd.close();
4298 } catch (IOException e) {
4299 }
4300 clearProfilerLocked();
4301 }
4302 }
4303 }
4304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004305 Binder.restoreCallingIdentity(origId);
4306 }
4307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004309 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004310 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004311 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004312
4313 synchronized (this) {
4314 updateEventDispatchingLocked();
4315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317
Dianne Hackborn661cd522011-08-22 00:26:20 -07004318 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004319 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004320 mWindowManager.showBootMessage(msg, always);
4321 }
4322
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004323 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004324 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004325 final long token = Binder.clearCallingIdentity();
4326 try {
4327 synchronized (this) {
4328 if (mLockScreenShown) {
4329 mLockScreenShown = false;
4330 comeOutOfSleepIfNeededLocked();
4331 }
4332 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004333 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004334 } finally {
4335 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004336 }
4337 }
4338
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004339 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004340 IntentFilter pkgFilter = new IntentFilter();
4341 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4342 pkgFilter.addDataScheme("package");
4343 mContext.registerReceiver(new BroadcastReceiver() {
4344 @Override
4345 public void onReceive(Context context, Intent intent) {
4346 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4347 if (pkgs != null) {
4348 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004349 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004350 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4351 setResultCode(Activity.RESULT_OK);
4352 return;
4353 }
4354 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004355 }
4356 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004357 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004358 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004359
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004360 synchronized (this) {
4361 // Ensure that any processes we had put on hold are now started
4362 // up.
4363 final int NP = mProcessesOnHold.size();
4364 if (NP > 0) {
4365 ArrayList<ProcessRecord> procs =
4366 new ArrayList<ProcessRecord>(mProcessesOnHold);
4367 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004368 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4369 + procs.get(ip));
4370 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004371 }
4372 }
4373
4374 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004375 // Start looking for apps that are abusing wake locks.
4376 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004377 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004378 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004379 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004380 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004381 for (int i=0; i<mStartedUsers.size(); i++) {
4382 UserStartedState uss = mStartedUsers.valueAt(i);
4383 if (uss.mState == UserStartedState.STATE_BOOTING) {
4384 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004385 final int userId = mStartedUsers.keyAt(i);
4386 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4387 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4388 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004389 null, null, 0, null, null,
4390 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004391 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004392 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004393 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004394 }
4395 }
4396 }
4397
4398 final void ensureBootCompleted() {
4399 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004400 boolean enableScreen;
4401 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004402 booting = mBooting;
4403 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004404 enableScreen = !mBooted;
4405 mBooted = true;
4406 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004407
4408 if (booting) {
4409 finishBooting();
4410 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004411
4412 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004413 enableScreenAfterBoot();
4414 }
4415 }
4416
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004417 public final void activityPaused(IBinder token) {
4418 final long origId = Binder.clearCallingIdentity();
4419 mMainStack.activityPaused(token, false);
4420 Binder.restoreCallingIdentity(origId);
4421 }
4422
4423 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4424 CharSequence description) {
4425 if (localLOGV) Slog.v(
4426 TAG, "Activity stopped: token=" + token);
4427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 // Refuse possible leaked file descriptors
4429 if (icicle != null && icicle.hasFileDescriptors()) {
4430 throw new IllegalArgumentException("File descriptors passed in Bundle");
4431 }
4432
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004433 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434
4435 final long origId = Binder.clearCallingIdentity();
4436
4437 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004438 r = mMainStack.isInStackLocked(token);
4439 if (r != null) {
4440 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 }
4442 }
4443
4444 if (r != null) {
4445 sendPendingThumbnail(r, null, null, null, false);
4446 }
4447
4448 trimApplications();
4449
4450 Binder.restoreCallingIdentity(origId);
4451 }
4452
4453 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004454 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004455 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 }
4457
4458 public String getCallingPackage(IBinder token) {
4459 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004460 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004461 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 }
4463 }
4464
4465 public ComponentName getCallingActivity(IBinder token) {
4466 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004467 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 return r != null ? r.intent.getComponent() : null;
4469 }
4470 }
4471
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004472 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004473 ActivityRecord r = mMainStack.isInStackLocked(token);
4474 if (r == null) {
4475 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004477 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 }
4479
4480 public ComponentName getActivityClassForToken(IBinder token) {
4481 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004482 ActivityRecord r = mMainStack.isInStackLocked(token);
4483 if (r == null) {
4484 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004486 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 }
4488 }
4489
4490 public String getPackageForToken(IBinder token) {
4491 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004492 ActivityRecord r = mMainStack.isInStackLocked(token);
4493 if (r == null) {
4494 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004496 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
4499
4500 public IIntentSender getIntentSender(int type,
4501 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004502 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004503 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004504 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004506 if (intents != null) {
4507 if (intents.length < 1) {
4508 throw new IllegalArgumentException("Intents array length must be >= 1");
4509 }
4510 for (int i=0; i<intents.length; i++) {
4511 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004512 if (intent != null) {
4513 if (intent.hasFileDescriptors()) {
4514 throw new IllegalArgumentException("File descriptors passed in Intent");
4515 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004516 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004517 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4518 throw new IllegalArgumentException(
4519 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4520 }
4521 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004522 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004523 }
4524 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004525 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004526 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004527 }
4528 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004529 if (options != null) {
4530 if (options.hasFileDescriptors()) {
4531 throw new IllegalArgumentException("File descriptors passed in options");
4532 }
4533 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004535 synchronized(this) {
4536 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004537 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4538 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004540 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004541 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004542 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4543 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 String msg = "Permission Denial: getIntentSender() from pid="
4545 + Binder.getCallingPid()
4546 + ", uid=" + Binder.getCallingUid()
4547 + ", (need uid=" + uid + ")"
4548 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 throw new SecurityException(msg);
4551 }
4552 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004553
4554 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004555 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 } catch (RemoteException e) {
4558 throw new SecurityException(e);
4559 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004560 }
4561 }
4562
Dianne Hackborn41203752012-08-31 14:05:51 -07004563 IIntentSender getIntentSenderLocked(int type, String packageName,
4564 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004565 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4566 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004567 if (DEBUG_MU)
4568 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004569 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004570 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004571 activity = mMainStack.isInStackLocked(token);
4572 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004573 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004575 if (activity.finishing) {
4576 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004578 }
4579
4580 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4581 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4582 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4583 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4584 |PendingIntent.FLAG_UPDATE_CURRENT);
4585
4586 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4587 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004588 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004589 WeakReference<PendingIntentRecord> ref;
4590 ref = mIntentSenderRecords.get(key);
4591 PendingIntentRecord rec = ref != null ? ref.get() : null;
4592 if (rec != null) {
4593 if (!cancelCurrent) {
4594 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004595 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004596 rec.key.requestIntent.replaceExtras(intents != null ?
4597 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004598 }
4599 if (intents != null) {
4600 intents[intents.length-1] = rec.key.requestIntent;
4601 rec.key.allIntents = intents;
4602 rec.key.allResolvedTypes = resolvedTypes;
4603 } else {
4604 rec.key.allIntents = null;
4605 rec.key.allResolvedTypes = null;
4606 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 return rec;
4609 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004610 rec.canceled = true;
4611 mIntentSenderRecords.remove(key);
4612 }
4613 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 return rec;
4615 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004616 rec = new PendingIntentRecord(this, key, callingUid);
4617 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004618 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004619 if (activity.pendingResults == null) {
4620 activity.pendingResults
4621 = new HashSet<WeakReference<PendingIntentRecord>>();
4622 }
4623 activity.pendingResults.add(rec.ref);
4624 }
4625 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 }
4627
4628 public void cancelIntentSender(IIntentSender sender) {
4629 if (!(sender instanceof PendingIntentRecord)) {
4630 return;
4631 }
4632 synchronized(this) {
4633 PendingIntentRecord rec = (PendingIntentRecord)sender;
4634 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004635 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004636 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4637 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 String msg = "Permission Denial: cancelIntentSender() from pid="
4639 + Binder.getCallingPid()
4640 + ", uid=" + Binder.getCallingUid()
4641 + " is not allowed to cancel packges "
4642 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004643 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 throw new SecurityException(msg);
4645 }
4646 } catch (RemoteException e) {
4647 throw new SecurityException(e);
4648 }
4649 cancelIntentSenderLocked(rec, true);
4650 }
4651 }
4652
4653 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4654 rec.canceled = true;
4655 mIntentSenderRecords.remove(rec.key);
4656 if (cleanActivity && rec.key.activity != null) {
4657 rec.key.activity.pendingResults.remove(rec.ref);
4658 }
4659 }
4660
4661 public String getPackageForIntentSender(IIntentSender pendingResult) {
4662 if (!(pendingResult instanceof PendingIntentRecord)) {
4663 return null;
4664 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004665 try {
4666 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4667 return res.key.packageName;
4668 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 }
4670 return null;
4671 }
4672
Christopher Tatec4a07d12012-04-06 14:19:13 -07004673 public int getUidForIntentSender(IIntentSender sender) {
4674 if (sender instanceof PendingIntentRecord) {
4675 try {
4676 PendingIntentRecord res = (PendingIntentRecord)sender;
4677 return res.uid;
4678 } catch (ClassCastException e) {
4679 }
4680 }
4681 return -1;
4682 }
4683
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004684 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4685 if (!(pendingResult instanceof PendingIntentRecord)) {
4686 return false;
4687 }
4688 try {
4689 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4690 if (res.key.allIntents == null) {
4691 return false;
4692 }
4693 for (int i=0; i<res.key.allIntents.length; i++) {
4694 Intent intent = res.key.allIntents[i];
4695 if (intent.getPackage() != null && intent.getComponent() != null) {
4696 return false;
4697 }
4698 }
4699 return true;
4700 } catch (ClassCastException e) {
4701 }
4702 return false;
4703 }
4704
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004705 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4706 if (!(pendingResult instanceof PendingIntentRecord)) {
4707 return false;
4708 }
4709 try {
4710 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4711 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4712 return true;
4713 }
4714 return false;
4715 } catch (ClassCastException e) {
4716 }
4717 return false;
4718 }
4719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004720 public void setProcessLimit(int max) {
4721 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4722 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004723 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004724 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004725 mProcessLimitOverride = max;
4726 }
4727 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004728 }
4729
4730 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004731 synchronized (this) {
4732 return mProcessLimitOverride;
4733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004734 }
4735
4736 void foregroundTokenDied(ForegroundToken token) {
4737 synchronized (ActivityManagerService.this) {
4738 synchronized (mPidsSelfLocked) {
4739 ForegroundToken cur
4740 = mForegroundProcesses.get(token.pid);
4741 if (cur != token) {
4742 return;
4743 }
4744 mForegroundProcesses.remove(token.pid);
4745 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4746 if (pr == null) {
4747 return;
4748 }
4749 pr.forcingToForeground = null;
4750 pr.foregroundServices = false;
4751 }
4752 updateOomAdjLocked();
4753 }
4754 }
4755
4756 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4757 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4758 "setProcessForeground()");
4759 synchronized(this) {
4760 boolean changed = false;
4761
4762 synchronized (mPidsSelfLocked) {
4763 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004764 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004765 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004766 return;
4767 }
4768 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4769 if (oldToken != null) {
4770 oldToken.token.unlinkToDeath(oldToken, 0);
4771 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004772 if (pr != null) {
4773 pr.forcingToForeground = null;
4774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004775 changed = true;
4776 }
4777 if (isForeground && token != null) {
4778 ForegroundToken newToken = new ForegroundToken() {
4779 public void binderDied() {
4780 foregroundTokenDied(this);
4781 }
4782 };
4783 newToken.pid = pid;
4784 newToken.token = token;
4785 try {
4786 token.linkToDeath(newToken, 0);
4787 mForegroundProcesses.put(pid, newToken);
4788 pr.forcingToForeground = token;
4789 changed = true;
4790 } catch (RemoteException e) {
4791 // If the process died while doing this, we will later
4792 // do the cleanup with the process death link.
4793 }
4794 }
4795 }
4796
4797 if (changed) {
4798 updateOomAdjLocked();
4799 }
4800 }
4801 }
4802
4803 // =========================================================
4804 // PERMISSIONS
4805 // =========================================================
4806
4807 static class PermissionController extends IPermissionController.Stub {
4808 ActivityManagerService mActivityManagerService;
4809 PermissionController(ActivityManagerService activityManagerService) {
4810 mActivityManagerService = activityManagerService;
4811 }
4812
4813 public boolean checkPermission(String permission, int pid, int uid) {
4814 return mActivityManagerService.checkPermission(permission, pid,
4815 uid) == PackageManager.PERMISSION_GRANTED;
4816 }
4817 }
4818
4819 /**
4820 * This can be called with or without the global lock held.
4821 */
4822 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004823 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 // We might be performing an operation on behalf of an indirect binder
4825 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4826 // client identity accordingly before proceeding.
4827 Identity tlsIdentity = sCallerIdentity.get();
4828 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004829 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4831 uid = tlsIdentity.uid;
4832 pid = tlsIdentity.pid;
4833 }
4834
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004835 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004836 return PackageManager.PERMISSION_GRANTED;
4837 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004838
4839 return ActivityManager.checkComponentPermission(permission, uid,
4840 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 }
4842
4843 /**
4844 * As the only public entry point for permissions checking, this method
4845 * can enforce the semantic that requesting a check on a null global
4846 * permission is automatically denied. (Internally a null permission
4847 * string is used when calling {@link #checkComponentPermission} in cases
4848 * when only uid-based security is needed.)
4849 *
4850 * This can be called with or without the global lock held.
4851 */
4852 public int checkPermission(String permission, int pid, int uid) {
4853 if (permission == null) {
4854 return PackageManager.PERMISSION_DENIED;
4855 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004856 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 }
4858
4859 /**
4860 * Binder IPC calls go through the public entry point.
4861 * This can be called with or without the global lock held.
4862 */
4863 int checkCallingPermission(String permission) {
4864 return checkPermission(permission,
4865 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004866 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
4868
4869 /**
4870 * This can be called with or without the global lock held.
4871 */
4872 void enforceCallingPermission(String permission, String func) {
4873 if (checkCallingPermission(permission)
4874 == PackageManager.PERMISSION_GRANTED) {
4875 return;
4876 }
4877
4878 String msg = "Permission Denial: " + func + " from pid="
4879 + Binder.getCallingPid()
4880 + ", uid=" + Binder.getCallingUid()
4881 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004882 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 throw new SecurityException(msg);
4884 }
4885
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004886 /**
4887 * Determine if UID is holding permissions required to access {@link Uri} in
4888 * the given {@link ProviderInfo}. Final permission checking is always done
4889 * in {@link ContentProvider}.
4890 */
4891 private final boolean checkHoldingPermissionsLocked(
4892 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004893 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4894 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004895
4896 if (pi.applicationInfo.uid == uid) {
4897 return true;
4898 } else if (!pi.exported) {
4899 return false;
4900 }
4901
4902 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4903 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004905 // check if target holds top-level <provider> permissions
4906 if (!readMet && pi.readPermission != null
4907 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4908 readMet = true;
4909 }
4910 if (!writeMet && pi.writePermission != null
4911 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4912 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004914
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004915 // track if unprotected read/write is allowed; any denied
4916 // <path-permission> below removes this ability
4917 boolean allowDefaultRead = pi.readPermission == null;
4918 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004919
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004920 // check if target holds any <path-permission> that match uri
4921 final PathPermission[] pps = pi.pathPermissions;
4922 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004923 final String path = uri.getPath();
4924 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004925 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004926 i--;
4927 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004928 if (pp.match(path)) {
4929 if (!readMet) {
4930 final String pprperm = pp.getReadPermission();
4931 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4932 + pprperm + " for " + pp.getPath()
4933 + ": match=" + pp.match(path)
4934 + " check=" + pm.checkUidPermission(pprperm, uid));
4935 if (pprperm != null) {
4936 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4937 readMet = true;
4938 } else {
4939 allowDefaultRead = false;
4940 }
4941 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004942 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004943 if (!writeMet) {
4944 final String ppwperm = pp.getWritePermission();
4945 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4946 + ppwperm + " for " + pp.getPath()
4947 + ": match=" + pp.match(path)
4948 + " check=" + pm.checkUidPermission(ppwperm, uid));
4949 if (ppwperm != null) {
4950 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4951 writeMet = true;
4952 } else {
4953 allowDefaultWrite = false;
4954 }
4955 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004956 }
4957 }
4958 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004959 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004960
4961 // grant unprotected <provider> read/write, if not blocked by
4962 // <path-permission> above
4963 if (allowDefaultRead) readMet = true;
4964 if (allowDefaultWrite) writeMet = true;
4965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004966 } catch (RemoteException e) {
4967 return false;
4968 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004969
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004970 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 }
4972
4973 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4974 int modeFlags) {
4975 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004976 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 return true;
4978 }
4979 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4980 if (perms == null) return false;
4981 UriPermission perm = perms.get(uri);
4982 if (perm == null) return false;
4983 return (modeFlags&perm.modeFlags) == modeFlags;
4984 }
4985
4986 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004987 enforceNotIsolatedCaller("checkUriPermission");
4988
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004989 // Another redirected-binder-call permissions check as in
4990 // {@link checkComponentPermission}.
4991 Identity tlsIdentity = sCallerIdentity.get();
4992 if (tlsIdentity != null) {
4993 uid = tlsIdentity.uid;
4994 pid = tlsIdentity.pid;
4995 }
4996
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004997 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004998 // Our own process gets to do everything.
4999 if (pid == MY_PID) {
5000 return PackageManager.PERMISSION_GRANTED;
5001 }
5002 synchronized(this) {
5003 return checkUriPermissionLocked(uri, uid, modeFlags)
5004 ? PackageManager.PERMISSION_GRANTED
5005 : PackageManager.PERMISSION_DENIED;
5006 }
5007 }
5008
Dianne Hackborn39792d22010-08-19 18:01:52 -07005009 /**
5010 * Check if the targetPkg can be granted permission to access uri by
5011 * the callingUid using the given modeFlags. Throws a security exception
5012 * if callingUid is not allowed to do this. Returns the uid of the target
5013 * if the URI permission grant should be performed; returns -1 if it is not
5014 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005015 * If you already know the uid of the target, you can supply it in
5016 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005017 */
5018 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005019 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5021 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5022 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005023 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005024 }
5025
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005026 if (targetPkg != null) {
5027 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5028 "Checking grant " + targetPkg + " permission to " + uri);
5029 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005030
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005031 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032
5033 // If this is not a content: uri, we can't do anything with it.
5034 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005035 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005036 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005037 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039
5040 String name = uri.getAuthority();
5041 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005042 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005043 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 if (cpr != null) {
5045 pi = cpr.info;
5046 } else {
5047 try {
5048 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005049 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005050 } catch (RemoteException ex) {
5051 }
5052 }
5053 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005054 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005055 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005056 }
5057
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005058 int targetUid = lastTargetUid;
5059 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005060 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005061 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005062 if (targetUid < 0) {
5063 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5064 "Can't grant URI permission no uid for: " + targetPkg);
5065 return -1;
5066 }
5067 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 }
5071
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005072 if (targetUid >= 0) {
5073 // First... does the target actually need this permission?
5074 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5075 // No need to grant the target this permission.
5076 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5077 "Target " + targetPkg + " already has full permission to " + uri);
5078 return -1;
5079 }
5080 } else {
5081 // First... there is no target package, so can anyone access it?
5082 boolean allowed = pi.exported;
5083 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5084 if (pi.readPermission != null) {
5085 allowed = false;
5086 }
5087 }
5088 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5089 if (pi.writePermission != null) {
5090 allowed = false;
5091 }
5092 }
5093 if (allowed) {
5094 return -1;
5095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005096 }
5097
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005098 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 if (!pi.grantUriPermissions) {
5100 throw new SecurityException("Provider " + pi.packageName
5101 + "/" + pi.name
5102 + " does not allow granting of Uri permissions (uri "
5103 + uri + ")");
5104 }
5105 if (pi.uriPermissionPatterns != null) {
5106 final int N = pi.uriPermissionPatterns.length;
5107 boolean allowed = false;
5108 for (int i=0; i<N; i++) {
5109 if (pi.uriPermissionPatterns[i] != null
5110 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5111 allowed = true;
5112 break;
5113 }
5114 }
5115 if (!allowed) {
5116 throw new SecurityException("Provider " + pi.packageName
5117 + "/" + pi.name
5118 + " does not allow granting of permission to path of Uri "
5119 + uri);
5120 }
5121 }
5122
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005123 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005124 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005125 if (callingUid != Process.myUid()) {
5126 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5127 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5128 throw new SecurityException("Uid " + callingUid
5129 + " does not have permission to uri " + uri);
5130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 }
5132 }
5133
Dianne Hackborn39792d22010-08-19 18:01:52 -07005134 return targetUid;
5135 }
5136
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005137 public int checkGrantUriPermission(int callingUid, String targetPkg,
5138 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005139 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005140 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005141 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005142 }
5143 }
5144
Dianne Hackborn39792d22010-08-19 18:01:52 -07005145 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5146 Uri uri, int modeFlags, UriPermissionOwner owner) {
5147 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5148 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5149 if (modeFlags == 0) {
5150 return;
5151 }
5152
5153 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005154 // to the uri, and the target doesn't. Let's now give this to
5155 // the target.
5156
Joe Onorato8a9b2202010-02-26 18:56:32 -08005157 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005158 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 HashMap<Uri, UriPermission> targetUris
5161 = mGrantedUriPermissions.get(targetUid);
5162 if (targetUris == null) {
5163 targetUris = new HashMap<Uri, UriPermission>();
5164 mGrantedUriPermissions.put(targetUid, targetUris);
5165 }
5166
5167 UriPermission perm = targetUris.get(uri);
5168 if (perm == null) {
5169 perm = new UriPermission(targetUid, uri);
5170 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005174 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005175 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005176 } else {
5177 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5178 perm.readOwners.add(owner);
5179 owner.addReadPermission(perm);
5180 }
5181 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5182 perm.writeOwners.add(owner);
5183 owner.addWritePermission(perm);
5184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005185 }
5186 }
5187
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005188 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5189 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005190 if (targetPkg == null) {
5191 throw new NullPointerException("targetPkg");
5192 }
5193
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005194 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005195 if (targetUid < 0) {
5196 return;
5197 }
5198
5199 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5200 }
5201
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005202 static class NeededUriGrants extends ArrayList<Uri> {
5203 final String targetPkg;
5204 final int targetUid;
5205 final int flags;
5206
5207 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5208 targetPkg = _targetPkg;
5209 targetUid = _targetUid;
5210 flags = _flags;
5211 }
5212 }
5213
Dianne Hackborn39792d22010-08-19 18:01:52 -07005214 /**
5215 * Like checkGrantUriPermissionLocked, but takes an Intent.
5216 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005217 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5218 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005219 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005220 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5221 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005222 + " from " + intent + "; flags=0x"
5223 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5224
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005225 if (targetPkg == null) {
5226 throw new NullPointerException("targetPkg");
5227 }
5228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005230 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005231 }
5232 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005233 ClipData clip = intent.getClipData();
5234 if (data == null && clip == null) {
5235 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005236 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005237 if (data != null) {
5238 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5239 mode, needed != null ? needed.targetUid : -1);
5240 if (target > 0) {
5241 if (needed == null) {
5242 needed = new NeededUriGrants(targetPkg, target, mode);
5243 }
5244 needed.add(data);
5245 }
5246 }
5247 if (clip != null) {
5248 for (int i=0; i<clip.getItemCount(); i++) {
5249 Uri uri = clip.getItemAt(i).getUri();
5250 if (uri != null) {
5251 int target = -1;
5252 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5253 mode, needed != null ? needed.targetUid : -1);
5254 if (target > 0) {
5255 if (needed == null) {
5256 needed = new NeededUriGrants(targetPkg, target, mode);
5257 }
5258 needed.add(uri);
5259 }
5260 } else {
5261 Intent clipIntent = clip.getItemAt(i).getIntent();
5262 if (clipIntent != null) {
5263 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5264 callingUid, targetPkg, clipIntent, mode, needed);
5265 if (newNeeded != null) {
5266 needed = newNeeded;
5267 }
5268 }
5269 }
5270 }
5271 }
5272
5273 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005274 }
5275
5276 /**
5277 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5278 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005279 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5280 UriPermissionOwner owner) {
5281 if (needed != null) {
5282 for (int i=0; i<needed.size(); i++) {
5283 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5284 needed.get(i), needed.flags, owner);
5285 }
5286 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005287 }
5288
5289 void grantUriPermissionFromIntentLocked(int callingUid,
5290 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005291 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005292 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005293 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005294 return;
5295 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005296
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005297 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 }
5299
5300 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5301 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005302 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 synchronized(this) {
5304 final ProcessRecord r = getRecordForAppLocked(caller);
5305 if (r == null) {
5306 throw new SecurityException("Unable to find app for caller "
5307 + caller
5308 + " when granting permission to uri " + uri);
5309 }
5310 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005311 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005314 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 }
5316
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005317 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 null);
5319 }
5320 }
5321
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005322 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005323 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5324 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5325 HashMap<Uri, UriPermission> perms
5326 = mGrantedUriPermissions.get(perm.uid);
5327 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005328 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005329 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 perms.remove(perm.uri);
5331 if (perms.size() == 0) {
5332 mGrantedUriPermissions.remove(perm.uid);
5333 }
5334 }
5335 }
5336 }
5337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5339 int modeFlags) {
5340 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5341 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5342 if (modeFlags == 0) {
5343 return;
5344 }
5345
Joe Onorato8a9b2202010-02-26 18:56:32 -08005346 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005347 "Revoking all granted permissions to " + uri);
5348
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005349 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350
5351 final String authority = uri.getAuthority();
5352 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005353 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005354 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005355 if (cpr != null) {
5356 pi = cpr.info;
5357 } else {
5358 try {
5359 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005360 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 } catch (RemoteException ex) {
5362 }
5363 }
5364 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005365 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 return;
5367 }
5368
5369 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005370 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005371 // Right now, if you are not the original owner of the permission,
5372 // you are not allowed to revoke it.
5373 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5374 throw new SecurityException("Uid " + callingUid
5375 + " does not have permission to uri " + uri);
5376 //}
5377 }
5378
5379 // Go through all of the permissions and remove any that match.
5380 final List<String> SEGMENTS = uri.getPathSegments();
5381 if (SEGMENTS != null) {
5382 final int NS = SEGMENTS.size();
5383 int N = mGrantedUriPermissions.size();
5384 for (int i=0; i<N; i++) {
5385 HashMap<Uri, UriPermission> perms
5386 = mGrantedUriPermissions.valueAt(i);
5387 Iterator<UriPermission> it = perms.values().iterator();
5388 toploop:
5389 while (it.hasNext()) {
5390 UriPermission perm = it.next();
5391 Uri targetUri = perm.uri;
5392 if (!authority.equals(targetUri.getAuthority())) {
5393 continue;
5394 }
5395 List<String> targetSegments = targetUri.getPathSegments();
5396 if (targetSegments == null) {
5397 continue;
5398 }
5399 if (targetSegments.size() < NS) {
5400 continue;
5401 }
5402 for (int j=0; j<NS; j++) {
5403 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5404 continue toploop;
5405 }
5406 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005407 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005408 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005409 perm.clearModes(modeFlags);
5410 if (perm.modeFlags == 0) {
5411 it.remove();
5412 }
5413 }
5414 if (perms.size() == 0) {
5415 mGrantedUriPermissions.remove(
5416 mGrantedUriPermissions.keyAt(i));
5417 N--;
5418 i--;
5419 }
5420 }
5421 }
5422 }
5423
5424 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5425 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005426 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 synchronized(this) {
5428 final ProcessRecord r = getRecordForAppLocked(caller);
5429 if (r == null) {
5430 throw new SecurityException("Unable to find app for caller "
5431 + caller
5432 + " when revoking permission to uri " + uri);
5433 }
5434 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005435 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 return;
5437 }
5438
5439 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5440 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5441 if (modeFlags == 0) {
5442 return;
5443 }
5444
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005445 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446
5447 final String authority = uri.getAuthority();
5448 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005449 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if (cpr != null) {
5451 pi = cpr.info;
5452 } else {
5453 try {
5454 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005455 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 } catch (RemoteException ex) {
5457 }
5458 }
5459 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005460 Slog.w(TAG, "No content provider found for permission revoke: "
5461 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 return;
5463 }
5464
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005465 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 }
5467 }
5468
Dianne Hackborn7e269642010-08-25 19:50:20 -07005469 @Override
5470 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005471 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005472 synchronized(this) {
5473 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5474 return owner.getExternalTokenLocked();
5475 }
5476 }
5477
5478 @Override
5479 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5480 Uri uri, int modeFlags) {
5481 synchronized(this) {
5482 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5483 if (owner == null) {
5484 throw new IllegalArgumentException("Unknown owner: " + token);
5485 }
5486 if (fromUid != Binder.getCallingUid()) {
5487 if (Binder.getCallingUid() != Process.myUid()) {
5488 // Only system code can grant URI permissions on behalf
5489 // of other users.
5490 throw new SecurityException("nice try");
5491 }
5492 }
5493 if (targetPkg == null) {
5494 throw new IllegalArgumentException("null target");
5495 }
5496 if (uri == null) {
5497 throw new IllegalArgumentException("null uri");
5498 }
5499
5500 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5501 }
5502 }
5503
5504 @Override
5505 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5506 synchronized(this) {
5507 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5508 if (owner == null) {
5509 throw new IllegalArgumentException("Unknown owner: " + token);
5510 }
5511
5512 if (uri == null) {
5513 owner.removeUriPermissionsLocked(mode);
5514 } else {
5515 owner.removeUriPermissionLocked(uri, mode);
5516 }
5517 }
5518 }
5519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5521 synchronized (this) {
5522 ProcessRecord app =
5523 who != null ? getRecordForAppLocked(who) : null;
5524 if (app == null) return;
5525
5526 Message msg = Message.obtain();
5527 msg.what = WAIT_FOR_DEBUGGER_MSG;
5528 msg.obj = app;
5529 msg.arg1 = waiting ? 1 : 0;
5530 mHandler.sendMessage(msg);
5531 }
5532 }
5533
5534 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005535 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5536 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005538 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005539 outInfo.threshold = homeAppMem;
5540 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5541 outInfo.hiddenAppThreshold = hiddenAppMem;
5542 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005543 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005544 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5545 ProcessList.VISIBLE_APP_ADJ);
5546 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5547 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548 }
5549
5550 // =========================================================
5551 // TASK MANAGEMENT
5552 // =========================================================
5553
5554 public List getTasks(int maxNum, int flags,
5555 IThumbnailReceiver receiver) {
5556 ArrayList list = new ArrayList();
5557
5558 PendingThumbnailsRecord pending = null;
5559 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005560 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561
5562 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005563 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5565 + ", receiver=" + receiver);
5566
5567 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5568 != PackageManager.PERMISSION_GRANTED) {
5569 if (receiver != null) {
5570 // If the caller wants to wait for pending thumbnails,
5571 // it ain't gonna get them.
5572 try {
5573 receiver.finished();
5574 } catch (RemoteException ex) {
5575 }
5576 }
5577 String msg = "Permission Denial: getTasks() from pid="
5578 + Binder.getCallingPid()
5579 + ", uid=" + Binder.getCallingUid()
5580 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005581 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 throw new SecurityException(msg);
5583 }
5584
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005585 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005586 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005587 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005588 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 TaskRecord curTask = null;
5590 int numActivities = 0;
5591 int numRunning = 0;
5592 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005593 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005595 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596
5597 // Initialize state for next task if needed.
5598 if (top == null ||
5599 (top.state == ActivityState.INITIALIZING
5600 && top.task == r.task)) {
5601 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 curTask = r.task;
5603 numActivities = numRunning = 0;
5604 }
5605
5606 // Add 'r' into the current task.
5607 numActivities++;
5608 if (r.app != null && r.app.thread != null) {
5609 numRunning++;
5610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611
Joe Onorato8a9b2202010-02-26 18:56:32 -08005612 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 TAG, r.intent.getComponent().flattenToShortString()
5614 + ": task=" + r.task);
5615
5616 // If the next one is a different task, generate a new
5617 // TaskInfo entry for what we have.
5618 if (next == null || next.task != curTask) {
5619 ActivityManager.RunningTaskInfo ci
5620 = new ActivityManager.RunningTaskInfo();
5621 ci.id = curTask.taskId;
5622 ci.baseActivity = r.intent.getComponent();
5623 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005624 if (top.thumbHolder != null) {
5625 ci.description = top.thumbHolder.lastDescription;
5626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 ci.numActivities = numActivities;
5628 ci.numRunning = numRunning;
5629 //System.out.println(
5630 // "#" + maxNum + ": " + " descr=" + ci.description);
5631 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005632 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 TAG, "State=" + top.state + "Idle=" + top.idle
5634 + " app=" + top.app
5635 + " thr=" + (top.app != null ? top.app.thread : null));
5636 if (top.state == ActivityState.RESUMED
5637 || top.state == ActivityState.PAUSING) {
5638 if (top.idle && top.app != null
5639 && top.app.thread != null) {
5640 topRecord = top;
5641 topThumbnail = top.app.thread;
5642 } else {
5643 top.thumbnailNeeded = true;
5644 }
5645 }
5646 if (pending == null) {
5647 pending = new PendingThumbnailsRecord(receiver);
5648 }
5649 pending.pendingRecords.add(top);
5650 }
5651 list.add(ci);
5652 maxNum--;
5653 top = null;
5654 }
5655 }
5656
5657 if (pending != null) {
5658 mPendingThumbnails.add(pending);
5659 }
5660 }
5661
Joe Onorato8a9b2202010-02-26 18:56:32 -08005662 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663
5664 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005665 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005667 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005669 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005670 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 }
5672 }
5673
5674 if (pending == null && receiver != null) {
5675 // In this case all thumbnails were available and the client
5676 // is being asked to be told when the remaining ones come in...
5677 // which is unusually, since the top-most currently running
5678 // activity should never have a canned thumbnail! Oh well.
5679 try {
5680 receiver.finished();
5681 } catch (RemoteException ex) {
5682 }
5683 }
5684
5685 return list;
5686 }
5687
5688 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005689 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005690 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005691 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005692 // Check if the caller is holding permissions for cross-user requests.
5693 if (checkComponentPermission(
5694 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5695 Binder.getCallingPid(), callingUid, -1, true)
5696 != PackageManager.PERMISSION_GRANTED) {
5697 String msg = "Permission Denial: "
5698 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005699 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005700 + "; this requires "
5701 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5702 Slog.w(TAG, msg);
5703 throw new SecurityException(msg);
5704 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005705 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005706 userId = mCurrentUserId;
5707 }
5708 }
5709 }
5710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 synchronized (this) {
5712 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5713 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005714 final boolean detailed = checkCallingPermission(
5715 android.Manifest.permission.GET_DETAILED_TASKS)
5716 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005718 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 final int N = mRecentTasks.size();
5721 ArrayList<ActivityManager.RecentTaskInfo> res
5722 = new ArrayList<ActivityManager.RecentTaskInfo>(
5723 maxNum < N ? maxNum : N);
5724 for (int i=0; i<N && maxNum > 0; i++) {
5725 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005726 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005727 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005728 // Return the entry if desired by the caller. We always return
5729 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005730 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005731 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5732 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005733
Dianne Hackborn905577f2011-09-07 18:31:28 -07005734 if (i == 0
5735 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 || (tr.intent == null)
5737 || ((tr.intent.getFlags()
5738 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5739 ActivityManager.RecentTaskInfo rti
5740 = new ActivityManager.RecentTaskInfo();
5741 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005742 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 rti.baseIntent = new Intent(
5744 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005745 if (!detailed) {
5746 rti.baseIntent.replaceExtras((Bundle)null);
5747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005749 rti.description = tr.lastDescription;
5750
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005751 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5752 // Check whether this activity is currently available.
5753 try {
5754 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005755 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005756 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005757 continue;
5758 }
5759 } else if (rti.baseIntent != null) {
5760 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005761 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005762 continue;
5763 }
5764 }
5765 } catch (RemoteException e) {
5766 // Will never happen.
5767 }
5768 }
5769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 res.add(rti);
5771 maxNum--;
5772 }
5773 }
5774 return res;
5775 }
5776 }
5777
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005778 private TaskRecord taskForIdLocked(int id) {
5779 final int N = mRecentTasks.size();
5780 for (int i=0; i<N; i++) {
5781 TaskRecord tr = mRecentTasks.get(i);
5782 if (tr.taskId == id) {
5783 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005784 }
5785 }
5786 return null;
5787 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005788
5789 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5790 synchronized (this) {
5791 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5792 "getTaskThumbnails()");
5793 TaskRecord tr = taskForIdLocked(id);
5794 if (tr != null) {
5795 return mMainStack.getTaskThumbnailsLocked(tr);
5796 }
5797 }
5798 return null;
5799 }
5800
5801 public boolean removeSubTask(int taskId, int subTaskIndex) {
5802 synchronized (this) {
5803 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5804 "removeSubTask()");
5805 long ident = Binder.clearCallingIdentity();
5806 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005807 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5808 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005809 } finally {
5810 Binder.restoreCallingIdentity(ident);
5811 }
5812 }
5813 }
5814
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005815 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5816 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005817 Intent baseIntent = new Intent(
5818 tr.intent != null ? tr.intent : tr.affinityIntent);
5819 ComponentName component = baseIntent.getComponent();
5820 if (component == null) {
5821 Slog.w(TAG, "Now component for base intent of task: " + tr);
5822 return;
5823 }
5824
5825 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005826 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005827
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005828 if (killProcesses) {
5829 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005830 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005831 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005832 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5833 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5834 for (int i=0; i<uids.size(); i++) {
5835 ProcessRecord proc = uids.valueAt(i);
5836 if (proc.userId != tr.userId) {
5837 continue;
5838 }
5839 if (!proc.pkgList.contains(pkg)) {
5840 continue;
5841 }
5842 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005843 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005844 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005845
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005846 // Kill the running processes.
5847 for (int i=0; i<procs.size(); i++) {
5848 ProcessRecord pr = procs.get(i);
5849 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5850 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5851 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5852 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005853 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005854 Process.killProcessQuiet(pr.pid);
5855 } else {
5856 pr.waitingToKill = "remove task";
5857 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858 }
5859 }
5860 }
5861
5862 public boolean removeTask(int taskId, int flags) {
5863 synchronized (this) {
5864 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5865 "removeTask()");
5866 long ident = Binder.clearCallingIdentity();
5867 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005868 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5869 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 if (r != null) {
5871 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005872 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005873 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005874 } else {
5875 TaskRecord tr = null;
5876 int i=0;
5877 while (i < mRecentTasks.size()) {
5878 TaskRecord t = mRecentTasks.get(i);
5879 if (t.taskId == taskId) {
5880 tr = t;
5881 break;
5882 }
5883 i++;
5884 }
5885 if (tr != null) {
5886 if (tr.numActivities <= 0) {
5887 // Caller is just removing a recent task that is
5888 // not actively running. That is easy!
5889 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005890 cleanUpRemovedTaskLocked(tr, flags);
5891 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005892 } else {
5893 Slog.w(TAG, "removeTask: task " + taskId
5894 + " does not have activities to remove, "
5895 + " but numActivities=" + tr.numActivities
5896 + ": " + tr);
5897 }
5898 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005899 }
5900 } finally {
5901 Binder.restoreCallingIdentity(ident);
5902 }
5903 }
5904 return false;
5905 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5908 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005909 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 TaskRecord jt = startTask;
5911
5912 // First look backwards
5913 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005914 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 if (r.task != jt) {
5916 jt = r.task;
5917 if (affinity.equals(jt.affinity)) {
5918 return j;
5919 }
5920 }
5921 }
5922
5923 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005924 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 jt = startTask;
5926 for (j=startIndex+1; j<N; 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 if (affinity.equals(jt.affinity)) {
5930 return j;
5931 }
5932 jt = r.task;
5933 }
5934 }
5935
5936 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005937 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 return N-1;
5939 }
5940
5941 return -1;
5942 }
5943
5944 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005945 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005947 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005948 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5949 "moveTaskToFront()");
5950
5951 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005952 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5953 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005954 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005955 return;
5956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 final long origId = Binder.clearCallingIdentity();
5958 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005959 TaskRecord tr = taskForIdLocked(task);
5960 if (tr != null) {
5961 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5962 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005964 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5965 // Caller wants the home activity moved with it. To accomplish this,
5966 // we'll just move the home task to the top first.
5967 mMainStack.moveHomeToFrontLocked();
5968 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005969 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005970 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005972 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5973 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005975 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5976 mMainStack.mUserLeaving = true;
5977 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005978 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5979 // Caller wants the home activity moved with it. To accomplish this,
5980 // we'll just move the home task to the top first.
5981 mMainStack.moveHomeToFrontLocked();
5982 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005983 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 return;
5985 }
5986 }
5987 } finally {
5988 Binder.restoreCallingIdentity(origId);
5989 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005990 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 }
5992 }
5993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 public void moveTaskToBack(int task) {
5995 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5996 "moveTaskToBack()");
5997
5998 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005999 if (mMainStack.mResumedActivity != null
6000 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006001 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6002 Binder.getCallingUid(), "Task to back")) {
6003 return;
6004 }
6005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006007 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 Binder.restoreCallingIdentity(origId);
6009 }
6010 }
6011
6012 /**
6013 * Moves an activity, and all of the other activities within the same task, to the bottom
6014 * of the history stack. The activity's order within the task is unchanged.
6015 *
6016 * @param token A reference to the activity we wish to move
6017 * @param nonRoot If false then this only works if the activity is the root
6018 * of a task; if true it will work for any activity in a task.
6019 * @return Returns true if the move completed, false if not.
6020 */
6021 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006022 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 synchronized(this) {
6024 final long origId = Binder.clearCallingIdentity();
6025 int taskId = getTaskForActivityLocked(token, !nonRoot);
6026 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006027 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 }
6029 Binder.restoreCallingIdentity(origId);
6030 }
6031 return false;
6032 }
6033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 public void moveTaskBackwards(int task) {
6035 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6036 "moveTaskBackwards()");
6037
6038 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006039 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6040 Binder.getCallingUid(), "Task backwards")) {
6041 return;
6042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 final long origId = Binder.clearCallingIdentity();
6044 moveTaskBackwardsLocked(task);
6045 Binder.restoreCallingIdentity(origId);
6046 }
6047 }
6048
6049 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006050 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 }
6052
6053 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6054 synchronized(this) {
6055 return getTaskForActivityLocked(token, onlyRoot);
6056 }
6057 }
6058
6059 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006060 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 TaskRecord lastTask = null;
6062 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006063 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006064 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 if (!onlyRoot || lastTask != r.task) {
6066 return r.task.taskId;
6067 }
6068 return -1;
6069 }
6070 lastTask = r.task;
6071 }
6072
6073 return -1;
6074 }
6075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 // =========================================================
6077 // THUMBNAILS
6078 // =========================================================
6079
6080 public void reportThumbnail(IBinder token,
6081 Bitmap thumbnail, CharSequence description) {
6082 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6083 final long origId = Binder.clearCallingIdentity();
6084 sendPendingThumbnail(null, token, thumbnail, description, true);
6085 Binder.restoreCallingIdentity(origId);
6086 }
6087
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006088 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 Bitmap thumbnail, CharSequence description, boolean always) {
6090 TaskRecord task = null;
6091 ArrayList receivers = null;
6092
6093 //System.out.println("Send pending thumbnail: " + r);
6094
6095 synchronized(this) {
6096 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006097 r = mMainStack.isInStackLocked(token);
6098 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 return;
6100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006102 if (thumbnail == null && r.thumbHolder != null) {
6103 thumbnail = r.thumbHolder.lastThumbnail;
6104 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 }
6106 if (thumbnail == null && !always) {
6107 // If there is no thumbnail, and this entry is not actually
6108 // going away, then abort for now and pick up the next
6109 // thumbnail we get.
6110 return;
6111 }
6112 task = r.task;
6113
6114 int N = mPendingThumbnails.size();
6115 int i=0;
6116 while (i<N) {
6117 PendingThumbnailsRecord pr =
6118 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6119 //System.out.println("Looking in " + pr.pendingRecords);
6120 if (pr.pendingRecords.remove(r)) {
6121 if (receivers == null) {
6122 receivers = new ArrayList();
6123 }
6124 receivers.add(pr);
6125 if (pr.pendingRecords.size() == 0) {
6126 pr.finished = true;
6127 mPendingThumbnails.remove(i);
6128 N--;
6129 continue;
6130 }
6131 }
6132 i++;
6133 }
6134 }
6135
6136 if (receivers != null) {
6137 final int N = receivers.size();
6138 for (int i=0; i<N; i++) {
6139 try {
6140 PendingThumbnailsRecord pr =
6141 (PendingThumbnailsRecord)receivers.get(i);
6142 pr.receiver.newThumbnail(
6143 task != null ? task.taskId : -1, thumbnail, description);
6144 if (pr.finished) {
6145 pr.receiver.finished();
6146 }
6147 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006148 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150 }
6151 }
6152 }
6153
6154 // =========================================================
6155 // CONTENT PROVIDERS
6156 // =========================================================
6157
Jeff Brown10e89712011-07-08 18:52:57 -07006158 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6159 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006161 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006162 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006163 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 } catch (RemoteException ex) {
6165 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006166 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006167 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6168 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006170 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 for (int i=0; i<N; i++) {
6172 ProviderInfo cpi =
6173 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006174 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6175 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006176 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006177 // This is a singleton provider, but a user besides the
6178 // default user is asking to initialize a process it runs
6179 // in... well, no, it doesn't actually run in this process,
6180 // it runs in the process of the default user. Get rid of it.
6181 providers.remove(i);
6182 N--;
6183 continue;
6184 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006185
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006186 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006187 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006189 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006190 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006192 if (DEBUG_MU)
6193 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 app.pubProviders.put(cpi.name, cpr);
6195 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006196 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198 }
6199 return providers;
6200 }
6201
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006202 /**
6203 * Check if {@link ProcessRecord} has a possible chance at accessing the
6204 * given {@link ProviderInfo}. Final permission checking is always done
6205 * in {@link ContentProvider}.
6206 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006208 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006210 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006212 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006213 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 return null;
6215 }
6216 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006217 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 == PackageManager.PERMISSION_GRANTED) {
6219 return null;
6220 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006221
6222 PathPermission[] pps = cpi.pathPermissions;
6223 if (pps != null) {
6224 int i = pps.length;
6225 while (i > 0) {
6226 i--;
6227 PathPermission pp = pps[i];
6228 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006229 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006230 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006231 return null;
6232 }
6233 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006234 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006235 == PackageManager.PERMISSION_GRANTED) {
6236 return null;
6237 }
6238 }
6239 }
6240
Dianne Hackbornb424b632010-08-18 15:59:05 -07006241 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6242 if (perms != null) {
6243 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6244 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6245 return null;
6246 }
6247 }
6248 }
6249
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006250 String msg;
6251 if (!cpi.exported) {
6252 msg = "Permission Denial: opening provider " + cpi.name
6253 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6254 + ", uid=" + callingUid + ") that is not exported from uid "
6255 + cpi.applicationInfo.uid;
6256 } else {
6257 msg = "Permission Denial: opening provider " + cpi.name
6258 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6259 + ", uid=" + callingUid + ") requires "
6260 + cpi.readPermission + " or " + cpi.writePermission;
6261 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006262 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 return msg;
6264 }
6265
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006266 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6267 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006268 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006269 for (int i=0; i<r.conProviders.size(); i++) {
6270 ContentProviderConnection conn = r.conProviders.get(i);
6271 if (conn.provider == cpr) {
6272 if (DEBUG_PROVIDER) Slog.v(TAG,
6273 "Adding provider requested by "
6274 + r.processName + " from process "
6275 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6276 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6277 if (stable) {
6278 conn.stableCount++;
6279 conn.numStableIncs++;
6280 } else {
6281 conn.unstableCount++;
6282 conn.numUnstableIncs++;
6283 }
6284 return conn;
6285 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006286 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006287 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6288 if (stable) {
6289 conn.stableCount = 1;
6290 conn.numStableIncs = 1;
6291 } else {
6292 conn.unstableCount = 1;
6293 conn.numUnstableIncs = 1;
6294 }
6295 cpr.connections.add(conn);
6296 r.conProviders.add(conn);
6297 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006298 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006299 cpr.addExternalProcessHandleLocked(externalProcessToken);
6300 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006301 }
6302
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006303 boolean decProviderCountLocked(ContentProviderConnection conn,
6304 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6305 if (conn != null) {
6306 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006307 if (DEBUG_PROVIDER) Slog.v(TAG,
6308 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006309 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006310 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006311 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6312 if (stable) {
6313 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006314 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006315 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006316 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006317 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6318 cpr.connections.remove(conn);
6319 conn.client.conProviders.remove(conn);
6320 return true;
6321 }
6322 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006323 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006324 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006325 return false;
6326 }
6327
Amith Yamasani742a6712011-05-04 14:49:28 -07006328 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006329 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006331 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 ProviderInfo cpi = null;
6333
6334 synchronized(this) {
6335 ProcessRecord r = null;
6336 if (caller != null) {
6337 r = getRecordForAppLocked(caller);
6338 if (r == null) {
6339 throw new SecurityException(
6340 "Unable to find app for caller " + caller
6341 + " (pid=" + Binder.getCallingPid()
6342 + ") when getting content provider " + name);
6343 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006344 if (r.userId != userId) {
6345 throw new SecurityException("Calling requested user " + userId
6346 + " but app is user " + r.userId);
6347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 }
6349
6350 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006351 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006352 boolean providerRunning = cpr != null;
6353 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006355 String msg;
6356 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6357 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359
6360 if (r != null && cpr.canRunHere(r)) {
6361 // This provider has been published or is in the process
6362 // of being published... but it is also allowed to run
6363 // in the caller's process, so don't make a connection
6364 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006365 ContentProviderHolder holder = cpr.newHolder(null);
6366 // don't give caller the provider object, it needs
6367 // to make its own.
6368 holder.provider = null;
6369 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
6371
6372 final long origId = Binder.clearCallingIdentity();
6373
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006374 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006376 conn = incProviderCountLocked(r, cpr, token, stable);
6377 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006378 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006379 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006380 // make sure to count it as being accessed and thus
6381 // back up on the LRU list. This is good because
6382 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006383 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006384 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006385 }
6386
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006387 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006388 if (false) {
6389 if (cpr.name.flattenToShortString().equals(
6390 "com.android.providers.calendar/.CalendarProvider2")) {
6391 Slog.v(TAG, "****************** KILLING "
6392 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006393 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006394 }
6395 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006396 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006397 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6398 // NOTE: there is still a race here where a signal could be
6399 // pending on the process even though we managed to update its
6400 // adj level. Not sure what to do about this, but at least
6401 // the race is now smaller.
6402 if (!success) {
6403 // Uh oh... it looks like the provider's process
6404 // has been killed on us. We need to wait for a new
6405 // process to be started, and make sure its death
6406 // doesn't kill our process.
6407 Slog.i(TAG,
6408 "Existing provider " + cpr.name.flattenToShortString()
6409 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006410 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006411 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006412 if (!lastRef) {
6413 // This wasn't the last ref our process had on
6414 // the provider... we have now been killed, bail.
6415 return null;
6416 }
6417 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006418 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 }
6421
6422 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006423 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006425 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006426 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006428 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006429 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006430 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 } catch (RemoteException ex) {
6432 }
6433 if (cpi == null) {
6434 return null;
6435 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006436 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6437 cpi.name, cpi.flags);
6438 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006439 userId = 0;
6440 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006441 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006442
Dianne Hackbornb424b632010-08-18 15:59:05 -07006443 String msg;
6444 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6445 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 }
6447
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006448 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006449 && !cpi.processName.equals("system")) {
6450 // If this content provider does not run in the system
6451 // process, and the system is not yet ready to run other
6452 // processes, then fail fast instead of hanging.
6453 throw new IllegalArgumentException(
6454 "Attempt to launch content provider before system ready");
6455 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006456
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006457 // Make sure that the user who owns this provider is started. If not,
6458 // we don't want to allow it to run.
6459 if (mStartedUsers.get(userId) == null) {
6460 Slog.w(TAG, "Unable to launch app "
6461 + cpi.applicationInfo.packageName + "/"
6462 + cpi.applicationInfo.uid + " for provider "
6463 + name + ": user " + userId + " is stopped");
6464 return null;
6465 }
6466
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006467 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006468 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 final boolean firstClass = cpr == null;
6470 if (firstClass) {
6471 try {
6472 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006473 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 getApplicationInfo(
6475 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006476 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006478 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 + cpi.name);
6480 return null;
6481 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006482 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006483 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 } catch (RemoteException ex) {
6485 // pm is in same process, this will never happen.
6486 }
6487 }
6488
6489 if (r != null && cpr.canRunHere(r)) {
6490 // If this is a multiprocess provider, then just return its
6491 // info and allow the caller to instantiate it. Only do
6492 // this if the provider is the same user as the caller's
6493 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006494 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006497 if (DEBUG_PROVIDER) {
6498 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006499 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006500 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502
6503 // This is single process, and our app is now connecting to it.
6504 // See if we are already in the process of launching this
6505 // provider.
6506 final int N = mLaunchingProviders.size();
6507 int i;
6508 for (i=0; i<N; i++) {
6509 if (mLaunchingProviders.get(i) == cpr) {
6510 break;
6511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 // If the provider is not already being launched, then get it
6515 // started.
6516 if (i >= N) {
6517 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006518
6519 try {
6520 // Content provider is now in use, its package can't be stopped.
6521 try {
6522 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006523 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006524 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006525 } catch (IllegalArgumentException e) {
6526 Slog.w(TAG, "Failed trying to unstop package "
6527 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006528 }
6529
6530 ProcessRecord proc = startProcessLocked(cpi.processName,
6531 cpr.appInfo, false, 0, "content provider",
6532 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006533 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006534 if (proc == null) {
6535 Slog.w(TAG, "Unable to launch app "
6536 + cpi.applicationInfo.packageName + "/"
6537 + cpi.applicationInfo.uid + " for provider "
6538 + name + ": process is bad");
6539 return null;
6540 }
6541 cpr.launchingApp = proc;
6542 mLaunchingProviders.add(cpr);
6543 } finally {
6544 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 }
6547
6548 // Make sure the provider is published (the same provider class
6549 // may be published under multiple names).
6550 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006551 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006553
Amith Yamasani742a6712011-05-04 14:49:28 -07006554 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 conn = incProviderCountLocked(r, cpr, token, stable);
6556 if (conn != null) {
6557 conn.waiting = true;
6558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 }
6560 }
6561
6562 // Wait for the provider to be published...
6563 synchronized (cpr) {
6564 while (cpr.provider == null) {
6565 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006566 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 + cpi.applicationInfo.packageName + "/"
6568 + cpi.applicationInfo.uid + " for provider "
6569 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006570 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 cpi.applicationInfo.packageName,
6572 cpi.applicationInfo.uid, name);
6573 return null;
6574 }
6575 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006576 if (DEBUG_MU) {
6577 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6578 + cpr.launchingApp);
6579 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006580 if (conn != null) {
6581 conn.waiting = true;
6582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 cpr.wait();
6584 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006585 } finally {
6586 if (conn != null) {
6587 conn.waiting = false;
6588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006589 }
6590 }
6591 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006592 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 }
6594
6595 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006596 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006597 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 if (caller == null) {
6599 String msg = "null IApplicationThread when getting content provider "
6600 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006601 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 throw new SecurityException(msg);
6603 }
6604
Dianne Hackborn41203752012-08-31 14:05:51 -07006605 return getContentProviderImpl(caller, name, null, stable,
6606 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 }
6608
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006609 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6610 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6611 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006612 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006613 }
6614
Dianne Hackborn41203752012-08-31 14:05:51 -07006615 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6616 IBinder token, int userId) {
6617 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619
6620 /**
6621 * Drop a content provider from a ProcessRecord's bookkeeping
6622 * @param cpr
6623 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006624 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006625 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006627 ContentProviderConnection conn;
6628 try {
6629 conn = (ContentProviderConnection)connection;
6630 } catch (ClassCastException e) {
6631 String msg ="removeContentProvider: " + connection
6632 + " not a ContentProviderConnection";
6633 Slog.w(TAG, msg);
6634 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006636 if (conn == null) {
6637 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006639 if (decProviderCountLocked(conn, null, null, stable)) {
6640 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 }
6643 }
6644
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006645 public void removeContentProviderExternal(String name, IBinder token) {
6646 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6647 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006648 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006649 }
6650
Dianne Hackborn41203752012-08-31 14:05:51 -07006651 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006653 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006654 if(cpr == null) {
6655 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006656 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 return;
6658 }
6659
6660 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006661 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006662 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006663 if (localCpr.hasExternalProcessHandles()) {
6664 if (localCpr.removeExternalProcessHandleLocked(token)) {
6665 updateOomAdjLocked();
6666 } else {
6667 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6668 + " with no external reference for token: "
6669 + token + ".");
6670 }
6671 } else {
6672 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6673 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676 }
6677
6678 public final void publishContentProviders(IApplicationThread caller,
6679 List<ContentProviderHolder> providers) {
6680 if (providers == null) {
6681 return;
6682 }
6683
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006684 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006685 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006687 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006688 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 if (r == null) {
6690 throw new SecurityException(
6691 "Unable to find app for caller " + caller
6692 + " (pid=" + Binder.getCallingPid()
6693 + ") when publishing content providers");
6694 }
6695
6696 final long origId = Binder.clearCallingIdentity();
6697
6698 final int N = providers.size();
6699 for (int i=0; i<N; i++) {
6700 ContentProviderHolder src = providers.get(i);
6701 if (src == null || src.info == null || src.provider == null) {
6702 continue;
6703 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006704 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006705 if (DEBUG_MU)
6706 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006708 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006709 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 String names[] = dst.info.authority.split(";");
6711 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006712 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 }
6714
6715 int NL = mLaunchingProviders.size();
6716 int j;
6717 for (j=0; j<NL; j++) {
6718 if (mLaunchingProviders.get(j) == dst) {
6719 mLaunchingProviders.remove(j);
6720 j--;
6721 NL--;
6722 }
6723 }
6724 synchronized (dst) {
6725 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006726 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 dst.notifyAll();
6728 }
6729 updateOomAdjLocked(r);
6730 }
6731 }
6732
6733 Binder.restoreCallingIdentity(origId);
6734 }
6735 }
6736
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006737 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6738 ContentProviderConnection conn;
6739 try {
6740 conn = (ContentProviderConnection)connection;
6741 } catch (ClassCastException e) {
6742 String msg ="refContentProvider: " + connection
6743 + " not a ContentProviderConnection";
6744 Slog.w(TAG, msg);
6745 throw new IllegalArgumentException(msg);
6746 }
6747 if (conn == null) {
6748 throw new NullPointerException("connection is null");
6749 }
6750
6751 synchronized (this) {
6752 if (stable > 0) {
6753 conn.numStableIncs += stable;
6754 }
6755 stable = conn.stableCount + stable;
6756 if (stable < 0) {
6757 throw new IllegalStateException("stableCount < 0: " + stable);
6758 }
6759
6760 if (unstable > 0) {
6761 conn.numUnstableIncs += unstable;
6762 }
6763 unstable = conn.unstableCount + unstable;
6764 if (unstable < 0) {
6765 throw new IllegalStateException("unstableCount < 0: " + unstable);
6766 }
6767
6768 if ((stable+unstable) <= 0) {
6769 throw new IllegalStateException("ref counts can't go to zero here: stable="
6770 + stable + " unstable=" + unstable);
6771 }
6772 conn.stableCount = stable;
6773 conn.unstableCount = unstable;
6774 return !conn.dead;
6775 }
6776 }
6777
6778 public void unstableProviderDied(IBinder connection) {
6779 ContentProviderConnection conn;
6780 try {
6781 conn = (ContentProviderConnection)connection;
6782 } catch (ClassCastException e) {
6783 String msg ="refContentProvider: " + connection
6784 + " not a ContentProviderConnection";
6785 Slog.w(TAG, msg);
6786 throw new IllegalArgumentException(msg);
6787 }
6788 if (conn == null) {
6789 throw new NullPointerException("connection is null");
6790 }
6791
6792 // Safely retrieve the content provider associated with the connection.
6793 IContentProvider provider;
6794 synchronized (this) {
6795 provider = conn.provider.provider;
6796 }
6797
6798 if (provider == null) {
6799 // Um, yeah, we're way ahead of you.
6800 return;
6801 }
6802
6803 // Make sure the caller is being honest with us.
6804 if (provider.asBinder().pingBinder()) {
6805 // Er, no, still looks good to us.
6806 synchronized (this) {
6807 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6808 + " says " + conn + " died, but we don't agree");
6809 return;
6810 }
6811 }
6812
6813 // Well look at that! It's dead!
6814 synchronized (this) {
6815 if (conn.provider.provider != provider) {
6816 // But something changed... good enough.
6817 return;
6818 }
6819
6820 ProcessRecord proc = conn.provider.proc;
6821 if (proc == null || proc.thread == null) {
6822 // Seems like the process is already cleaned up.
6823 return;
6824 }
6825
6826 // As far as we're concerned, this is just like receiving a
6827 // death notification... just a bit prematurely.
6828 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6829 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006830 final long ident = Binder.clearCallingIdentity();
6831 try {
6832 appDiedLocked(proc, proc.pid, proc.thread);
6833 } finally {
6834 Binder.restoreCallingIdentity(ident);
6835 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006836 }
6837 }
6838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006840 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006841 synchronized (mSelf) {
6842 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6843 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006844 if (providers != null) {
6845 for (int i=providers.size()-1; i>=0; i--) {
6846 ProviderInfo pi = (ProviderInfo)providers.get(i);
6847 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6848 Slog.w(TAG, "Not installing system proc provider " + pi.name
6849 + ": not system .apk");
6850 providers.remove(i);
6851 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006852 }
6853 }
6854 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006855 if (providers != null) {
6856 mSystemThread.installSystemProviders(providers);
6857 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006858
6859 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006860
6861 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 }
6863
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006864 /**
6865 * Allows app to retrieve the MIME type of a URI without having permission
6866 * to access its content provider.
6867 *
6868 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6869 *
6870 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6871 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6872 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006873 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006874 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006875 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6876 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006877 final String name = uri.getAuthority();
6878 final long ident = Binder.clearCallingIdentity();
6879 ContentProviderHolder holder = null;
6880
6881 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006882 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006883 if (holder != null) {
6884 return holder.provider.getType(uri);
6885 }
6886 } catch (RemoteException e) {
6887 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6888 return null;
6889 } finally {
6890 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006891 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006892 }
6893 Binder.restoreCallingIdentity(ident);
6894 }
6895
6896 return null;
6897 }
6898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 // =========================================================
6900 // GLOBAL MANAGEMENT
6901 // =========================================================
6902
6903 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006904 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 String proc = customProcess != null ? customProcess : info.processName;
6906 BatteryStatsImpl.Uid.Proc ps = null;
6907 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006908 int uid = info.uid;
6909 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006910 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006911 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6912 uid = 0;
6913 while (true) {
6914 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6915 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6916 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6917 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006918 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006919 mNextIsolatedProcessUid++;
6920 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6921 // No process for this uid, use it.
6922 break;
6923 }
6924 stepsLeft--;
6925 if (stepsLeft <= 0) {
6926 return null;
6927 }
6928 }
6929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006930 synchronized (stats) {
6931 ps = stats.getProcessStatsLocked(info.uid, proc);
6932 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006933 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006934 }
6935
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006936 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6937 ProcessRecord app;
6938 if (!isolated) {
6939 app = getProcessRecordLocked(info.processName, info.uid);
6940 } else {
6941 app = null;
6942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943
6944 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006945 app = newProcessRecordLocked(null, info, null, isolated);
6946 mProcessNames.put(info.processName, app.uid, app);
6947 if (isolated) {
6948 mIsolatedProcesses.put(app.uid, app);
6949 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006950 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 }
6952
Dianne Hackborne7f97212011-02-24 14:40:20 -08006953 // This package really, really can not be stopped.
6954 try {
6955 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006956 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006957 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006958 } catch (IllegalArgumentException e) {
6959 Slog.w(TAG, "Failed trying to unstop package "
6960 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006961 }
6962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006963 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6964 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6965 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006966 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 }
6968 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6969 mPersistentStartingProcesses.add(app);
6970 startProcessLocked(app, "added application", app.processName);
6971 }
6972
6973 return app;
6974 }
6975
6976 public void unhandledBack() {
6977 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6978 "unhandledBack()");
6979
6980 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006981 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006982 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006983 TAG, "Performing unhandledBack(): stack size = " + count);
6984 if (count > 1) {
6985 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006986 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07006987 count-1, Activity.RESULT_CANCELED, null, "unhandled-back", true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 Binder.restoreCallingIdentity(origId);
6989 }
6990 }
6991 }
6992
6993 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006994 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006995 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006996 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006997 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006998 ParcelFileDescriptor pfd = null;
6999 if (cph != null) {
7000 // We record the binder invoker's uid in thread-local storage before
7001 // going to the content provider to open the file. Later, in the code
7002 // that handles all permissions checks, we look for this uid and use
7003 // that rather than the Activity Manager's own uid. The effect is that
7004 // we do the check against the caller's permissions even though it looks
7005 // to the content provider like the Activity Manager itself is making
7006 // the request.
7007 sCallerIdentity.set(new Identity(
7008 Binder.getCallingPid(), Binder.getCallingUid()));
7009 try {
7010 pfd = cph.provider.openFile(uri, "r");
7011 } catch (FileNotFoundException e) {
7012 // do nothing; pfd will be returned null
7013 } finally {
7014 // Ensure that whatever happens, we clean up the identity state
7015 sCallerIdentity.remove();
7016 }
7017
7018 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007019 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007021 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
7023 return pfd;
7024 }
7025
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007026 // Actually is sleeping or shutting down or whatever else in the future
7027 // is an inactive state.
7028 public boolean isSleeping() {
7029 return mSleeping || mShuttingDown;
7030 }
7031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007032 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007033 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7034 != PackageManager.PERMISSION_GRANTED) {
7035 throw new SecurityException("Requires permission "
7036 + android.Manifest.permission.DEVICE_POWER);
7037 }
7038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007039 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007040 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007041 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007042
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007043 if (!mSleeping) {
7044 mSleeping = true;
7045 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007046
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007047 // Initialize the wake times of all processes.
7048 checkExcessivePowerUsageLocked(false);
7049 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7050 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7051 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 }
7054 }
7055
Dianne Hackborn55280a92009-05-07 15:53:46 -07007056 public boolean shutdown(int timeout) {
7057 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7058 != PackageManager.PERMISSION_GRANTED) {
7059 throw new SecurityException("Requires permission "
7060 + android.Manifest.permission.SHUTDOWN);
7061 }
7062
7063 boolean timedout = false;
7064
7065 synchronized(this) {
7066 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007067 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007068
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007069 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007070 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007071 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007072 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007073 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007074 long delay = endTime - System.currentTimeMillis();
7075 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007076 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007077 timedout = true;
7078 break;
7079 }
7080 try {
7081 this.wait();
7082 } catch (InterruptedException e) {
7083 }
7084 }
7085 }
7086 }
7087
7088 mUsageStatsService.shutdown();
7089 mBatteryStatsService.shutdown();
7090
7091 return timedout;
7092 }
7093
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007094 public final void activitySlept(IBinder token) {
7095 if (localLOGV) Slog.v(
7096 TAG, "Activity slept: token=" + token);
7097
7098 ActivityRecord r = null;
7099
7100 final long origId = Binder.clearCallingIdentity();
7101
7102 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007103 r = mMainStack.isInStackLocked(token);
7104 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007105 mMainStack.activitySleptLocked(r);
7106 }
7107 }
7108
7109 Binder.restoreCallingIdentity(origId);
7110 }
7111
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007112 private void comeOutOfSleepIfNeededLocked() {
7113 if (!mWentToSleep && !mLockScreenShown) {
7114 if (mSleeping) {
7115 mSleeping = false;
7116 mMainStack.awakeFromSleepingLocked();
7117 mMainStack.resumeTopActivityLocked(null);
7118 }
7119 }
7120 }
7121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007123 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7124 != PackageManager.PERMISSION_GRANTED) {
7125 throw new SecurityException("Requires permission "
7126 + android.Manifest.permission.DEVICE_POWER);
7127 }
7128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007130 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007131 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007132 comeOutOfSleepIfNeededLocked();
7133 }
7134 }
7135
Jeff Brownc042ee22012-05-08 13:03:42 -07007136 private void updateEventDispatchingLocked() {
7137 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7138 }
7139
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007140 public void setLockScreenShown(boolean shown) {
7141 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7142 != PackageManager.PERMISSION_GRANTED) {
7143 throw new SecurityException("Requires permission "
7144 + android.Manifest.permission.DEVICE_POWER);
7145 }
7146
7147 synchronized(this) {
7148 mLockScreenShown = shown;
7149 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 }
7151 }
7152
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007153 public void stopAppSwitches() {
7154 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7155 != PackageManager.PERMISSION_GRANTED) {
7156 throw new SecurityException("Requires permission "
7157 + android.Manifest.permission.STOP_APP_SWITCHES);
7158 }
7159
7160 synchronized(this) {
7161 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7162 + APP_SWITCH_DELAY_TIME;
7163 mDidAppSwitch = false;
7164 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7165 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7166 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7167 }
7168 }
7169
7170 public void resumeAppSwitches() {
7171 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7172 != PackageManager.PERMISSION_GRANTED) {
7173 throw new SecurityException("Requires permission "
7174 + android.Manifest.permission.STOP_APP_SWITCHES);
7175 }
7176
7177 synchronized(this) {
7178 // Note that we don't execute any pending app switches... we will
7179 // let those wait until either the timeout, or the next start
7180 // activity request.
7181 mAppSwitchesAllowedTime = 0;
7182 }
7183 }
7184
7185 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7186 String name) {
7187 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7188 return true;
7189 }
7190
7191 final int perm = checkComponentPermission(
7192 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007193 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007194 if (perm == PackageManager.PERMISSION_GRANTED) {
7195 return true;
7196 }
7197
Joe Onorato8a9b2202010-02-26 18:56:32 -08007198 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007199 return false;
7200 }
7201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007202 public void setDebugApp(String packageName, boolean waitForDebugger,
7203 boolean persistent) {
7204 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7205 "setDebugApp()");
7206
7207 // Note that this is not really thread safe if there are multiple
7208 // callers into it at the same time, but that's not a situation we
7209 // care about.
7210 if (persistent) {
7211 final ContentResolver resolver = mContext.getContentResolver();
7212 Settings.System.putString(
7213 resolver, Settings.System.DEBUG_APP,
7214 packageName);
7215 Settings.System.putInt(
7216 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7217 waitForDebugger ? 1 : 0);
7218 }
7219
7220 synchronized (this) {
7221 if (!persistent) {
7222 mOrigDebugApp = mDebugApp;
7223 mOrigWaitForDebugger = mWaitForDebugger;
7224 }
7225 mDebugApp = packageName;
7226 mWaitForDebugger = waitForDebugger;
7227 mDebugTransient = !persistent;
7228 if (packageName != null) {
7229 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007230 forceStopPackageLocked(packageName, -1, false, false, true, true,
7231 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007232 Binder.restoreCallingIdentity(origId);
7233 }
7234 }
7235 }
7236
Siva Velusamy92a8b222012-03-09 16:24:04 -08007237 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7238 synchronized (this) {
7239 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7240 if (!isDebuggable) {
7241 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7242 throw new SecurityException("Process not debuggable: " + app.packageName);
7243 }
7244 }
7245
7246 mOpenGlTraceApp = processName;
7247 }
7248 }
7249
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007250 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7251 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7252 synchronized (this) {
7253 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7254 if (!isDebuggable) {
7255 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7256 throw new SecurityException("Process not debuggable: " + app.packageName);
7257 }
7258 }
7259 mProfileApp = processName;
7260 mProfileFile = profileFile;
7261 if (mProfileFd != null) {
7262 try {
7263 mProfileFd.close();
7264 } catch (IOException e) {
7265 }
7266 mProfileFd = null;
7267 }
7268 mProfileFd = profileFd;
7269 mProfileType = 0;
7270 mAutoStopProfiler = autoStopProfiler;
7271 }
7272 }
7273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007274 public void setAlwaysFinish(boolean enabled) {
7275 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7276 "setAlwaysFinish()");
7277
7278 Settings.System.putInt(
7279 mContext.getContentResolver(),
7280 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7281
7282 synchronized (this) {
7283 mAlwaysFinishActivities = enabled;
7284 }
7285 }
7286
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007287 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007289 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007290 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007291 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 }
7293 }
7294
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007295 public boolean isUserAMonkey() {
7296 // For now the fact that there is a controller implies
7297 // we have a monkey.
7298 synchronized (this) {
7299 return mController != null;
7300 }
7301 }
7302
Jeff Sharkeya4620792011-05-20 15:29:23 -07007303 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007304 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7305 "registerProcessObserver()");
7306 synchronized (this) {
7307 mProcessObservers.register(observer);
7308 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007309 }
7310
7311 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007312 synchronized (this) {
7313 mProcessObservers.unregister(observer);
7314 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007315 }
7316
Daniel Sandler69a48172010-06-23 16:29:36 -04007317 public void setImmersive(IBinder token, boolean immersive) {
7318 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007319 ActivityRecord r = mMainStack.isInStackLocked(token);
7320 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007321 throw new IllegalArgumentException();
7322 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007323 r.immersive = immersive;
7324 }
7325 }
7326
7327 public boolean isImmersive(IBinder token) {
7328 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007329 ActivityRecord r = mMainStack.isInStackLocked(token);
7330 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007331 throw new IllegalArgumentException();
7332 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007333 return r.immersive;
7334 }
7335 }
7336
7337 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007338 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007339 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007340 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007341 return (r != null) ? r.immersive : false;
7342 }
7343 }
7344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 public final void enterSafeMode() {
7346 synchronized(this) {
7347 // It only makes sense to do this before the system is ready
7348 // and started launching other packages.
7349 if (!mSystemReady) {
7350 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007351 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 } catch (RemoteException e) {
7353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007354 }
7355 }
7356 }
7357
Jeff Brownb09abc12011-01-13 21:08:27 -08007358 public final void showSafeModeOverlay() {
7359 View v = LayoutInflater.from(mContext).inflate(
7360 com.android.internal.R.layout.safe_mode, null);
7361 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7362 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7363 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7364 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007365 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007366 lp.format = v.getBackground().getOpacity();
7367 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7368 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7369 ((WindowManager)mContext.getSystemService(
7370 Context.WINDOW_SERVICE)).addView(v, lp);
7371 }
7372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 public void noteWakeupAlarm(IIntentSender sender) {
7374 if (!(sender instanceof PendingIntentRecord)) {
7375 return;
7376 }
7377 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7378 synchronized (stats) {
7379 if (mBatteryStatsService.isOnBattery()) {
7380 mBatteryStatsService.enforceCallingPermission();
7381 PendingIntentRecord rec = (PendingIntentRecord)sender;
7382 int MY_UID = Binder.getCallingUid();
7383 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7384 BatteryStatsImpl.Uid.Pkg pkg =
7385 stats.getPackageStatsLocked(uid, rec.key.packageName);
7386 pkg.incWakeupsLocked();
7387 }
7388 }
7389 }
7390
Dianne Hackborn64825172011-03-02 21:32:58 -08007391 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007393 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007395 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 // XXX Note: don't acquire main activity lock here, because the window
7397 // manager calls in with its locks held.
7398
7399 boolean killed = false;
7400 synchronized (mPidsSelfLocked) {
7401 int[] types = new int[pids.length];
7402 int worstType = 0;
7403 for (int i=0; i<pids.length; i++) {
7404 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7405 if (proc != null) {
7406 int type = proc.setAdj;
7407 types[i] = type;
7408 if (type > worstType) {
7409 worstType = type;
7410 }
7411 }
7412 }
7413
Dianne Hackborn64825172011-03-02 21:32:58 -08007414 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007416 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7417 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007418 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007420
7421 // If this is not a secure call, don't let it kill processes that
7422 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007423 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7424 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007425 }
7426
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007427 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 for (int i=0; i<pids.length; i++) {
7429 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7430 if (proc == null) {
7431 continue;
7432 }
7433 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007434 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007435 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007436 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7437 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007439 proc.killedBackground = true;
7440 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 }
7442 }
7443 }
7444 return killed;
7445 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007446
7447 @Override
7448 public boolean killProcessesBelowForeground(String reason) {
7449 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7450 throw new SecurityException("killProcessesBelowForeground() only available to system");
7451 }
7452
7453 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7454 }
7455
7456 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7457 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7458 throw new SecurityException("killProcessesBelowAdj() only available to system");
7459 }
7460
7461 boolean killed = false;
7462 synchronized (mPidsSelfLocked) {
7463 final int size = mPidsSelfLocked.size();
7464 for (int i = 0; i < size; i++) {
7465 final int pid = mPidsSelfLocked.keyAt(i);
7466 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7467 if (proc == null) continue;
7468
7469 final int adj = proc.setAdj;
7470 if (adj > belowAdj && !proc.killedBackground) {
7471 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7472 EventLog.writeEvent(
7473 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7474 killed = true;
7475 proc.killedBackground = true;
7476 Process.killProcessQuiet(pid);
7477 }
7478 }
7479 }
7480 return killed;
7481 }
7482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007483 public final void startRunning(String pkg, String cls, String action,
7484 String data) {
7485 synchronized(this) {
7486 if (mStartRunning) {
7487 return;
7488 }
7489 mStartRunning = true;
7490 mTopComponent = pkg != null && cls != null
7491 ? new ComponentName(pkg, cls) : null;
7492 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7493 mTopData = data;
7494 if (!mSystemReady) {
7495 return;
7496 }
7497 }
7498
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007499 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 }
7501
7502 private void retrieveSettings() {
7503 final ContentResolver resolver = mContext.getContentResolver();
7504 String debugApp = Settings.System.getString(
7505 resolver, Settings.System.DEBUG_APP);
7506 boolean waitForDebugger = Settings.System.getInt(
7507 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7508 boolean alwaysFinishActivities = Settings.System.getInt(
7509 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7510
7511 Configuration configuration = new Configuration();
7512 Settings.System.getConfiguration(resolver, configuration);
7513
7514 synchronized (this) {
7515 mDebugApp = mOrigDebugApp = debugApp;
7516 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7517 mAlwaysFinishActivities = alwaysFinishActivities;
7518 // This happens before any activities are started, so we can
7519 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007520 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007521 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007522 }
7523 }
7524
7525 public boolean testIsSystemReady() {
7526 // no need to synchronize(this) just to read & return the value
7527 return mSystemReady;
7528 }
7529
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007530 private static File getCalledPreBootReceiversFile() {
7531 File dataDir = Environment.getDataDirectory();
7532 File systemDir = new File(dataDir, "system");
7533 File fname = new File(systemDir, "called_pre_boots.dat");
7534 return fname;
7535 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007536
7537 static final int LAST_DONE_VERSION = 10000;
7538
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007539 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7540 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7541 File file = getCalledPreBootReceiversFile();
7542 FileInputStream fis = null;
7543 try {
7544 fis = new FileInputStream(file);
7545 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007546 int fvers = dis.readInt();
7547 if (fvers == LAST_DONE_VERSION) {
7548 String vers = dis.readUTF();
7549 String codename = dis.readUTF();
7550 String build = dis.readUTF();
7551 if (android.os.Build.VERSION.RELEASE.equals(vers)
7552 && android.os.Build.VERSION.CODENAME.equals(codename)
7553 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7554 int num = dis.readInt();
7555 while (num > 0) {
7556 num--;
7557 String pkg = dis.readUTF();
7558 String cls = dis.readUTF();
7559 lastDoneReceivers.add(new ComponentName(pkg, cls));
7560 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007561 }
7562 }
7563 } catch (FileNotFoundException e) {
7564 } catch (IOException e) {
7565 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7566 } finally {
7567 if (fis != null) {
7568 try {
7569 fis.close();
7570 } catch (IOException e) {
7571 }
7572 }
7573 }
7574 return lastDoneReceivers;
7575 }
7576
7577 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7578 File file = getCalledPreBootReceiversFile();
7579 FileOutputStream fos = null;
7580 DataOutputStream dos = null;
7581 try {
7582 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7583 fos = new FileOutputStream(file);
7584 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007585 dos.writeInt(LAST_DONE_VERSION);
7586 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007587 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007588 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007589 dos.writeInt(list.size());
7590 for (int i=0; i<list.size(); i++) {
7591 dos.writeUTF(list.get(i).getPackageName());
7592 dos.writeUTF(list.get(i).getClassName());
7593 }
7594 } catch (IOException e) {
7595 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7596 file.delete();
7597 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007598 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007599 if (dos != null) {
7600 try {
7601 dos.close();
7602 } catch (IOException e) {
7603 // TODO Auto-generated catch block
7604 e.printStackTrace();
7605 }
7606 }
7607 }
7608 }
7609
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007610 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 synchronized(this) {
7612 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007613 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 return;
7615 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007616
7617 // Check to see if there are any update receivers to run.
7618 if (!mDidUpdate) {
7619 if (mWaitingUpdate) {
7620 return;
7621 }
7622 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7623 List<ResolveInfo> ris = null;
7624 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007625 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007626 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007627 } catch (RemoteException e) {
7628 }
7629 if (ris != null) {
7630 for (int i=ris.size()-1; i>=0; i--) {
7631 if ((ris.get(i).activityInfo.applicationInfo.flags
7632 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7633 ris.remove(i);
7634 }
7635 }
7636 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007637
7638 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7639
7640 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007641 for (int i=0; i<ris.size(); i++) {
7642 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007643 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7644 if (lastDoneReceivers.contains(comp)) {
7645 ris.remove(i);
7646 i--;
7647 }
7648 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007649
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007650 for (int i=0; i<ris.size(); i++) {
7651 ActivityInfo ai = ris.get(i).activityInfo;
7652 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7653 doneReceivers.add(comp);
7654 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007655 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007656 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007657 finisher = new IIntentReceiver.Stub() {
7658 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007659 String data, Bundle extras, boolean ordered,
Dianne Hackborn20e80982012-08-31 19:00:44 -07007660 boolean sticky, int sendingUser) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007661 // The raw IIntentReceiver interface is called
7662 // with the AM lock held, so redispatch to
7663 // execute our code without the lock.
7664 mHandler.post(new Runnable() {
7665 public void run() {
7666 synchronized (ActivityManagerService.this) {
7667 mDidUpdate = true;
7668 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007669 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007670 showBootMessage(mContext.getText(
7671 R.string.android_upgrading_complete),
7672 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007673 systemReady(goingCallback);
7674 }
7675 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007676 }
7677 };
7678 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007679 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007680 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007681 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007682 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007683 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007684 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007685 mWaitingUpdate = true;
7686 }
7687 }
7688 }
7689 if (mWaitingUpdate) {
7690 return;
7691 }
7692 mDidUpdate = true;
7693 }
7694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 mSystemReady = true;
7696 if (!mStartRunning) {
7697 return;
7698 }
7699 }
7700
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007701 ArrayList<ProcessRecord> procsToKill = null;
7702 synchronized(mPidsSelfLocked) {
7703 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7704 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7705 if (!isAllowedWhileBooting(proc.info)){
7706 if (procsToKill == null) {
7707 procsToKill = new ArrayList<ProcessRecord>();
7708 }
7709 procsToKill.add(proc);
7710 }
7711 }
7712 }
7713
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007714 synchronized(this) {
7715 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007716 for (int i=procsToKill.size()-1; i>=0; i--) {
7717 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007718 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007719 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007720 }
7721 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007722
7723 // Now that we have cleaned up any update processes, we
7724 // are ready to start launching real processes and know that
7725 // we won't trample on them any more.
7726 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007727 }
7728
Joe Onorato8a9b2202010-02-26 18:56:32 -08007729 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007730 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 SystemClock.uptimeMillis());
7732
7733 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007734 // Make sure we have no pre-ready processes sitting around.
7735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7737 ResolveInfo ri = mContext.getPackageManager()
7738 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007739 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 CharSequence errorMsg = null;
7741 if (ri != null) {
7742 ActivityInfo ai = ri.activityInfo;
7743 ApplicationInfo app = ai.applicationInfo;
7744 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7745 mTopAction = Intent.ACTION_FACTORY_TEST;
7746 mTopData = null;
7747 mTopComponent = new ComponentName(app.packageName,
7748 ai.name);
7749 } else {
7750 errorMsg = mContext.getResources().getText(
7751 com.android.internal.R.string.factorytest_not_system);
7752 }
7753 } else {
7754 errorMsg = mContext.getResources().getText(
7755 com.android.internal.R.string.factorytest_no_action);
7756 }
7757 if (errorMsg != null) {
7758 mTopAction = null;
7759 mTopData = null;
7760 mTopComponent = null;
7761 Message msg = Message.obtain();
7762 msg.what = SHOW_FACTORY_ERROR_MSG;
7763 msg.getData().putCharSequence("msg", errorMsg);
7764 mHandler.sendMessage(msg);
7765 }
7766 }
7767 }
7768
7769 retrieveSettings();
7770
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007771 if (goingCallback != null) goingCallback.run();
7772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 synchronized (this) {
7774 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7775 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007776 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007777 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 if (apps != null) {
7779 int N = apps.size();
7780 int i;
7781 for (i=0; i<N; i++) {
7782 ApplicationInfo info
7783 = (ApplicationInfo)apps.get(i);
7784 if (info != null &&
7785 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007786 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 }
7788 }
7789 }
7790 } catch (RemoteException ex) {
7791 // pm is in same process, this will never happen.
7792 }
7793 }
7794
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007795 // Start up initial activity.
7796 mBooting = true;
7797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007799 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 Message msg = Message.obtain();
7801 msg.what = SHOW_UID_ERROR_MSG;
7802 mHandler.sendMessage(msg);
7803 }
7804 } catch (RemoteException e) {
7805 }
7806
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007807 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 }
7809 }
7810
Dan Egnorb7f03672009-12-09 16:22:32 -08007811 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007812 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007814 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007815 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 startAppProblemLocked(app);
7817 app.stopFreezingAllLocked();
7818 return handleAppCrashLocked(app);
7819 }
7820
Dan Egnorb7f03672009-12-09 16:22:32 -08007821 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007822 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007824 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007825 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7826 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 startAppProblemLocked(app);
7828 app.stopFreezingAllLocked();
7829 }
7830
7831 /**
7832 * Generate a process error record, suitable for attachment to a ProcessRecord.
7833 *
7834 * @param app The ProcessRecord in which the error occurred.
7835 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7836 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007837 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 * @param shortMsg Short message describing the crash.
7839 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007840 * @param stackTrace Full crash stack trace, may be null.
7841 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 * @return Returns a fully-formed AppErrorStateInfo record.
7843 */
7844 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007845 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 report.condition = condition;
7849 report.processName = app.processName;
7850 report.pid = app.pid;
7851 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007852 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 report.shortMsg = shortMsg;
7854 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007855 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856
7857 return report;
7858 }
7859
Dan Egnor42471dd2010-01-07 17:25:22 -08007860 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 synchronized (this) {
7862 app.crashing = false;
7863 app.crashingReport = null;
7864 app.notResponding = false;
7865 app.notRespondingReport = null;
7866 if (app.anrDialog == fromDialog) {
7867 app.anrDialog = null;
7868 }
7869 if (app.waitDialog == fromDialog) {
7870 app.waitDialog = null;
7871 }
7872 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007873 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007874 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007875 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7876 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007877 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 }
7880 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007881
Dan Egnorb7f03672009-12-09 16:22:32 -08007882 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007883 if (mHeadless) {
7884 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7885 return false;
7886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 long now = SystemClock.uptimeMillis();
7888
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007889 Long crashTime;
7890 if (!app.isolated) {
7891 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7892 } else {
7893 crashTime = null;
7894 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007895 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007897 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007899 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007900 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007901 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7902 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007904 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007906 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
7907 null, "crashed", false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007908 }
7909 }
7910 if (!app.persistent) {
7911 // We don't want to start this process again until the user
7912 // explicitly does so... but for persistent process, we really
7913 // need to keep it running. If a persistent process is actually
7914 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007915 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007917 if (!app.isolated) {
7918 // XXX We don't have a way to mark isolated processes
7919 // as bad, since they don't have a peristent identity.
7920 mBadProcesses.put(app.info.processName, app.uid, now);
7921 mProcessCrashTimes.remove(app.info.processName, app.uid);
7922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007923 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007925 // Don't let services in this process be restarted and potentially
7926 // annoy the user repeatedly. Unless it is persistent, since those
7927 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007928 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007929 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 return false;
7931 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007932 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007933 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007934 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007935 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007936 // If the top running activity is from this crashing
7937 // process, then terminate it to avoid getting in a loop.
7938 Slog.w(TAG, " Force finishing activity "
7939 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007940 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007941 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007942 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackborn070783f2010-12-29 16:46:28 -08007943 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007944 // stopped, to avoid a situation where one will get
7945 // re-start our crashing activity once it gets resumed again.
7946 index--;
7947 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007948 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007949 if (r.state == ActivityState.RESUMED
7950 || r.state == ActivityState.PAUSING
7951 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007952 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007953 Slog.w(TAG, " Force finishing activity "
7954 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007955 r.stack.finishActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07007956 Activity.RESULT_CANCELED, null, "crashed", false);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007957 }
7958 }
7959 }
7960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 }
7962
7963 // Bump up the crash count of any services currently running in the proc.
7964 if (app.services.size() != 0) {
7965 // Any services running in the application need to be placed
7966 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007967 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007969 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 sr.crashCount++;
7971 }
7972 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007973
7974 // If the crashing process is what we consider to be the "home process" and it has been
7975 // replaced by a third-party app, clear the package preferred activities from packages
7976 // with a home activity running in the process to prevent a repeatedly crashing app
7977 // from blocking the user to manually clear the list.
7978 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7979 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7980 Iterator it = mHomeProcess.activities.iterator();
7981 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007982 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007983 if (r.isHomeActivity) {
7984 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7985 try {
7986 ActivityThread.getPackageManager()
7987 .clearPackagePreferredActivities(r.packageName);
7988 } catch (RemoteException c) {
7989 // pm is in same process, this will never happen.
7990 }
7991 }
7992 }
7993 }
7994
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007995 if (!app.isolated) {
7996 // XXX Can't keep track of crash times for isolated processes,
7997 // because they don't have a perisistent identity.
7998 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7999 }
8000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 return true;
8002 }
8003
8004 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08008005 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
8006 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 skipCurrentReceiverLocked(app);
8008 }
8009
8010 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08008011 for (BroadcastQueue queue : mBroadcastQueues) {
8012 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 }
8014 }
8015
Dan Egnor60d87622009-12-16 16:32:58 -08008016 /**
8017 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8018 * The application process will exit immediately after this call returns.
8019 * @param app object of the crashing app, null for the system server
8020 * @param crashInfo describing the exception
8021 */
8022 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008023 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008024 final String processName = app == null ? "system_server"
8025 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008026
8027 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008028 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008029 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008030 crashInfo.exceptionClassName,
8031 crashInfo.exceptionMessage,
8032 crashInfo.throwFileName,
8033 crashInfo.throwLineNumber);
8034
Jeff Sharkeya353d262011-10-28 11:12:06 -07008035 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008036
8037 crashApplication(r, crashInfo);
8038 }
8039
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008040 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008041 IBinder app,
8042 int violationMask,
8043 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008044 ProcessRecord r = findAppProcess(app, "StrictMode");
8045 if (r == null) {
8046 return;
8047 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008048
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008049 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008050 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008051 boolean logIt = true;
8052 synchronized (mAlreadyLoggedViolatedStacks) {
8053 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8054 logIt = false;
8055 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008056 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008057 // the relative pain numbers, without logging all
8058 // the stack traces repeatedly. We'd want to do
8059 // likewise in the client code, which also does
8060 // dup suppression, before the Binder call.
8061 } else {
8062 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8063 mAlreadyLoggedViolatedStacks.clear();
8064 }
8065 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8066 }
8067 }
8068 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008069 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008070 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008071 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008072
8073 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8074 AppErrorResult result = new AppErrorResult();
8075 synchronized (this) {
8076 final long origId = Binder.clearCallingIdentity();
8077
8078 Message msg = Message.obtain();
8079 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8080 HashMap<String, Object> data = new HashMap<String, Object>();
8081 data.put("result", result);
8082 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008083 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008084 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008085 msg.obj = data;
8086 mHandler.sendMessage(msg);
8087
8088 Binder.restoreCallingIdentity(origId);
8089 }
8090 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008091 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008092 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008093 }
8094
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008095 // Depending on the policy in effect, there could be a bunch of
8096 // these in quick succession so we try to batch these together to
8097 // minimize disk writes, number of dropbox entries, and maximize
8098 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008099 private void logStrictModeViolationToDropBox(
8100 ProcessRecord process,
8101 StrictMode.ViolationInfo info) {
8102 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008103 return;
8104 }
8105 final boolean isSystemApp = process == null ||
8106 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8107 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008108 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008109 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8110 final DropBoxManager dbox = (DropBoxManager)
8111 mContext.getSystemService(Context.DROPBOX_SERVICE);
8112
8113 // Exit early if the dropbox isn't configured to accept this report type.
8114 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8115
8116 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008117 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008118 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8119 synchronized (sb) {
8120 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008121 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008122 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8123 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008124 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8125 if (info.violationNumThisLoop != 0) {
8126 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8127 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008128 if (info.numAnimationsRunning != 0) {
8129 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8130 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008131 if (info.broadcastIntentAction != null) {
8132 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8133 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008134 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008135 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008136 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008137 if (info.numInstances != -1) {
8138 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8139 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008140 if (info.tags != null) {
8141 for (String tag : info.tags) {
8142 sb.append("Span-Tag: ").append(tag).append("\n");
8143 }
8144 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008145 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008146 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8147 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008148 }
8149 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008150
8151 // Only buffer up to ~64k. Various logging bits truncate
8152 // things at 128k.
8153 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008154 }
8155
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008156 // Flush immediately if the buffer's grown too large, or this
8157 // is a non-system app. Non-system apps are isolated with a
8158 // different tag & policy and not batched.
8159 //
8160 // Batching is useful during internal testing with
8161 // StrictMode settings turned up high. Without batching,
8162 // thousands of separate files could be created on boot.
8163 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008164 new Thread("Error dump: " + dropboxTag) {
8165 @Override
8166 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008167 String report;
8168 synchronized (sb) {
8169 report = sb.toString();
8170 sb.delete(0, sb.length());
8171 sb.trimToSize();
8172 }
8173 if (report.length() != 0) {
8174 dbox.addText(dropboxTag, report);
8175 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008176 }
8177 }.start();
8178 return;
8179 }
8180
8181 // System app batching:
8182 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008183 // An existing dropbox-writing thread is outstanding, so
8184 // we don't need to start it up. The existing thread will
8185 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008186 return;
8187 }
8188
8189 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8190 // (After this point, we shouldn't access AMS internal data structures.)
8191 new Thread("Error dump: " + dropboxTag) {
8192 @Override
8193 public void run() {
8194 // 5 second sleep to let stacks arrive and be batched together
8195 try {
8196 Thread.sleep(5000); // 5 seconds
8197 } catch (InterruptedException e) {}
8198
8199 String errorReport;
8200 synchronized (mStrictModeBuffer) {
8201 errorReport = mStrictModeBuffer.toString();
8202 if (errorReport.length() == 0) {
8203 return;
8204 }
8205 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8206 mStrictModeBuffer.trimToSize();
8207 }
8208 dbox.addText(dropboxTag, errorReport);
8209 }
8210 }.start();
8211 }
8212
Dan Egnor60d87622009-12-16 16:32:58 -08008213 /**
8214 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8215 * @param app object of the crashing app, null for the system server
8216 * @param tag reported by the caller
8217 * @param crashInfo describing the context of the error
8218 * @return true if the process should exit immediately (WTF is fatal)
8219 */
8220 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008221 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008222 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008223 final String processName = app == null ? "system_server"
8224 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008225
8226 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008227 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008228 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008229 tag, crashInfo.exceptionMessage);
8230
Jeff Sharkeya353d262011-10-28 11:12:06 -07008231 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008232
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008233 if (r != null && r.pid != Process.myPid() &&
8234 Settings.Secure.getInt(mContext.getContentResolver(),
8235 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008236 crashApplication(r, crashInfo);
8237 return true;
8238 } else {
8239 return false;
8240 }
8241 }
8242
8243 /**
8244 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8245 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8246 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008247 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008248 if (app == null) {
8249 return null;
8250 }
8251
8252 synchronized (this) {
8253 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8254 final int NA = apps.size();
8255 for (int ia=0; ia<NA; ia++) {
8256 ProcessRecord p = apps.valueAt(ia);
8257 if (p.thread != null && p.thread.asBinder() == app) {
8258 return p;
8259 }
8260 }
8261 }
8262
Dianne Hackborncb44d962011-03-10 17:02:27 -08008263 Slog.w(TAG, "Can't find mystery application for " + reason
8264 + " from pid=" + Binder.getCallingPid()
8265 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008266 return null;
8267 }
8268 }
8269
8270 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008271 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8272 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008273 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008274 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8275 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008276 // Watchdog thread ends up invoking this function (with
8277 // a null ProcessRecord) to add the stack file to dropbox.
8278 // Do not acquire a lock on this (am) in such cases, as it
8279 // could cause a potential deadlock, if and when watchdog
8280 // is invoked due to unavailability of lock on am and it
8281 // would prevent watchdog from killing system_server.
8282 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008283 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008284 return;
8285 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008286 // Note: ProcessRecord 'process' is guarded by the service
8287 // instance. (notably process.pkgList, which could otherwise change
8288 // concurrently during execution of this method)
8289 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008290 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008291 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008292 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008293 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8294 for (String pkg : process.pkgList) {
8295 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008296 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008297 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008298 if (pi != null) {
8299 sb.append(" v").append(pi.versionCode);
8300 if (pi.versionName != null) {
8301 sb.append(" (").append(pi.versionName).append(")");
8302 }
8303 }
8304 } catch (RemoteException e) {
8305 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008306 }
Dan Egnora455d192010-03-12 08:52:28 -08008307 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008308 }
Dan Egnora455d192010-03-12 08:52:28 -08008309 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008310 }
8311
8312 private static String processClass(ProcessRecord process) {
8313 if (process == null || process.pid == MY_PID) {
8314 return "system_server";
8315 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8316 return "system_app";
8317 } else {
8318 return "data_app";
8319 }
8320 }
8321
8322 /**
8323 * Write a description of an error (crash, WTF, ANR) to the drop box.
8324 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8325 * @param process which caused the error, null means the system server
8326 * @param activity which triggered the error, null if unknown
8327 * @param parent activity related to the error, null if unknown
8328 * @param subject line related to the error, null if absent
8329 * @param report in long form describing the error, null if absent
8330 * @param logFile to include in the report, null if none
8331 * @param crashInfo giving an application stack trace, null if absent
8332 */
8333 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008334 ProcessRecord process, String processName, ActivityRecord activity,
8335 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008336 final String report, final File logFile,
8337 final ApplicationErrorReport.CrashInfo crashInfo) {
8338 // NOTE -- this must never acquire the ActivityManagerService lock,
8339 // otherwise the watchdog may be prevented from resetting the system.
8340
8341 final String dropboxTag = processClass(process) + "_" + eventType;
8342 final DropBoxManager dbox = (DropBoxManager)
8343 mContext.getSystemService(Context.DROPBOX_SERVICE);
8344
8345 // Exit early if the dropbox isn't configured to accept this report type.
8346 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8347
8348 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008349 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008350 if (activity != null) {
8351 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8352 }
8353 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8354 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8355 }
8356 if (parent != null && parent != activity) {
8357 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8358 }
8359 if (subject != null) {
8360 sb.append("Subject: ").append(subject).append("\n");
8361 }
8362 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008363 if (Debug.isDebuggerConnected()) {
8364 sb.append("Debugger: Connected\n");
8365 }
Dan Egnora455d192010-03-12 08:52:28 -08008366 sb.append("\n");
8367
8368 // Do the rest in a worker thread to avoid blocking the caller on I/O
8369 // (After this point, we shouldn't access AMS internal data structures.)
8370 Thread worker = new Thread("Error dump: " + dropboxTag) {
8371 @Override
8372 public void run() {
8373 if (report != null) {
8374 sb.append(report);
8375 }
8376 if (logFile != null) {
8377 try {
8378 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8379 } catch (IOException e) {
8380 Slog.e(TAG, "Error reading " + logFile, e);
8381 }
8382 }
8383 if (crashInfo != null && crashInfo.stackTrace != null) {
8384 sb.append(crashInfo.stackTrace);
8385 }
8386
8387 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8388 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8389 if (lines > 0) {
8390 sb.append("\n");
8391
8392 // Merge several logcat streams, and take the last N lines
8393 InputStreamReader input = null;
8394 try {
8395 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8396 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8397 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8398
8399 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8400 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8401 input = new InputStreamReader(logcat.getInputStream());
8402
8403 int num;
8404 char[] buf = new char[8192];
8405 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8406 } catch (IOException e) {
8407 Slog.e(TAG, "Error running logcat", e);
8408 } finally {
8409 if (input != null) try { input.close(); } catch (IOException e) {}
8410 }
8411 }
8412
8413 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008414 }
Dan Egnora455d192010-03-12 08:52:28 -08008415 };
8416
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008417 if (process == null) {
8418 // If process is null, we are being called from some internal code
8419 // and may be about to die -- run this synchronously.
8420 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008421 } else {
8422 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008423 }
8424 }
8425
8426 /**
8427 * Bring up the "unexpected error" dialog box for a crashing app.
8428 * Deal with edge cases (intercepts from instrumented applications,
8429 * ActivityController, error intent receivers, that sort of thing).
8430 * @param r the application crashing
8431 * @param crashInfo describing the failure
8432 */
8433 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008434 long timeMillis = System.currentTimeMillis();
8435 String shortMsg = crashInfo.exceptionClassName;
8436 String longMsg = crashInfo.exceptionMessage;
8437 String stackTrace = crashInfo.stackTrace;
8438 if (shortMsg != null && longMsg != null) {
8439 longMsg = shortMsg + ": " + longMsg;
8440 } else if (shortMsg != null) {
8441 longMsg = shortMsg;
8442 }
8443
Dan Egnor60d87622009-12-16 16:32:58 -08008444 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008446 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 try {
8448 String name = r != null ? r.processName : null;
8449 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008450 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008451 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008452 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 + " at watcher's request");
8454 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008455 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 }
8457 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008458 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 }
8460 }
8461
8462 final long origId = Binder.clearCallingIdentity();
8463
8464 // If this process is running instrumentation, finish it.
8465 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008466 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008468 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8469 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 Bundle info = new Bundle();
8471 info.putString("shortMsg", shortMsg);
8472 info.putString("longMsg", longMsg);
8473 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8474 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008475 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 }
8477
Dan Egnor60d87622009-12-16 16:32:58 -08008478 // If we can't identify the process or it's already exceeded its crash quota,
8479 // quit right away without showing a crash dialog.
8480 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008482 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 }
8484
8485 Message msg = Message.obtain();
8486 msg.what = SHOW_ERROR_MSG;
8487 HashMap data = new HashMap();
8488 data.put("result", result);
8489 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490 msg.obj = data;
8491 mHandler.sendMessage(msg);
8492
8493 Binder.restoreCallingIdentity(origId);
8494 }
8495
8496 int res = result.get();
8497
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008498 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008500 if (r != null && !r.isolated) {
8501 // XXX Can't keep track of crash time for isolated processes,
8502 // since they don't have a persistent identity.
8503 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 SystemClock.uptimeMillis());
8505 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008506 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008507 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008508 }
8509 }
8510
8511 if (appErrorIntent != null) {
8512 try {
8513 mContext.startActivity(appErrorIntent);
8514 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008515 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008519
8520 Intent createAppErrorIntentLocked(ProcessRecord r,
8521 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8522 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008523 if (report == null) {
8524 return null;
8525 }
8526 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8527 result.setComponent(r.errorReportReceiver);
8528 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8529 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8530 return result;
8531 }
8532
Dan Egnorb7f03672009-12-09 16:22:32 -08008533 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8534 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008535 if (r.errorReportReceiver == null) {
8536 return null;
8537 }
8538
8539 if (!r.crashing && !r.notResponding) {
8540 return null;
8541 }
8542
Dan Egnorb7f03672009-12-09 16:22:32 -08008543 ApplicationErrorReport report = new ApplicationErrorReport();
8544 report.packageName = r.info.packageName;
8545 report.installerPackageName = r.errorReportReceiver.getPackageName();
8546 report.processName = r.processName;
8547 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008548 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008549
Dan Egnorb7f03672009-12-09 16:22:32 -08008550 if (r.crashing) {
8551 report.type = ApplicationErrorReport.TYPE_CRASH;
8552 report.crashInfo = crashInfo;
8553 } else if (r.notResponding) {
8554 report.type = ApplicationErrorReport.TYPE_ANR;
8555 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008556
Dan Egnorb7f03672009-12-09 16:22:32 -08008557 report.anrInfo.activity = r.notRespondingReport.tag;
8558 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8559 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008560 }
8561
Dan Egnorb7f03672009-12-09 16:22:32 -08008562 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008563 }
8564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008566 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008567 // assume our apps are happy - lazy create the list
8568 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8569
Dianne Hackborn0c380492012-08-20 17:23:30 -07008570 final boolean allUsers = ActivityManager.checkUidPermission(
8571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8572 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8573 int userId = UserHandle.getUserId(Binder.getCallingUid());
8574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008575 synchronized (this) {
8576
8577 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008578 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8579 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008580 if (!allUsers && app.userId != userId) {
8581 continue;
8582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008583 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8584 // This one's in trouble, so we'll generate a report for it
8585 // crashes are higher priority (in case there's a crash *and* an anr)
8586 ActivityManager.ProcessErrorStateInfo report = null;
8587 if (app.crashing) {
8588 report = app.crashingReport;
8589 } else if (app.notResponding) {
8590 report = app.notRespondingReport;
8591 }
8592
8593 if (report != null) {
8594 if (errList == null) {
8595 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8596 }
8597 errList.add(report);
8598 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008599 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 " crashing = " + app.crashing +
8601 " notResponding = " + app.notResponding);
8602 }
8603 }
8604 }
8605 }
8606
8607 return errList;
8608 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008609
8610 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008611 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008612 if (currApp != null) {
8613 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8614 }
8615 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008616 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8617 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008618 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8619 if (currApp != null) {
8620 currApp.lru = 0;
8621 }
8622 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008623 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008624 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8625 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8626 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8627 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8628 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8629 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8630 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8631 } else {
8632 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8633 }
8634 }
8635
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008636 private void fillInProcMemInfo(ProcessRecord app,
8637 ActivityManager.RunningAppProcessInfo outInfo) {
8638 outInfo.pid = app.pid;
8639 outInfo.uid = app.info.uid;
8640 if (mHeavyWeightProcess == app) {
8641 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8642 }
8643 if (app.persistent) {
8644 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8645 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008646 if (app.hasActivities) {
8647 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8648 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008649 outInfo.lastTrimLevel = app.trimMemoryLevel;
8650 int adj = app.curAdj;
8651 outInfo.importance = oomAdjToImportance(adj, outInfo);
8652 outInfo.importanceReasonCode = app.adjTypeCode;
8653 }
8654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008656 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 // Lazy instantiation of list
8658 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008659 final boolean allUsers = ActivityManager.checkUidPermission(
8660 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8661 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8662 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 synchronized (this) {
8664 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008665 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8666 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008667 if (!allUsers && app.userId != userId) {
8668 continue;
8669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8671 // Generate process state info for running application
8672 ActivityManager.RunningAppProcessInfo currApp =
8673 new ActivityManager.RunningAppProcessInfo(app.processName,
8674 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008675 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008676 if (app.adjSource instanceof ProcessRecord) {
8677 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008678 currApp.importanceReasonImportance = oomAdjToImportance(
8679 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008680 } else if (app.adjSource instanceof ActivityRecord) {
8681 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008682 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8683 }
8684 if (app.adjTarget instanceof ComponentName) {
8685 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8686 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008687 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 // + " lru=" + currApp.lru);
8689 if (runList == null) {
8690 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8691 }
8692 runList.add(currApp);
8693 }
8694 }
8695 }
8696 return runList;
8697 }
8698
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008699 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008700 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008701 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8702 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8703 if (runningApps != null && runningApps.size() > 0) {
8704 Set<String> extList = new HashSet<String>();
8705 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8706 if (app.pkgList != null) {
8707 for (String pkg : app.pkgList) {
8708 extList.add(pkg);
8709 }
8710 }
8711 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008712 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008713 for (String pkg : extList) {
8714 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008715 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008716 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8717 retList.add(info);
8718 }
8719 } catch (RemoteException e) {
8720 }
8721 }
8722 }
8723 return retList;
8724 }
8725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008727 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8728 enforceNotIsolatedCaller("getMyMemoryState");
8729 synchronized (this) {
8730 ProcessRecord proc;
8731 synchronized (mPidsSelfLocked) {
8732 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8733 }
8734 fillInProcMemInfo(proc, outInfo);
8735 }
8736 }
8737
8738 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008740 if (checkCallingPermission(android.Manifest.permission.DUMP)
8741 != PackageManager.PERMISSION_GRANTED) {
8742 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8743 + Binder.getCallingPid()
8744 + ", uid=" + Binder.getCallingUid()
8745 + " without permission "
8746 + android.Manifest.permission.DUMP);
8747 return;
8748 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008749
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008750 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008751 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753
8754 int opti = 0;
8755 while (opti < args.length) {
8756 String opt = args[opti];
8757 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8758 break;
8759 }
8760 opti++;
8761 if ("-a".equals(opt)) {
8762 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008763 } else if ("-c".equals(opt)) {
8764 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 } else if ("-h".equals(opt)) {
8766 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008767 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008768 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008769 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008770 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8771 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8772 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008773 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008774 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008775 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008776 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008778 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008779 pw.println(" all: dump all activities");
8780 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008781 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008782 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8783 pw.println(" a partial substring in a component name, a");
8784 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008785 pw.println(" -a: include all available server state.");
8786 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788 } else {
8789 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008791 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008792
8793 long origId = Binder.clearCallingIdentity();
8794 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795 // Is the caller requesting to dump a particular piece of data?
8796 if (opti < args.length) {
8797 String cmd = args[opti];
8798 opti++;
8799 if ("activities".equals(cmd) || "a".equals(cmd)) {
8800 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008801 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008802 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008804 String[] newArgs;
8805 String name;
8806 if (opti >= args.length) {
8807 name = null;
8808 newArgs = EMPTY_STRING_ARRAY;
8809 } else {
8810 name = args[opti];
8811 opti++;
8812 newArgs = new String[args.length - opti];
8813 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8814 args.length - opti);
8815 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008816 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008817 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 String[] newArgs;
8821 String name;
8822 if (opti >= args.length) {
8823 name = null;
8824 newArgs = EMPTY_STRING_ARRAY;
8825 } else {
8826 name = args[opti];
8827 opti++;
8828 newArgs = new String[args.length - opti];
8829 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8830 args.length - opti);
8831 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008835 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008836 String[] newArgs;
8837 String name;
8838 if (opti >= args.length) {
8839 name = null;
8840 newArgs = EMPTY_STRING_ARRAY;
8841 } else {
8842 name = args[opti];
8843 opti++;
8844 newArgs = new String[args.length - opti];
8845 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8846 args.length - opti);
8847 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008849 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008850 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008851 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8852 synchronized (this) {
8853 dumpOomLocked(fd, pw, args, opti, true);
8854 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008855 } else if ("provider".equals(cmd)) {
8856 String[] newArgs;
8857 String name;
8858 if (opti >= args.length) {
8859 name = null;
8860 newArgs = EMPTY_STRING_ARRAY;
8861 } else {
8862 name = args[opti];
8863 opti++;
8864 newArgs = new String[args.length - opti];
8865 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8866 }
8867 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8868 pw.println("No providers match: " + name);
8869 pw.println("Use -h for help.");
8870 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008871 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8872 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008873 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008875 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008876 String[] newArgs;
8877 String name;
8878 if (opti >= args.length) {
8879 name = null;
8880 newArgs = EMPTY_STRING_ARRAY;
8881 } else {
8882 name = args[opti];
8883 opti++;
8884 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008885 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8886 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008887 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008888 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 pw.println("No services match: " + name);
8890 pw.println("Use -h for help.");
8891 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008892 } else if ("package".equals(cmd)) {
8893 String[] newArgs;
8894 if (opti >= args.length) {
8895 pw.println("package: no package name specified");
8896 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008897 } else {
8898 dumpPackage = args[opti];
8899 opti++;
8900 newArgs = new String[args.length - opti];
8901 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8902 args.length - opti);
8903 args = newArgs;
8904 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008905 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008906 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008907 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8908 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008909 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008911 } else {
8912 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008913 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8914 pw.println("Bad activity command, or no activities match: " + cmd);
8915 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008916 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008917 }
8918 if (!more) {
8919 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008920 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008921 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008922 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008923
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 // No piece of data specified, dump everything.
8925 synchronized (this) {
8926 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008927 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 if (needSep) {
8929 pw.println(" ");
8930 }
8931 if (dumpAll) {
8932 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008933 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008934 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 if (needSep) {
8936 pw.println(" ");
8937 }
8938 if (dumpAll) {
8939 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008940 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008941 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 if (needSep) {
8943 pw.println(" ");
8944 }
8945 if (dumpAll) {
8946 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008948 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008949 if (needSep) {
8950 pw.println(" ");
8951 }
8952 if (dumpAll) {
8953 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008956 if (needSep) {
8957 pw.println(" ");
8958 }
8959 if (dumpAll) {
8960 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008962 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008964 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008965 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008966
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008967 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008969 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8970 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008971 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8972 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008973 pw.println(" ");
8974 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8976 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008977 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008981 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008982 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008983 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008986 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008987 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008988 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008989 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8990 pw.println(" ");
8991 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008992 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008994 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008995 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008996 pw.println(" ");
8997 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008998 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008999 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08009003 if (mMainStack.mPausingActivity != null) {
9004 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009005 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009006 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009007 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009008 if (dumpAll) {
9009 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
9010 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009011 pw.println(" mDismissKeyguardOnNextActivity: "
9012 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009015 if (mRecentTasks.size() > 0) {
9016 pw.println();
9017 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018
9019 final int N = mRecentTasks.size();
9020 for (int i=0; i<N; i++) {
9021 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009022 if (dumpPackage != null) {
9023 if (tr.realActivity == null ||
9024 !dumpPackage.equals(tr.realActivity)) {
9025 continue;
9026 }
9027 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9029 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 if (dumpAll) {
9031 mRecentTasks.get(i).dump(pw, " ");
9032 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009033 }
9034 }
9035
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 if (dumpAll) {
9037 pw.println(" ");
9038 pw.println(" mCurTask: " + mCurTask);
9039 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009040
9041 return true;
9042 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009043
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009045 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 boolean needSep = false;
9047 int numPers = 0;
9048
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9050
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009051 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9053 final int NA = procs.size();
9054 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009055 ProcessRecord r = procs.valueAt(ia);
9056 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9057 continue;
9058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009059 if (!needSep) {
9060 pw.println(" All known processes:");
9061 needSep = true;
9062 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009063 pw.print(r.persistent ? " *PERS*" : " *APP*");
9064 pw.print(" UID "); pw.print(procs.keyAt(ia));
9065 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 r.dump(pw, " ");
9067 if (r.persistent) {
9068 numPers++;
9069 }
9070 }
9071 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009072 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009073
9074 if (mIsolatedProcesses.size() > 0) {
9075 if (needSep) pw.println(" ");
9076 needSep = true;
9077 pw.println(" Isolated process list (sorted by uid):");
9078 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9079 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9080 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9081 continue;
9082 }
9083 pw.println(String.format("%sIsolated #%2d: %s",
9084 " ", i, r.toString()));
9085 }
9086 }
9087
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088 if (mLruProcesses.size() > 0) {
9089 if (needSep) pw.println(" ");
9090 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009091 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009092 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009093 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 needSep = true;
9095 }
9096
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009097 if (dumpAll) {
9098 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 boolean printed = false;
9100 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9101 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9102 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9103 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009104 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 if (!printed) {
9106 if (needSep) pw.println(" ");
9107 needSep = true;
9108 pw.println(" PID mappings:");
9109 printed = true;
9110 }
9111 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9112 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 }
9114 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009115 }
9116
9117 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009118 synchronized (mPidsSelfLocked) {
9119 boolean printed = false;
9120 for (int i=0; i<mForegroundProcesses.size(); i++) {
9121 ProcessRecord r = mPidsSelfLocked.get(
9122 mForegroundProcesses.valueAt(i).pid);
9123 if (dumpPackage != null && (r == null
9124 || !dumpPackage.equals(r.info.packageName))) {
9125 continue;
9126 }
9127 if (!printed) {
9128 if (needSep) pw.println(" ");
9129 needSep = true;
9130 pw.println(" Foreground Processes:");
9131 printed = true;
9132 }
9133 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9134 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009137 }
9138
9139 if (mPersistentStartingProcesses.size() > 0) {
9140 if (needSep) pw.println(" ");
9141 needSep = true;
9142 pw.println(" Persisent processes that are starting:");
9143 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009144 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009147 if (mRemovedProcesses.size() > 0) {
9148 if (needSep) pw.println(" ");
9149 needSep = true;
9150 pw.println(" Processes that are being removed:");
9151 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009152 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009153 }
9154
9155 if (mProcessesOnHold.size() > 0) {
9156 if (needSep) pw.println(" ");
9157 needSep = true;
9158 pw.println(" Processes that are on old until the system is ready:");
9159 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009160 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009162
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009163 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009164
9165 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009166 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009167 long now = SystemClock.uptimeMillis();
9168 for (Map.Entry<String, SparseArray<Long>> procs
9169 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009170 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 SparseArray<Long> uids = procs.getValue();
9172 final int N = uids.size();
9173 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009174 int puid = uids.keyAt(i);
9175 ProcessRecord r = mProcessNames.get(pname, puid);
9176 if (dumpPackage != null && (r == null
9177 || !dumpPackage.equals(r.info.packageName))) {
9178 continue;
9179 }
9180 if (!printed) {
9181 if (needSep) pw.println(" ");
9182 needSep = true;
9183 pw.println(" Time since processes crashed:");
9184 printed = true;
9185 }
9186 pw.print(" Process "); pw.print(pname);
9187 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009189 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9190 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009191 }
9192 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009195 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009196 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009197 for (Map.Entry<String, SparseArray<Long>> procs
9198 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009199 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009200 SparseArray<Long> uids = procs.getValue();
9201 final int N = uids.size();
9202 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009203 int puid = uids.keyAt(i);
9204 ProcessRecord r = mProcessNames.get(pname, puid);
9205 if (dumpPackage != null && (r == null
9206 || !dumpPackage.equals(r.info.packageName))) {
9207 continue;
9208 }
9209 if (!printed) {
9210 if (needSep) pw.println(" ");
9211 needSep = true;
9212 pw.println(" Bad processes:");
9213 }
9214 pw.print(" Bad process "); pw.print(pname);
9215 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009216 pw.print(": crashed at time ");
9217 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218 }
9219 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009221
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009222 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009223 pw.println(" mStartedUsers:");
9224 for (int i=0; i<mStartedUsers.size(); i++) {
9225 UserStartedState uss = mStartedUsers.valueAt(i);
9226 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009227 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009228 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009229 pw.print(" mUserLru: [");
9230 for (int i=0; i<mUserLru.size(); i++) {
9231 if (i > 0) pw.print(", ");
9232 pw.print(mUserLru.get(i));
9233 }
9234 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009235 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009236 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009237 if (dumpAll) {
9238 StringBuilder sb = new StringBuilder(128);
9239 sb.append(" mPreviousProcessVisibleTime: ");
9240 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9241 pw.println(sb);
9242 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009243 if (mHeavyWeightProcess != null) {
9244 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9245 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009246 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009247 if (dumpAll) {
9248 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009249 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009250 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009251 for (Map.Entry<String, Integer> entry
9252 : mCompatModePackages.getPackages().entrySet()) {
9253 String pkg = entry.getKey();
9254 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009255 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9256 continue;
9257 }
9258 if (!printed) {
9259 pw.println(" mScreenCompatPackages:");
9260 printed = true;
9261 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009262 pw.print(" "); pw.print(pkg); pw.print(": ");
9263 pw.print(mode); pw.println();
9264 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009265 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009266 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009267 if (mSleeping || mWentToSleep || mLockScreenShown) {
9268 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9269 + " mLockScreenShown " + mLockScreenShown);
9270 }
9271 if (mShuttingDown) {
9272 pw.println(" mShuttingDown=" + mShuttingDown);
9273 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009274 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9275 || mOrigWaitForDebugger) {
9276 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9277 + " mDebugTransient=" + mDebugTransient
9278 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9279 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009280 if (mOpenGlTraceApp != null) {
9281 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9282 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009283 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9284 || mProfileFd != null) {
9285 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9286 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9287 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9288 + mAutoStopProfiler);
9289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009290 if (mAlwaysFinishActivities || mController != null) {
9291 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9292 + " mController=" + mController);
9293 }
9294 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009296 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009297 + " mProcessesReady=" + mProcessesReady
9298 + " mSystemReady=" + mSystemReady);
9299 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 + " mBooted=" + mBooted
9301 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009302 pw.print(" mLastPowerCheckRealtime=");
9303 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9304 pw.println("");
9305 pw.print(" mLastPowerCheckUptime=");
9306 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9307 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009308 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9309 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009310 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009311 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9312 + " mNumHiddenProcs=" + mNumHiddenProcs
9313 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009314 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009315 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316
9317 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 }
9319
Dianne Hackborn287952c2010-09-22 22:34:31 -07009320 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009321 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009322 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009323 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009324 long now = SystemClock.uptimeMillis();
9325 for (int i=0; i<mProcessesToGc.size(); i++) {
9326 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009327 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9328 continue;
9329 }
9330 if (!printed) {
9331 if (needSep) pw.println(" ");
9332 needSep = true;
9333 pw.println(" Processes that are waiting to GC:");
9334 printed = true;
9335 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009336 pw.print(" Process "); pw.println(proc);
9337 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9338 pw.print(", last gced=");
9339 pw.print(now-proc.lastRequestedGc);
9340 pw.print(" ms ago, last lowMem=");
9341 pw.print(now-proc.lastLowMemory);
9342 pw.println(" ms ago");
9343
9344 }
9345 }
9346 return needSep;
9347 }
9348
9349 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9350 int opti, boolean dumpAll) {
9351 boolean needSep = false;
9352
9353 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009354 if (needSep) pw.println(" ");
9355 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009356 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009357 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009358 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009359 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9360 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9361 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9362 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9363 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009364 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009365 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009366 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009367 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009368 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009369 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009370
9371 if (needSep) pw.println(" ");
9372 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009373 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009374 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009375 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009376 needSep = true;
9377 }
9378
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009379 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009380
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009381 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009382 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009383 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009384 if (mHeavyWeightProcess != null) {
9385 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9386 }
9387
9388 return true;
9389 }
9390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 /**
9392 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009393 * - no provider specified: dump all the providers
9394 * - a flattened component name that matched an existing provider was specified as the
9395 * first arg: dump that one provider
9396 * - the first arg isn't the flattened component name of an existing provider:
9397 * dump all providers whose component contains the first arg as a substring
9398 */
9399 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9400 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009401 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009402 }
9403
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009404 static class ItemMatcher {
9405 ArrayList<ComponentName> components;
9406 ArrayList<String> strings;
9407 ArrayList<Integer> objects;
9408 boolean all;
9409
9410 ItemMatcher() {
9411 all = true;
9412 }
9413
9414 void build(String name) {
9415 ComponentName componentName = ComponentName.unflattenFromString(name);
9416 if (componentName != null) {
9417 if (components == null) {
9418 components = new ArrayList<ComponentName>();
9419 }
9420 components.add(componentName);
9421 all = false;
9422 } else {
9423 int objectId = 0;
9424 // Not a '/' separated full component name; maybe an object ID?
9425 try {
9426 objectId = Integer.parseInt(name, 16);
9427 if (objects == null) {
9428 objects = new ArrayList<Integer>();
9429 }
9430 objects.add(objectId);
9431 all = false;
9432 } catch (RuntimeException e) {
9433 // Not an integer; just do string match.
9434 if (strings == null) {
9435 strings = new ArrayList<String>();
9436 }
9437 strings.add(name);
9438 all = false;
9439 }
9440 }
9441 }
9442
9443 int build(String[] args, int opti) {
9444 for (; opti<args.length; opti++) {
9445 String name = args[opti];
9446 if ("--".equals(name)) {
9447 return opti+1;
9448 }
9449 build(name);
9450 }
9451 return opti;
9452 }
9453
9454 boolean match(Object object, ComponentName comp) {
9455 if (all) {
9456 return true;
9457 }
9458 if (components != null) {
9459 for (int i=0; i<components.size(); i++) {
9460 if (components.get(i).equals(comp)) {
9461 return true;
9462 }
9463 }
9464 }
9465 if (objects != null) {
9466 for (int i=0; i<objects.size(); i++) {
9467 if (System.identityHashCode(object) == objects.get(i)) {
9468 return true;
9469 }
9470 }
9471 }
9472 if (strings != null) {
9473 String flat = comp.flattenToString();
9474 for (int i=0; i<strings.size(); i++) {
9475 if (flat.contains(strings.get(i))) {
9476 return true;
9477 }
9478 }
9479 }
9480 return false;
9481 }
9482 }
9483
Dianne Hackborn625ac272010-09-17 18:29:22 -07009484 /**
9485 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009486 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009487 * - the cmd arg isn't the flattened component name of an existing activity:
9488 * dump all activity whose component contains the cmd as a substring
9489 * - A hex number of the ActivityRecord object instance.
9490 */
9491 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9492 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009493 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009494
9495 if ("all".equals(name)) {
9496 synchronized (this) {
9497 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009498 activities.add(r1);
9499 }
9500 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009501 } else if ("top".equals(name)) {
9502 synchronized (this) {
9503 final int N = mMainStack.mHistory.size();
9504 if (N > 0) {
9505 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9506 }
9507 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009508 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009509 ItemMatcher matcher = new ItemMatcher();
9510 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009511
9512 synchronized (this) {
9513 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009514 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009515 activities.add(r1);
9516 }
9517 }
9518 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009519 }
9520
9521 if (activities.size() <= 0) {
9522 return false;
9523 }
9524
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 String[] newArgs = new String[args.length - opti];
9526 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9527
Dianne Hackborn30d71892010-12-11 10:37:55 -08009528 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009530 for (int i=activities.size()-1; i>=0; i--) {
9531 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009532 if (needSep) {
9533 pw.println();
9534 }
9535 needSep = true;
9536 synchronized (this) {
9537 if (lastTask != r.task) {
9538 lastTask = r.task;
9539 pw.print("TASK "); pw.print(lastTask.affinity);
9540 pw.print(" id="); pw.println(lastTask.taskId);
9541 if (dumpAll) {
9542 lastTask.dump(pw, " ");
9543 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009544 }
9545 }
9546 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009547 }
9548 return true;
9549 }
9550
9551 /**
9552 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9553 * there is a thread associated with the activity.
9554 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009555 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009556 final ActivityRecord r, String[] args, boolean dumpAll) {
9557 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009558 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009559 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9560 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9561 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009562 if (r.app != null) pw.println(r.app.pid);
9563 else pw.println("(not running)");
9564 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009565 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009566 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009567 }
9568 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009569 // flush anything that is already in the PrintWriter since the thread is going
9570 // to write to the file descriptor directly
9571 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009572 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 TransferPipe tp = new TransferPipe();
9574 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009575 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9576 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009577 tp.go(fd);
9578 } finally {
9579 tp.kill();
9580 }
9581 } catch (IOException e) {
9582 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009583 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009585 }
9586 }
9587 }
9588
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009589 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009590 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009591 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009592 boolean onlyHistory = false;
9593
9594 if ("history".equals(dumpPackage)) {
9595 onlyHistory = true;
9596 dumpPackage = null;
9597 }
9598
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009599 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009600 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 Iterator it = mRegisteredReceivers.values().iterator();
9604 while (it.hasNext()) {
9605 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009606 if (dumpPackage != null && (r.app == null ||
9607 !dumpPackage.equals(r.app.info.packageName))) {
9608 continue;
9609 }
9610 if (!printed) {
9611 pw.println(" Registered Receivers:");
9612 needSep = true;
9613 printed = true;
9614 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009615 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009616 r.dump(pw, " ");
9617 }
9618 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009619
9620 if (mReceiverResolver.dump(pw, needSep ?
9621 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9622 " ", dumpPackage, false)) {
9623 needSep = true;
9624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009625 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009626
9627 for (BroadcastQueue q : mBroadcastQueues) {
9628 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009631 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009632
Dianne Hackborn786b4402012-08-27 15:14:02 -07009633 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009634 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9635 if (needSep) {
9636 pw.println();
9637 }
9638 needSep = true;
9639 pw.print(" Sticky broadcasts for user ");
9640 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9641 StringBuilder sb = new StringBuilder(128);
9642 for (Map.Entry<String, ArrayList<Intent>> ent
9643 : mStickyBroadcasts.valueAt(user).entrySet()) {
9644 pw.print(" * Sticky action "); pw.print(ent.getKey());
9645 if (dumpAll) {
9646 pw.println(":");
9647 ArrayList<Intent> intents = ent.getValue();
9648 final int N = intents.size();
9649 for (int i=0; i<N; i++) {
9650 sb.setLength(0);
9651 sb.append(" Intent: ");
9652 intents.get(i).toShortString(sb, false, true, false, false);
9653 pw.println(sb.toString());
9654 Bundle bundle = intents.get(i).getExtras();
9655 if (bundle != null) {
9656 pw.print(" ");
9657 pw.println(bundle.toString());
9658 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009659 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009660 } else {
9661 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009662 }
9663 }
9664 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009665 }
9666
Dianne Hackborn786b4402012-08-27 15:14:02 -07009667 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009668 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009669 for (BroadcastQueue queue : mBroadcastQueues) {
9670 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9671 + queue.mBroadcastsScheduled);
9672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009673 pw.println(" mHandler:");
9674 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009675 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009676 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009677
9678 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009679 }
9680
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009682 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009683 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009685 ItemMatcher matcher = new ItemMatcher();
9686 matcher.build(args, opti);
9687
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009688 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009689
9690 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009691
9692 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009693 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009694 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009695 ContentProviderRecord r = mLaunchingProviders.get(i);
9696 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9697 continue;
9698 }
9699 if (!printed) {
9700 if (needSep) pw.println(" ");
9701 needSep = true;
9702 pw.println(" Launching content providers:");
9703 printed = true;
9704 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009705 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009706 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009707 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009708 }
9709
9710 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009711 if (needSep) pw.println();
9712 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009713 pw.println("Granted Uri Permissions:");
9714 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9715 int uid = mGrantedUriPermissions.keyAt(i);
9716 HashMap<Uri, UriPermission> perms
9717 = mGrantedUriPermissions.valueAt(i);
9718 pw.print(" * UID "); pw.print(uid);
9719 pw.println(" holds:");
9720 for (UriPermission perm : perms.values()) {
9721 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009722 if (dumpAll) {
9723 perm.dump(pw, " ");
9724 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009725 }
9726 }
9727 needSep = true;
9728 }
9729
9730 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 }
9732
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009733 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009734 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009735 boolean needSep = false;
9736
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009737 if (mIntentSenderRecords.size() > 0) {
9738 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 Iterator<WeakReference<PendingIntentRecord>> it
9740 = mIntentSenderRecords.values().iterator();
9741 while (it.hasNext()) {
9742 WeakReference<PendingIntentRecord> ref = it.next();
9743 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009744 if (dumpPackage != null && (rec == null
9745 || !dumpPackage.equals(rec.key.packageName))) {
9746 continue;
9747 }
9748 if (!printed) {
9749 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9750 printed = true;
9751 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009752 needSep = true;
9753 if (rec != null) {
9754 pw.print(" * "); pw.println(rec);
9755 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009758 } else {
9759 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009760 }
9761 }
9762 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009763
9764 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009765 }
9766
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009767 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009768 String prefix, String label, boolean complete, boolean brief, boolean client,
9769 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009770 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009771 boolean needNL = false;
9772 final String innerPrefix = prefix + " ";
9773 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009774 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009775 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009776 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9777 continue;
9778 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009779 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009780 if (needNL) {
9781 pw.println(" ");
9782 needNL = false;
9783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009784 if (lastTask != r.task) {
9785 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009786 pw.print(prefix);
9787 pw.print(full ? "* " : " ");
9788 pw.println(lastTask);
9789 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009790 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009791 } else if (complete) {
9792 // Complete + brief == give a summary. Isn't that obvious?!?
9793 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009794 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009795 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009796 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009798 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009799 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9800 pw.print(" #"); pw.print(i); pw.print(": ");
9801 pw.println(r);
9802 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009803 r.dump(pw, innerPrefix);
9804 } else if (complete) {
9805 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009806 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009807 if (r.app != null) {
9808 pw.print(innerPrefix); pw.println(r.app);
9809 }
9810 }
9811 if (client && r.app != null && r.app.thread != null) {
9812 // flush anything that is already in the PrintWriter since the thread is going
9813 // to write to the file descriptor directly
9814 pw.flush();
9815 try {
9816 TransferPipe tp = new TransferPipe();
9817 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009818 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9819 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009820 // Short timeout, since blocking here can
9821 // deadlock with the application.
9822 tp.go(fd, 2000);
9823 } finally {
9824 tp.kill();
9825 }
9826 } catch (IOException e) {
9827 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9828 } catch (RemoteException e) {
9829 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9830 }
9831 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009833 }
9834 }
9835
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009836 private static String buildOomTag(String prefix, String space, int val, int base) {
9837 if (val == base) {
9838 if (space == null) return prefix;
9839 return prefix + " ";
9840 }
9841 return prefix + "+" + Integer.toString(val-base);
9842 }
9843
9844 private static final int dumpProcessList(PrintWriter pw,
9845 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009846 String prefix, String normalLabel, String persistentLabel,
9847 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009848 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009849 final int N = list.size()-1;
9850 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009851 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009852 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9853 continue;
9854 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009855 pw.println(String.format("%s%s #%2d: %s",
9856 prefix, (r.persistent ? persistentLabel : normalLabel),
9857 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009858 if (r.persistent) {
9859 numPers++;
9860 }
9861 }
9862 return numPers;
9863 }
9864
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009865 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009866 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009867 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009868 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009869
Dianne Hackborn905577f2011-09-07 18:31:28 -07009870 ArrayList<Pair<ProcessRecord, Integer>> list
9871 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9872 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009873 ProcessRecord r = origList.get(i);
9874 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9875 continue;
9876 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009877 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9878 }
9879
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009880 if (list.size() <= 0) {
9881 return false;
9882 }
9883
Dianne Hackborn905577f2011-09-07 18:31:28 -07009884 Comparator<Pair<ProcessRecord, Integer>> comparator
9885 = new Comparator<Pair<ProcessRecord, Integer>>() {
9886 @Override
9887 public int compare(Pair<ProcessRecord, Integer> object1,
9888 Pair<ProcessRecord, Integer> object2) {
9889 if (object1.first.setAdj != object2.first.setAdj) {
9890 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9891 }
9892 if (object1.second.intValue() != object2.second.intValue()) {
9893 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9894 }
9895 return 0;
9896 }
9897 };
9898
9899 Collections.sort(list, comparator);
9900
Dianne Hackborn287952c2010-09-22 22:34:31 -07009901 final long curRealtime = SystemClock.elapsedRealtime();
9902 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9903 final long curUptime = SystemClock.uptimeMillis();
9904 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9905
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009906 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009907 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009908 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009909 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009910 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009911 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9912 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009913 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9914 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009915 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9916 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009917 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9918 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009919 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009920 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009921 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9922 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9923 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9924 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9925 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9926 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9927 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9928 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009929 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9930 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009931 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9932 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009933 } else {
9934 oomAdj = Integer.toString(r.setAdj);
9935 }
9936 String schedGroup;
9937 switch (r.setSchedGroup) {
9938 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9939 schedGroup = "B";
9940 break;
9941 case Process.THREAD_GROUP_DEFAULT:
9942 schedGroup = "F";
9943 break;
9944 default:
9945 schedGroup = Integer.toString(r.setSchedGroup);
9946 break;
9947 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009948 String foreground;
9949 if (r.foregroundActivities) {
9950 foreground = "A";
9951 } else if (r.foregroundServices) {
9952 foreground = "S";
9953 } else {
9954 foreground = " ";
9955 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009956 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009957 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009958 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9959 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009960 if (r.adjSource != null || r.adjTarget != null) {
9961 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009962 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009963 if (r.adjTarget instanceof ComponentName) {
9964 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9965 } else if (r.adjTarget != null) {
9966 pw.print(r.adjTarget.toString());
9967 } else {
9968 pw.print("{null}");
9969 }
9970 pw.print("<=");
9971 if (r.adjSource instanceof ProcessRecord) {
9972 pw.print("Proc{");
9973 pw.print(((ProcessRecord)r.adjSource).toShortString());
9974 pw.println("}");
9975 } else if (r.adjSource != null) {
9976 pw.println(r.adjSource.toString());
9977 } else {
9978 pw.println("{null}");
9979 }
9980 }
9981 if (inclDetails) {
9982 pw.print(prefix);
9983 pw.print(" ");
9984 pw.print("oom: max="); pw.print(r.maxAdj);
9985 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009986 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009987 pw.print(" curRaw="); pw.print(r.curRawAdj);
9988 pw.print(" setRaw="); pw.print(r.setRawAdj);
9989 pw.print(" cur="); pw.print(r.curAdj);
9990 pw.print(" set="); pw.println(r.setAdj);
9991 pw.print(prefix);
9992 pw.print(" ");
9993 pw.print("keeping="); pw.print(r.keeping);
9994 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009995 pw.print(" empty="); pw.print(r.empty);
9996 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009997
9998 if (!r.keeping) {
9999 if (r.lastWakeTime != 0) {
10000 long wtime;
10001 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10002 synchronized (stats) {
10003 wtime = stats.getProcessWakeTime(r.info.uid,
10004 r.pid, curRealtime);
10005 }
10006 long timeUsed = wtime - r.lastWakeTime;
10007 pw.print(prefix);
10008 pw.print(" ");
10009 pw.print("keep awake over ");
10010 TimeUtils.formatDuration(realtimeSince, pw);
10011 pw.print(" used ");
10012 TimeUtils.formatDuration(timeUsed, pw);
10013 pw.print(" (");
10014 pw.print((timeUsed*100)/realtimeSince);
10015 pw.println("%)");
10016 }
10017 if (r.lastCpuTime != 0) {
10018 long timeUsed = r.curCpuTime - r.lastCpuTime;
10019 pw.print(prefix);
10020 pw.print(" ");
10021 pw.print("run cpu over ");
10022 TimeUtils.formatDuration(uptimeSince, pw);
10023 pw.print(" used ");
10024 TimeUtils.formatDuration(timeUsed, pw);
10025 pw.print(" (");
10026 pw.print((timeUsed*100)/uptimeSince);
10027 pw.println("%)");
10028 }
10029 }
10030 }
10031 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010032 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010033 }
10034
Dianne Hackbornb437e092011-08-05 17:50:29 -070010035 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010036 ArrayList<ProcessRecord> procs;
10037 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010038 if (args != null && args.length > start
10039 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010040 procs = new ArrayList<ProcessRecord>();
10041 int pid = -1;
10042 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010043 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010044 } catch (NumberFormatException e) {
10045
10046 }
10047 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10048 ProcessRecord proc = mLruProcesses.get(i);
10049 if (proc.pid == pid) {
10050 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010051 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010052 procs.add(proc);
10053 }
10054 }
10055 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 return null;
10058 }
10059 } else {
10060 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10061 }
10062 }
10063 return procs;
10064 }
10065
10066 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10067 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010068 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010069 if (procs == null) {
10070 return;
10071 }
10072
10073 long uptime = SystemClock.uptimeMillis();
10074 long realtime = SystemClock.elapsedRealtime();
10075 pw.println("Applications Graphics Acceleration Info:");
10076 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10077
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10079 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010080 if (r.thread != null) {
10081 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10082 pw.flush();
10083 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010084 TransferPipe tp = new TransferPipe();
10085 try {
10086 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10087 tp.go(fd);
10088 } finally {
10089 tp.kill();
10090 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010091 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010092 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010093 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010094 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010095 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010096 pw.flush();
10097 }
10098 }
10099 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010100 }
10101
Jeff Brown6754ba22011-12-14 20:20:01 -080010102 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10103 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10104 if (procs == null) {
10105 return;
10106 }
10107
10108 pw.println("Applications Database Info:");
10109
10110 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10111 ProcessRecord r = procs.get(i);
10112 if (r.thread != null) {
10113 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10114 pw.flush();
10115 try {
10116 TransferPipe tp = new TransferPipe();
10117 try {
10118 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10119 tp.go(fd);
10120 } finally {
10121 tp.kill();
10122 }
10123 } catch (IOException e) {
10124 pw.println("Failure while dumping the app: " + r);
10125 pw.flush();
10126 } catch (RemoteException e) {
10127 pw.println("Got a RemoteException while dumping the app " + r);
10128 pw.flush();
10129 }
10130 }
10131 }
10132 }
10133
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010134 final static class MemItem {
10135 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010136 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010137 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010138 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010139 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010140
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010141 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010142 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010143 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010144 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010145 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010146 }
10147 }
10148
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010149 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150 boolean sort) {
10151 if (sort) {
10152 Collections.sort(items, new Comparator<MemItem>() {
10153 @Override
10154 public int compare(MemItem lhs, MemItem rhs) {
10155 if (lhs.pss < rhs.pss) {
10156 return 1;
10157 } else if (lhs.pss > rhs.pss) {
10158 return -1;
10159 }
10160 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010161 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010162 });
10163 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010164
10165 for (int i=0; i<items.size(); i++) {
10166 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010167 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010168 if (mi.subitems != null) {
10169 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10170 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 }
10172 }
10173
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010174 // These are in KB.
10175 static final long[] DUMP_MEM_BUCKETS = new long[] {
10176 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10177 120*1024, 160*1024, 200*1024,
10178 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10179 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10180 };
10181
Dianne Hackborn672342c2011-11-29 11:29:02 -080010182 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10183 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010184 int start = label.lastIndexOf('.');
10185 if (start >= 0) start++;
10186 else start = 0;
10187 int end = label.length();
10188 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10189 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10190 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10191 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010192 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010193 out.append(label, start, end);
10194 return;
10195 }
10196 }
10197 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010198 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010199 out.append(label, start, end);
10200 }
10201
10202 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10203 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10204 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10205 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10206 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10207 };
10208 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10209 "System", "Persistent", "Foreground",
10210 "Visible", "Perceptible", "Heavy Weight",
10211 "Backup", "A Services", "Home", "Previous",
10212 "B Services", "Background"
10213 };
10214
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010215 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010216 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010217 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010219 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010220
10221 int opti = 0;
10222 while (opti < args.length) {
10223 String opt = args[opti];
10224 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10225 break;
10226 }
10227 opti++;
10228 if ("-a".equals(opt)) {
10229 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010230 } else if ("--oom".equals(opt)) {
10231 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010232 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010233 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010234 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010235 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010236 pw.println("If [process] is specified it can be the name or ");
10237 pw.println("pid of a specific process to dump.");
10238 return;
10239 } else {
10240 pw.println("Unknown argument: " + opt + "; use -h for help");
10241 }
10242 }
10243
10244 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010245 if (procs == null) {
10246 return;
10247 }
10248
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010249 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010250 long uptime = SystemClock.uptimeMillis();
10251 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010252
10253 if (procs.size() == 1 || isCheckinRequest) {
10254 dumpAll = true;
10255 }
10256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010257 if (isCheckinRequest) {
10258 // short checkin version
10259 pw.println(uptime + "," + realtime);
10260 pw.flush();
10261 } else {
10262 pw.println("Applications Memory Usage (kB):");
10263 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10264 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010265
Dianne Hackbornb437e092011-08-05 17:50:29 -070010266 String[] innerArgs = new String[args.length-opti];
10267 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10268
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010269 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10270 long nativePss=0, dalvikPss=0, otherPss=0;
10271 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10272
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010273 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10274 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10275 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010276
10277 long totalPss = 0;
10278
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010279 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10280 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010281 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010282 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010283 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10284 pw.flush();
10285 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010286 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010287 if (dumpAll) {
10288 try {
10289 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10290 } catch (RemoteException e) {
10291 if (!isCheckinRequest) {
10292 pw.println("Got RemoteException!");
10293 pw.flush();
10294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010296 } else {
10297 mi = new Debug.MemoryInfo();
10298 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010299 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010300
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010301 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010302 long myTotalPss = mi.getTotalPss();
10303 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010304 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010305 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010306 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010307
10308 nativePss += mi.nativePss;
10309 dalvikPss += mi.dalvikPss;
10310 otherPss += mi.otherPss;
10311 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10312 long mem = mi.getOtherPss(j);
10313 miscPss[j] += mem;
10314 otherPss -= mem;
10315 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316
10317 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010318 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10319 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010321 if (oomProcs[oomIndex] == null) {
10322 oomProcs[oomIndex] = new ArrayList<MemItem>();
10323 }
10324 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010325 break;
10326 }
10327 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010329 }
10330 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010331
10332 if (!isCheckinRequest && procs.size() > 1) {
10333 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10334
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010335 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10336 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10337 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010338 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010339 String label = Debug.MemoryInfo.getOtherLabel(j);
10340 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010341 }
10342
Dianne Hackbornb437e092011-08-05 17:50:29 -070010343 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10344 for (int j=0; j<oomPss.length; j++) {
10345 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010346 String label = DUMP_MEM_OOM_LABEL[j];
10347 MemItem item = new MemItem(label, label, oomPss[j],
10348 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010349 item.subitems = oomProcs[j];
10350 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010351 }
10352 }
10353
Dianne Hackborn672342c2011-11-29 11:29:02 -080010354 if (outTag != null || outStack != null) {
10355 if (outTag != null) {
10356 appendMemBucket(outTag, totalPss, "total", false);
10357 }
10358 if (outStack != null) {
10359 appendMemBucket(outStack, totalPss, "total", true);
10360 }
10361 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010362 for (int i=0; i<oomMems.size(); i++) {
10363 MemItem miCat = oomMems.get(i);
10364 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10365 continue;
10366 }
10367 if (miCat.id < ProcessList.SERVICE_ADJ
10368 || miCat.id == ProcessList.HOME_APP_ADJ
10369 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010370 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10371 outTag.append(" / ");
10372 }
10373 if (outStack != null) {
10374 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10375 if (firstLine) {
10376 outStack.append(":");
10377 firstLine = false;
10378 }
10379 outStack.append("\n\t at ");
10380 } else {
10381 outStack.append("$");
10382 }
10383 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010384 for (int j=0; j<miCat.subitems.size(); j++) {
10385 MemItem mi = miCat.subitems.get(j);
10386 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010387 if (outTag != null) {
10388 outTag.append(" ");
10389 }
10390 if (outStack != null) {
10391 outStack.append("$");
10392 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010393 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010394 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10395 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10396 }
10397 if (outStack != null) {
10398 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10399 }
10400 }
10401 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10402 outStack.append("(");
10403 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10404 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10405 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10406 outStack.append(":");
10407 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10408 }
10409 }
10410 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010411 }
10412 }
10413 }
10414 }
10415
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010416 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010417 pw.println();
10418 pw.println("Total PSS by process:");
10419 dumpMemItems(pw, " ", procMems, true);
10420 pw.println();
10421 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010422 pw.println("Total PSS by OOM adjustment:");
10423 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010424 if (!oomOnly) {
10425 PrintWriter out = categoryPw != null ? categoryPw : pw;
10426 out.println();
10427 out.println("Total PSS by category:");
10428 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010429 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010430 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010431 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010432 final int[] SINGLE_LONG_FORMAT = new int[] {
10433 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10434 };
10435 long[] longOut = new long[1];
10436 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10437 SINGLE_LONG_FORMAT, null, longOut, null);
10438 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10439 longOut[0] = 0;
10440 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10441 SINGLE_LONG_FORMAT, null, longOut, null);
10442 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10443 longOut[0] = 0;
10444 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10445 SINGLE_LONG_FORMAT, null, longOut, null);
10446 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10447 longOut[0] = 0;
10448 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10449 SINGLE_LONG_FORMAT, null, longOut, null);
10450 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10451 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10452 pw.print(shared); pw.println(" kB");
10453 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10454 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010456 }
10457
10458 /**
10459 * Searches array of arguments for the specified string
10460 * @param args array of argument strings
10461 * @param value value to search for
10462 * @return true if the value is contained in the array
10463 */
10464 private static boolean scanArgs(String[] args, String value) {
10465 if (args != null) {
10466 for (String arg : args) {
10467 if (value.equals(arg)) {
10468 return true;
10469 }
10470 }
10471 }
10472 return false;
10473 }
10474
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010475 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10476 ContentProviderRecord cpr, boolean always) {
10477 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10478
10479 if (!inLaunching || always) {
10480 synchronized (cpr) {
10481 cpr.launchingApp = null;
10482 cpr.notifyAll();
10483 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010484 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010485 String names[] = cpr.info.authority.split(";");
10486 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010487 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488 }
10489 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010490
10491 for (int i=0; i<cpr.connections.size(); i++) {
10492 ContentProviderConnection conn = cpr.connections.get(i);
10493 if (conn.waiting) {
10494 // If this connection is waiting for the provider, then we don't
10495 // need to mess with its process unless we are always removing
10496 // or for some reason the provider is not currently launching.
10497 if (inLaunching && !always) {
10498 continue;
10499 }
10500 }
10501 ProcessRecord capp = conn.client;
10502 conn.dead = true;
10503 if (conn.stableCount > 0) {
10504 if (!capp.persistent && capp.thread != null
10505 && capp.pid != 0
10506 && capp.pid != MY_PID) {
10507 Slog.i(TAG, "Kill " + capp.processName
10508 + " (pid " + capp.pid + "): provider " + cpr.info.name
10509 + " in dying process " + (proc != null ? proc.processName : "??"));
10510 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10511 capp.processName, capp.setAdj, "dying provider "
10512 + cpr.name.toShortString());
10513 Process.killProcessQuiet(capp.pid);
10514 }
10515 } else if (capp.thread != null && conn.provider.provider != null) {
10516 try {
10517 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10518 } catch (RemoteException e) {
10519 }
10520 // In the protocol here, we don't expect the client to correctly
10521 // clean up this connection, we'll just remove it.
10522 cpr.connections.remove(i);
10523 conn.client.conProviders.remove(conn);
10524 }
10525 }
10526
10527 if (inLaunching && always) {
10528 mLaunchingProviders.remove(cpr);
10529 }
10530 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010531 }
10532
10533 /**
10534 * Main code for cleaning up a process when it has gone away. This is
10535 * called both as a result of the process dying, or directly when stopping
10536 * a process when running in single process mode.
10537 */
10538 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010539 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010541 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 }
10543
Dianne Hackborn36124872009-10-08 16:22:03 -070010544 mProcessesToGc.remove(app);
10545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010546 // Dismiss any open dialogs.
10547 if (app.crashDialog != null) {
10548 app.crashDialog.dismiss();
10549 app.crashDialog = null;
10550 }
10551 if (app.anrDialog != null) {
10552 app.anrDialog.dismiss();
10553 app.anrDialog = null;
10554 }
10555 if (app.waitDialog != null) {
10556 app.waitDialog.dismiss();
10557 app.waitDialog = null;
10558 }
10559
10560 app.crashing = false;
10561 app.notResponding = false;
10562
10563 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010564 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 app.thread = null;
10566 app.forcingToForeground = null;
10567 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010568 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010569 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010570 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010572 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010573
10574 boolean restart = false;
10575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 // Remove published content providers.
10577 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010578 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010580 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010581
10582 final boolean always = app.bad || !allowRestart;
10583 if (removeDyingProviderLocked(app, cpr, always) || always) {
10584 // We left the provider in the launching list, need to
10585 // restart it.
10586 restart = true;
10587 }
10588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010590 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010591 }
10592 app.pubProviders.clear();
10593 }
10594
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010595 // Take care of any launching providers waiting for this process.
10596 if (checkAppInLaunchingProvidersLocked(app, false)) {
10597 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010598 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 // Unregister from connected content providers.
10601 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010602 for (int i=0; i<app.conProviders.size(); i++) {
10603 ContentProviderConnection conn = app.conProviders.get(i);
10604 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 }
10606 app.conProviders.clear();
10607 }
10608
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010609 // At this point there may be remaining entries in mLaunchingProviders
10610 // where we were the only one waiting, so they are no longer of use.
10611 // Look for these and clean up if found.
10612 // XXX Commented out for now. Trying to figure out a way to reproduce
10613 // the actual situation to identify what is actually going on.
10614 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010615 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010616 ContentProviderRecord cpr = (ContentProviderRecord)
10617 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010618 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010619 synchronized (cpr) {
10620 cpr.launchingApp = null;
10621 cpr.notifyAll();
10622 }
10623 }
10624 }
10625 }
10626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010627 skipCurrentReceiverLocked(app);
10628
10629 // Unregister any receivers.
10630 if (app.receivers.size() > 0) {
10631 Iterator<ReceiverList> it = app.receivers.iterator();
10632 while (it.hasNext()) {
10633 removeReceiverLocked(it.next());
10634 }
10635 app.receivers.clear();
10636 }
10637
Christopher Tate181fafa2009-05-14 11:12:14 -070010638 // If the app is undergoing backup, tell the backup manager about it
10639 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010640 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010641 try {
10642 IBackupManager bm = IBackupManager.Stub.asInterface(
10643 ServiceManager.getService(Context.BACKUP_SERVICE));
10644 bm.agentDisconnected(app.info.packageName);
10645 } catch (RemoteException e) {
10646 // can't happen; backup manager is local
10647 }
10648 }
10649
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010650 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10651 ProcessChangeItem item = mPendingProcessChanges.get(i);
10652 if (item.pid == app.pid) {
10653 mPendingProcessChanges.remove(i);
10654 mAvailProcessChanges.add(item);
10655 }
10656 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010657 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010659 // If the caller is restarting this app, then leave it in its
10660 // current lists and let the caller take care of it.
10661 if (restarting) {
10662 return;
10663 }
10664
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010665 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010666 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010668 mProcessNames.remove(app.processName, app.uid);
10669 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010670 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010671 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10672 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010673 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 } else if (!app.removed) {
10676 // This app is persistent, so we need to keep its record around.
10677 // If it is not already on the pending app list, add it there
10678 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10680 mPersistentStartingProcesses.add(app);
10681 restart = true;
10682 }
10683 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010684 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10685 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 mProcessesOnHold.remove(app);
10687
The Android Open Source Project4df24232009-03-05 14:34:35 -080010688 if (app == mHomeProcess) {
10689 mHomeProcess = null;
10690 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010691 if (app == mPreviousProcess) {
10692 mPreviousProcess = null;
10693 }
10694
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010695 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 // We have components that still need to be running in the
10697 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010698 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 startProcessLocked(app, "restart", app.processName);
10700 } else if (app.pid > 0 && app.pid != MY_PID) {
10701 // Goodbye!
10702 synchronized (mPidsSelfLocked) {
10703 mPidsSelfLocked.remove(app.pid);
10704 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10705 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010706 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 }
10708 }
10709
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010710 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10711 // Look through the content providers we are waiting to have launched,
10712 // and if any run in this process then either schedule a restart of
10713 // the process or kill the client waiting for it if this process has
10714 // gone bad.
10715 int NL = mLaunchingProviders.size();
10716 boolean restart = false;
10717 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010718 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010719 if (cpr.launchingApp == app) {
10720 if (!alwaysBad && !app.bad) {
10721 restart = true;
10722 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010723 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010724 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010725 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010726 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010727 }
10728 }
10729 }
10730 return restart;
10731 }
10732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 // =========================================================
10734 // SERVICES
10735 // =========================================================
10736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010737 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10738 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010739 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010741 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 }
10743 }
10744
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010745 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010746 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010747 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010748 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010749 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010750 }
10751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010753 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010754 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010755 // Refuse possible leaked file descriptors
10756 if (service != null && service.hasFileDescriptors() == true) {
10757 throw new IllegalArgumentException("File descriptors passed in Intent");
10758 }
10759
Amith Yamasani742a6712011-05-04 14:49:28 -070010760 if (DEBUG_SERVICE)
10761 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 synchronized(this) {
10763 final int callingPid = Binder.getCallingPid();
10764 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010765 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010767 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010768 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 Binder.restoreCallingIdentity(origId);
10770 return res;
10771 }
10772 }
10773
10774 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010775 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010776 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010777 if (DEBUG_SERVICE)
10778 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
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(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010781 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 Binder.restoreCallingIdentity(origId);
10783 return res;
10784 }
10785 }
10786
10787 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010788 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010789 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010790 // Refuse possible leaked file descriptors
10791 if (service != null && service.hasFileDescriptors() == true) {
10792 throw new IllegalArgumentException("File descriptors passed in Intent");
10793 }
10794
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010795 checkValidCaller(Binder.getCallingUid(), userId);
10796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010798 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 }
10801
10802 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010803 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 // Refuse possible leaked file descriptors
10805 if (service != null && service.hasFileDescriptors() == true) {
10806 throw new IllegalArgumentException("File descriptors passed in Intent");
10807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010808 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010809 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 }
10812
10813 public boolean stopServiceToken(ComponentName className, IBinder token,
10814 int startId) {
10815 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010816 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010818 }
10819
10820 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010821 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010823 mServices.setServiceForegroundLocked(className, token, id, notification,
10824 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 }
10826 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010827
Dianne Hackborn41203752012-08-31 14:05:51 -070010828 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10829 boolean requireFull, String name, String callerPackage) {
10830 synchronized(this) {
10831 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10832 requireFull, name, callerPackage);
10833 }
10834 }
10835
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010836 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10837 boolean requireFull, String name, String callerPackage) {
10838 final int callingUserId = UserHandle.getUserId(callingUid);
10839 if (callingUserId != userId) {
10840 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10841 if ((requireFull || checkComponentPermission(
10842 android.Manifest.permission.INTERACT_ACROSS_USERS,
10843 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10844 && checkComponentPermission(
10845 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10846 callingPid, callingUid, -1, true)
10847 != PackageManager.PERMISSION_GRANTED) {
10848 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10849 // In this case, they would like to just execute as their
10850 // owner user instead of failing.
10851 userId = callingUserId;
10852 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010853 StringBuilder builder = new StringBuilder(128);
10854 builder.append("Permission Denial: ");
10855 builder.append(name);
10856 if (callerPackage != null) {
10857 builder.append(" from ");
10858 builder.append(callerPackage);
10859 }
10860 builder.append(" asks to run as user ");
10861 builder.append(userId);
10862 builder.append(" but is calling from user ");
10863 builder.append(UserHandle.getUserId(callingUid));
10864 builder.append("; this requires ");
10865 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10866 if (!requireFull) {
Dianne Hackborn74ee8652012-09-07 18:33:18 -070010867 builder.append(" or ");
Dianne Hackborn41203752012-08-31 14:05:51 -070010868 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10869 }
10870 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010871 Slog.w(TAG, msg);
10872 throw new SecurityException(msg);
10873 }
10874 }
10875 }
10876 if (userId == UserHandle.USER_CURRENT
10877 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10878 userId = mCurrentUserId;
10879 }
10880 if (!allowAll && userId < 0) {
10881 throw new IllegalArgumentException(
10882 "Call does not support special user #" + userId);
10883 }
10884 }
10885 return userId;
10886 }
10887
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010888 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10889 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010890 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010891 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010892 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10893 if (ActivityManager.checkUidPermission(
10894 android.Manifest.permission.INTERACT_ACROSS_USERS,
10895 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10896 ComponentName comp = new ComponentName(aInfo.packageName, className);
10897 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10898 + " requests FLAG_SINGLE_USER, but app does not hold "
10899 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10900 Slog.w(TAG, msg);
10901 throw new SecurityException(msg);
10902 }
10903 result = true;
10904 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010905 } else if (componentProcessName == aInfo.packageName) {
10906 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10907 } else if ("system".equals(componentProcessName)) {
10908 result = true;
10909 }
10910 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010911 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10912 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010913 }
10914 return result;
10915 }
10916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010917 public int bindService(IApplicationThread caller, IBinder token,
10918 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010919 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010920 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010921 // Refuse possible leaked file descriptors
10922 if (service != null && service.hasFileDescriptors() == true) {
10923 throw new IllegalArgumentException("File descriptors passed in Intent");
10924 }
10925
10926 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010927 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10928 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010929 }
10930 }
10931
10932 public boolean unbindService(IServiceConnection connection) {
10933 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010934 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 }
10937
10938 public void publishService(IBinder token, Intent intent, IBinder service) {
10939 // Refuse possible leaked file descriptors
10940 if (intent != null && intent.hasFileDescriptors() == true) {
10941 throw new IllegalArgumentException("File descriptors passed in Intent");
10942 }
10943
10944 synchronized(this) {
10945 if (!(token instanceof ServiceRecord)) {
10946 throw new IllegalArgumentException("Invalid service token");
10947 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010948 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010949 }
10950 }
10951
10952 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10953 // Refuse possible leaked file descriptors
10954 if (intent != null && intent.hasFileDescriptors() == true) {
10955 throw new IllegalArgumentException("File descriptors passed in Intent");
10956 }
10957
10958 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010959 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 }
10961 }
10962
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010963 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010964 synchronized(this) {
10965 if (!(token instanceof ServiceRecord)) {
10966 throw new IllegalArgumentException("Invalid service token");
10967 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010968 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 }
10971
10972 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010973 // BACKUP AND RESTORE
10974 // =========================================================
10975
10976 // Cause the target app to be launched if necessary and its backup agent
10977 // instantiated. The backup agent will invoke backupAgentCreated() on the
10978 // activity manager to announce its creation.
10979 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010980 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010981 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10982
10983 synchronized(this) {
10984 // !!! TODO: currently no check here that we're already bound
10985 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10986 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10987 synchronized (stats) {
10988 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10989 }
10990
Dianne Hackborne7f97212011-02-24 14:40:20 -080010991 // Backup agent is now in use, its package can't be stopped.
10992 try {
10993 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010994 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010995 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010996 } catch (IllegalArgumentException e) {
10997 Slog.w(TAG, "Failed trying to unstop package "
10998 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010999 }
11000
Christopher Tate181fafa2009-05-14 11:12:14 -070011001 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070011002 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
11003 ? new ComponentName(app.packageName, app.backupAgentName)
11004 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070011005 // startProcessLocked() returns existing proc's record if it's already running
11006 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011007 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070011008 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011009 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070011010 return false;
11011 }
11012
11013 r.app = proc;
11014 mBackupTarget = r;
11015 mBackupAppName = app.packageName;
11016
Christopher Tate6fa95972009-06-05 18:43:55 -070011017 // Try not to kill the process during backup
11018 updateOomAdjLocked(proc);
11019
Christopher Tate181fafa2009-05-14 11:12:14 -070011020 // If the process is already attached, schedule the creation of the backup agent now.
11021 // If it is not yet live, this will be done when it attaches to the framework.
11022 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011023 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011024 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011025 proc.thread.scheduleCreateBackupAgent(app,
11026 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011027 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011028 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011029 }
11030 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011031 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011032 }
11033 // Invariants: at this point, the target app process exists and the application
11034 // is either already running or in the process of coming up. mBackupTarget and
11035 // mBackupAppName describe the app, so that when it binds back to the AM we
11036 // know that it's scheduled for a backup-agent operation.
11037 }
11038
11039 return true;
11040 }
11041
11042 // A backup agent has just come up
11043 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011044 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011045 + " = " + agent);
11046
11047 synchronized(this) {
11048 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011049 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011050 return;
11051 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011052 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011053
Dianne Hackborn06740692010-09-22 22:46:21 -070011054 long oldIdent = Binder.clearCallingIdentity();
11055 try {
11056 IBackupManager bm = IBackupManager.Stub.asInterface(
11057 ServiceManager.getService(Context.BACKUP_SERVICE));
11058 bm.agentConnected(agentPackageName, agent);
11059 } catch (RemoteException e) {
11060 // can't happen; the backup manager service is local
11061 } catch (Exception e) {
11062 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11063 e.printStackTrace();
11064 } finally {
11065 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011066 }
11067 }
11068
11069 // done with this agent
11070 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011071 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011072 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011073 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011074 return;
11075 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011076
11077 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011078 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011079 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011080 return;
11081 }
11082
Christopher Tate181fafa2009-05-14 11:12:14 -070011083 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011084 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011085 return;
11086 }
11087
Christopher Tate6fa95972009-06-05 18:43:55 -070011088 ProcessRecord proc = mBackupTarget.app;
11089 mBackupTarget = null;
11090 mBackupAppName = null;
11091
11092 // Not backing this app up any more; reset its OOM adjustment
11093 updateOomAdjLocked(proc);
11094
Christopher Tatec7b31e32009-06-10 15:49:30 -070011095 // If the app crashed during backup, 'thread' will be null here
11096 if (proc.thread != null) {
11097 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011098 proc.thread.scheduleDestroyBackupAgent(appInfo,
11099 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011100 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011101 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011102 e.printStackTrace();
11103 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011104 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011105 }
11106 }
11107 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011108 // BROADCASTS
11109 // =========================================================
11110
Josh Bartel7f208742010-02-25 11:01:44 -060011111 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011112 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011114 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11115 if (stickies == null) {
11116 return cur;
11117 }
11118 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011119 if (list == null) {
11120 return cur;
11121 }
11122 int N = list.size();
11123 for (int i=0; i<N; i++) {
11124 Intent intent = list.get(i);
11125 if (filter.match(resolver, intent, true, TAG) >= 0) {
11126 if (cur == null) {
11127 cur = new ArrayList<Intent>();
11128 }
11129 cur.add(intent);
11130 }
11131 }
11132 return cur;
11133 }
11134
Christopher Tatef46723b2012-01-26 14:19:24 -080011135 boolean isPendingBroadcastProcessLocked(int pid) {
11136 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11137 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011139
Christopher Tatef46723b2012-01-26 14:19:24 -080011140 void skipPendingBroadcastLocked(int pid) {
11141 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11142 for (BroadcastQueue queue : mBroadcastQueues) {
11143 queue.skipPendingBroadcastLocked(pid);
11144 }
11145 }
11146
11147 // The app just attached; send any pending broadcasts that it should receive
11148 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11149 boolean didSomething = false;
11150 for (BroadcastQueue queue : mBroadcastQueues) {
11151 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011153 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011154 }
11155
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011156 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011157 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011158 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011159 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011160 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 synchronized(this) {
11162 ProcessRecord callerApp = null;
11163 if (caller != null) {
11164 callerApp = getRecordForAppLocked(caller);
11165 if (callerApp == null) {
11166 throw new SecurityException(
11167 "Unable to find app for caller " + caller
11168 + " (pid=" + Binder.getCallingPid()
11169 + ") when registering receiver " + receiver);
11170 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011171 if (callerApp.info.uid != Process.SYSTEM_UID &&
11172 !callerApp.pkgList.contains(callerPackage)) {
11173 throw new SecurityException("Given caller package " + callerPackage
11174 + " is not running in process " + callerApp);
11175 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011176 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011177 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011178 } else {
11179 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011180 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011181 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011182 }
11183
Dianne Hackborn20e80982012-08-31 19:00:44 -070011184 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11185 true, true, "registerReceiver", callerPackage);
11186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011187 List allSticky = null;
11188
11189 // Look for any matching sticky broadcasts...
11190 Iterator actions = filter.actionsIterator();
11191 if (actions != null) {
11192 while (actions.hasNext()) {
11193 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011194 allSticky = getStickiesLocked(action, filter, allSticky,
11195 UserHandle.USER_ALL);
11196 allSticky = getStickiesLocked(action, filter, allSticky,
11197 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 }
11199 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011200 allSticky = getStickiesLocked(null, filter, allSticky,
11201 UserHandle.USER_ALL);
11202 allSticky = getStickiesLocked(null, filter, allSticky,
11203 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204 }
11205
11206 // The first sticky in the list is returned directly back to
11207 // the client.
11208 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11209
Joe Onorato8a9b2202010-02-26 18:56:32 -080011210 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011211 + ": " + sticky);
11212
11213 if (receiver == null) {
11214 return sticky;
11215 }
11216
11217 ReceiverList rl
11218 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11219 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011220 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11221 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 if (rl.app != null) {
11223 rl.app.receivers.add(rl);
11224 } else {
11225 try {
11226 receiver.asBinder().linkToDeath(rl, 0);
11227 } catch (RemoteException e) {
11228 return sticky;
11229 }
11230 rl.linkedToDeath = true;
11231 }
11232 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011233 } else if (rl.uid != callingUid) {
11234 throw new IllegalArgumentException(
11235 "Receiver requested to register for uid " + callingUid
11236 + " was previously registered for uid " + rl.uid);
11237 } else if (rl.pid != callingPid) {
11238 throw new IllegalArgumentException(
11239 "Receiver requested to register for pid " + callingPid
11240 + " was previously registered for pid " + rl.pid);
11241 } else if (rl.userId != userId) {
11242 throw new IllegalArgumentException(
11243 "Receiver requested to register for user " + userId
11244 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011245 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011246 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011247 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 rl.add(bf);
11249 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011250 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 }
11252 mReceiverResolver.addFilter(bf);
11253
11254 // Enqueue broadcasts for all existing stickies that match
11255 // this filter.
11256 if (allSticky != null) {
11257 ArrayList receivers = new ArrayList();
11258 receivers.add(bf);
11259
11260 int N = allSticky.size();
11261 for (int i=0; i<N; i++) {
11262 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011263 BroadcastQueue queue = broadcastQueueForIntent(intent);
11264 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011266 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011267 queue.enqueueParallelBroadcastLocked(r);
11268 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 }
11270 }
11271
11272 return sticky;
11273 }
11274 }
11275
11276 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011277 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278
Christopher Tatef46723b2012-01-26 14:19:24 -080011279 final long origId = Binder.clearCallingIdentity();
11280 try {
11281 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282
Christopher Tatef46723b2012-01-26 14:19:24 -080011283 synchronized(this) {
11284 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011286 if (rl != null) {
11287 if (rl.curBroadcast != null) {
11288 BroadcastRecord r = rl.curBroadcast;
11289 final boolean doNext = finishReceiverLocked(
11290 receiver.asBinder(), r.resultCode, r.resultData,
11291 r.resultExtras, r.resultAbort, true);
11292 if (doNext) {
11293 doTrim = true;
11294 r.queue.processNextBroadcast(false);
11295 }
11296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297
Christopher Tatef46723b2012-01-26 14:19:24 -080011298 if (rl.app != null) {
11299 rl.app.receivers.remove(rl);
11300 }
11301 removeReceiverLocked(rl);
11302 if (rl.linkedToDeath) {
11303 rl.linkedToDeath = false;
11304 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 }
11307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308
Christopher Tatef46723b2012-01-26 14:19:24 -080011309 // If we actually concluded any broadcasts, we might now be able
11310 // to trim the recipients' apps from our working set
11311 if (doTrim) {
11312 trimApplications();
11313 return;
11314 }
11315
11316 } finally {
11317 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 }
11320
11321 void removeReceiverLocked(ReceiverList rl) {
11322 mRegisteredReceivers.remove(rl.receiver.asBinder());
11323 int N = rl.size();
11324 for (int i=0; i<N; i++) {
11325 mReceiverResolver.removeFilter(rl.get(i));
11326 }
11327 }
11328
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011329 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011330 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11331 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011332 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011333 try {
11334 r.thread.dispatchPackageBroadcast(cmd, packages);
11335 } catch (RemoteException ex) {
11336 }
11337 }
11338 }
11339 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011340
11341 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11342 int[] users) {
11343 List<ResolveInfo> receivers = null;
11344 try {
11345 HashSet<ComponentName> singleUserReceivers = null;
11346 boolean scannedFirstReceivers = false;
11347 for (int user : users) {
11348 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11349 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11350 if (newReceivers != null && newReceivers.size() == 0) {
11351 newReceivers = null;
11352 }
11353 if (receivers == null) {
11354 receivers = newReceivers;
11355 } else if (newReceivers != null) {
11356 // We need to concatenate the additional receivers
11357 // found with what we have do far. This would be easy,
11358 // but we also need to de-dup any receivers that are
11359 // singleUser.
11360 if (!scannedFirstReceivers) {
11361 // Collect any single user receivers we had already retrieved.
11362 scannedFirstReceivers = true;
11363 for (int i=0; i<receivers.size(); i++) {
11364 ResolveInfo ri = receivers.get(i);
11365 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11366 ComponentName cn = new ComponentName(
11367 ri.activityInfo.packageName, ri.activityInfo.name);
11368 if (singleUserReceivers == null) {
11369 singleUserReceivers = new HashSet<ComponentName>();
11370 }
11371 singleUserReceivers.add(cn);
11372 }
11373 }
11374 }
11375 // Add the new results to the existing results, tracking
11376 // and de-dupping single user receivers.
11377 for (int i=0; i<newReceivers.size(); i++) {
11378 ResolveInfo ri = receivers.get(i);
11379 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11380 ComponentName cn = new ComponentName(
11381 ri.activityInfo.packageName, ri.activityInfo.name);
11382 if (singleUserReceivers == null) {
11383 singleUserReceivers = new HashSet<ComponentName>();
11384 }
11385 if (!singleUserReceivers.contains(cn)) {
11386 singleUserReceivers.add(cn);
11387 receivers.add(ri);
11388 }
11389 } else {
11390 receivers.add(ri);
11391 }
11392 }
11393 }
11394 }
11395 } catch (RemoteException ex) {
11396 // pm is in same process, this will never happen.
11397 }
11398 return receivers;
11399 }
11400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011401 private final int broadcastIntentLocked(ProcessRecord callerApp,
11402 String callerPackage, Intent intent, String resolvedType,
11403 IIntentReceiver resultTo, int resultCode, String resultData,
11404 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011405 boolean ordered, boolean sticky, int callingPid, int callingUid,
11406 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 intent = new Intent(intent);
11408
Dianne Hackborne7f97212011-02-24 14:40:20 -080011409 // By default broadcasts do not go to stopped apps.
11410 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11411
Joe Onorato8a9b2202010-02-26 18:56:32 -080011412 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011413 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011414 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011415 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011416 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011417 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011418
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011419 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11420 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011421
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011422 // Make sure that the user who is receiving this broadcast is started
11423 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011424 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011425 Slog.w(TAG, "Skipping broadcast of " + intent
11426 + ": user " + userId + " is stopped");
11427 return ActivityManager.BROADCAST_SUCCESS;
11428 }
11429
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011430 /*
11431 * Prevent non-system code (defined here to be non-persistent
11432 * processes) from sending protected broadcasts.
11433 */
11434 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11435 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11436 callingUid == 0) {
11437 // Always okay.
11438 } else if (callerApp == null || !callerApp.persistent) {
11439 try {
11440 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11441 intent.getAction())) {
11442 String msg = "Permission Denial: not allowed to send broadcast "
11443 + intent.getAction() + " from pid="
11444 + callingPid + ", uid=" + callingUid;
11445 Slog.w(TAG, msg);
11446 throw new SecurityException(msg);
11447 }
11448 } catch (RemoteException e) {
11449 Slog.w(TAG, "Remote exception", e);
11450 return ActivityManager.BROADCAST_SUCCESS;
11451 }
11452 }
11453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 // Handle special intents: if this broadcast is from the package
11455 // manager about a package being removed, we need to remove all of
11456 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011457 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011459 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11460 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011461 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011462 || uidRemoved) {
11463 if (checkComponentPermission(
11464 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011465 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011466 == PackageManager.PERMISSION_GRANTED) {
11467 if (uidRemoved) {
11468 final Bundle intentExtras = intent.getExtras();
11469 final int uid = intentExtras != null
11470 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11471 if (uid >= 0) {
11472 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11473 synchronized (bs) {
11474 bs.removeUidStatsLocked(uid);
11475 }
11476 }
11477 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011478 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011479 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011480 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011481 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11482 if (list != null && (list.length > 0)) {
11483 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011484 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011485 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011486 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011487 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011488 }
11489 } else {
11490 Uri data = intent.getData();
11491 String ssp;
11492 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11493 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11494 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011495 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11496 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011497 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011498 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011499 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011500 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011502 }
11503 }
11504 }
11505 } else {
11506 String msg = "Permission Denial: " + intent.getAction()
11507 + " broadcast from " + callerPackage + " (pid=" + callingPid
11508 + ", uid=" + callingUid + ")"
11509 + " requires "
11510 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011511 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 throw new SecurityException(msg);
11513 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011514
11515 // Special case for adding a package: by default turn on compatibility
11516 // mode.
11517 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011518 Uri data = intent.getData();
11519 String ssp;
11520 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11521 mCompatModePackages.handlePackageAddedLocked(ssp,
11522 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 }
11525
11526 /*
11527 * If this is the time zone changed action, queue up a message that will reset the timezone
11528 * of all currently running processes. This message will get queued up before the broadcast
11529 * happens.
11530 */
11531 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11532 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11533 }
11534
Robert Greenwalt03595d02010-11-02 14:08:23 -070011535 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11536 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11537 }
11538
Robert Greenwalt434203a2010-10-11 16:00:27 -070011539 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11540 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11541 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11542 }
11543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 // Add to the sticky list if requested.
11545 if (sticky) {
11546 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11547 callingPid, callingUid)
11548 != PackageManager.PERMISSION_GRANTED) {
11549 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11550 + callingPid + ", uid=" + callingUid
11551 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011552 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 throw new SecurityException(msg);
11554 }
11555 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011556 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011558 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011559 }
11560 if (intent.getComponent() != null) {
11561 throw new SecurityException(
11562 "Sticky broadcasts can't target a specific component");
11563 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011564 // We use userId directly here, since the "all" target is maintained
11565 // as a separate set of sticky broadcasts.
11566 if (userId != UserHandle.USER_ALL) {
11567 // But first, if this is not a broadcast to all users, then
11568 // make sure it doesn't conflict with an existing broadcast to
11569 // all users.
11570 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11571 UserHandle.USER_ALL);
11572 if (stickies != null) {
11573 ArrayList<Intent> list = stickies.get(intent.getAction());
11574 if (list != null) {
11575 int N = list.size();
11576 int i;
11577 for (i=0; i<N; i++) {
11578 if (intent.filterEquals(list.get(i))) {
11579 throw new IllegalArgumentException(
11580 "Sticky broadcast " + intent + " for user "
11581 + userId + " conflicts with existing global broadcast");
11582 }
11583 }
11584 }
11585 }
11586 }
11587 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11588 if (stickies == null) {
11589 stickies = new HashMap<String, ArrayList<Intent>>();
11590 mStickyBroadcasts.put(userId, stickies);
11591 }
11592 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011593 if (list == null) {
11594 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011595 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011596 }
11597 int N = list.size();
11598 int i;
11599 for (i=0; i<N; i++) {
11600 if (intent.filterEquals(list.get(i))) {
11601 // This sticky already exists, replace it.
11602 list.set(i, new Intent(intent));
11603 break;
11604 }
11605 }
11606 if (i >= N) {
11607 list.add(new Intent(intent));
11608 }
11609 }
11610
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011611 int[] users;
11612 if (userId == UserHandle.USER_ALL) {
11613 // Caller wants broadcast to go to all started users.
11614 users = new int[mStartedUsers.size()];
11615 for (int i=0; i<mStartedUsers.size(); i++) {
11616 users[i] = mStartedUsers.keyAt(i);
11617 }
11618 } else {
11619 // Caller wants broadcast to go to one specific user.
11620 users = new int[] {userId};
11621 }
11622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 // Figure out who all will receive this broadcast.
11624 List receivers = null;
11625 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011626 // Need to resolve the intent to interested receivers...
11627 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11628 == 0) {
11629 receivers = collectReceiverComponents(intent, resolvedType, users);
11630 }
11631 if (intent.getComponent() == null) {
11632 registeredReceivers = mReceiverResolver.queryIntent(intent,
11633 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011634 }
11635
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011636 final boolean replacePending =
11637 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11638
Joe Onorato8a9b2202010-02-26 18:56:32 -080011639 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011640 + " replacePending=" + replacePending);
11641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11643 if (!ordered && NR > 0) {
11644 // If we are not serializing this broadcast, then send the
11645 // registered receivers separately so they don't wait for the
11646 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011647 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11648 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011649 callerPackage, callingPid, callingUid, requiredPermission,
11650 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011651 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011652 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011653 TAG, "Enqueueing parallel broadcast " + r);
11654 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011655 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011656 queue.enqueueParallelBroadcastLocked(r);
11657 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 registeredReceivers = null;
11660 NR = 0;
11661 }
11662
11663 // Merge into one list.
11664 int ir = 0;
11665 if (receivers != null) {
11666 // A special case for PACKAGE_ADDED: do not allow the package
11667 // being added to see this broadcast. This prevents them from
11668 // using this as a back door to get run as soon as they are
11669 // installed. Maybe in the future we want to have a special install
11670 // broadcast or such for apps, but we'd like to deliberately make
11671 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011672 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011673 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11674 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11675 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011676 Uri data = intent.getData();
11677 if (data != null) {
11678 String pkgName = data.getSchemeSpecificPart();
11679 if (pkgName != null) {
11680 skipPackages = new String[] { pkgName };
11681 }
11682 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011683 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011684 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011685 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011686 if (skipPackages != null && (skipPackages.length > 0)) {
11687 for (String skipPackage : skipPackages) {
11688 if (skipPackage != null) {
11689 int NT = receivers.size();
11690 for (int it=0; it<NT; it++) {
11691 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11692 if (curt.activityInfo.packageName.equals(skipPackage)) {
11693 receivers.remove(it);
11694 it--;
11695 NT--;
11696 }
11697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 }
11699 }
11700 }
11701
11702 int NT = receivers != null ? receivers.size() : 0;
11703 int it = 0;
11704 ResolveInfo curt = null;
11705 BroadcastFilter curr = null;
11706 while (it < NT && ir < NR) {
11707 if (curt == null) {
11708 curt = (ResolveInfo)receivers.get(it);
11709 }
11710 if (curr == null) {
11711 curr = registeredReceivers.get(ir);
11712 }
11713 if (curr.getPriority() >= curt.priority) {
11714 // Insert this broadcast record into the final list.
11715 receivers.add(it, curr);
11716 ir++;
11717 curr = null;
11718 it++;
11719 NT++;
11720 } else {
11721 // Skip to the next ResolveInfo in the final list.
11722 it++;
11723 curt = null;
11724 }
11725 }
11726 }
11727 while (ir < NR) {
11728 if (receivers == null) {
11729 receivers = new ArrayList();
11730 }
11731 receivers.add(registeredReceivers.get(ir));
11732 ir++;
11733 }
11734
11735 if ((receivers != null && receivers.size() > 0)
11736 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011737 BroadcastQueue queue = broadcastQueueForIntent(intent);
11738 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011740 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011741 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011742 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011743 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011744 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 if (DEBUG_BROADCAST) {
11746 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011747 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011748 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011749 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011750 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011751 queue.enqueueOrderedBroadcastLocked(r);
11752 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011754 }
11755
Dianne Hackborna4972e92012-03-14 10:38:05 -070011756 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 }
11758
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011759 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011760 // Refuse possible leaked file descriptors
11761 if (intent != null && intent.hasFileDescriptors() == true) {
11762 throw new IllegalArgumentException("File descriptors passed in Intent");
11763 }
11764
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011765 int flags = intent.getFlags();
11766
11767 if (!mProcessesReady) {
11768 // if the caller really truly claims to know what they're doing, go
11769 // ahead and allow the broadcast without launching any receivers
11770 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11771 intent = new Intent(intent);
11772 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11773 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11774 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11775 + " before boot completion");
11776 throw new IllegalStateException("Cannot broadcast before boot completed");
11777 }
11778 }
11779
11780 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11781 throw new IllegalArgumentException(
11782 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11783 }
11784
11785 return intent;
11786 }
11787
11788 public final int broadcastIntent(IApplicationThread caller,
11789 Intent intent, String resolvedType, IIntentReceiver resultTo,
11790 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011791 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011792 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011793 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011794 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11797 final int callingPid = Binder.getCallingPid();
11798 final int callingUid = Binder.getCallingUid();
11799 final long origId = Binder.clearCallingIdentity();
11800 int res = broadcastIntentLocked(callerApp,
11801 callerApp != null ? callerApp.info.packageName : null,
11802 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011803 resultCode, resultData, map, requiredPermission, serialized, sticky,
11804 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011805 Binder.restoreCallingIdentity(origId);
11806 return res;
11807 }
11808 }
11809
11810 int broadcastIntentInPackage(String packageName, int uid,
11811 Intent intent, String resolvedType, IIntentReceiver resultTo,
11812 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011813 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011815 intent = verifyBroadcastLocked(intent);
11816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 final long origId = Binder.clearCallingIdentity();
11818 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11819 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011820 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 Binder.restoreCallingIdentity(origId);
11822 return res;
11823 }
11824 }
11825
Amith Yamasani742a6712011-05-04 14:49:28 -070011826 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 // Refuse possible leaked file descriptors
11828 if (intent != null && intent.hasFileDescriptors() == true) {
11829 throw new IllegalArgumentException("File descriptors passed in Intent");
11830 }
11831
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011832 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11833 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011835 synchronized(this) {
11836 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11837 != PackageManager.PERMISSION_GRANTED) {
11838 String msg = "Permission Denial: unbroadcastIntent() from pid="
11839 + Binder.getCallingPid()
11840 + ", uid=" + Binder.getCallingUid()
11841 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011842 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 throw new SecurityException(msg);
11844 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011845 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11846 if (stickies != null) {
11847 ArrayList<Intent> list = stickies.get(intent.getAction());
11848 if (list != null) {
11849 int N = list.size();
11850 int i;
11851 for (i=0; i<N; i++) {
11852 if (intent.filterEquals(list.get(i))) {
11853 list.remove(i);
11854 break;
11855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011857 if (list.size() <= 0) {
11858 stickies.remove(intent.getAction());
11859 }
11860 }
11861 if (stickies.size() <= 0) {
11862 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 }
11864 }
11865 }
11866 }
11867
11868 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11869 String resultData, Bundle resultExtras, boolean resultAbort,
11870 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011871 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11872 if (r == null) {
11873 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 return false;
11875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876
Christopher Tatef46723b2012-01-26 14:19:24 -080011877 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11878 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011879 }
11880
11881 public void finishReceiver(IBinder who, int resultCode, String resultData,
11882 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011883 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884
11885 // Refuse possible leaked file descriptors
11886 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11887 throw new IllegalArgumentException("File descriptors passed in Bundle");
11888 }
11889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011890 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011891 try {
11892 boolean doNext = false;
11893 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894
Christopher Tatef46723b2012-01-26 14:19:24 -080011895 synchronized(this) {
11896 r = broadcastRecordForReceiverLocked(who);
11897 if (r != null) {
11898 doNext = r.queue.finishReceiverLocked(r, resultCode,
11899 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011901 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011902
Christopher Tatef46723b2012-01-26 14:19:24 -080011903 if (doNext) {
11904 r.queue.processNextBroadcast(false);
11905 }
11906 trimApplications();
11907 } finally {
11908 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 // =========================================================
11913 // INSTRUMENTATION
11914 // =========================================================
11915
11916 public boolean startInstrumentation(ComponentName className,
11917 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011918 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011919 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011920 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11921 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 // Refuse possible leaked file descriptors
11923 if (arguments != null && arguments.hasFileDescriptors()) {
11924 throw new IllegalArgumentException("File descriptors passed in Bundle");
11925 }
11926
11927 synchronized(this) {
11928 InstrumentationInfo ii = null;
11929 ApplicationInfo ai = null;
11930 try {
11931 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011932 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011933 ai = AppGlobals.getPackageManager().getApplicationInfo(
11934 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011935 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011936 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 }
11938 if (ii == null) {
11939 reportStartInstrumentationFailure(watcher, className,
11940 "Unable to find instrumentation info for: " + className);
11941 return false;
11942 }
11943 if (ai == null) {
11944 reportStartInstrumentationFailure(watcher, className,
11945 "Unable to find instrumentation target package: " + ii.targetPackage);
11946 return false;
11947 }
11948
11949 int match = mContext.getPackageManager().checkSignatures(
11950 ii.targetPackage, ii.packageName);
11951 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11952 String msg = "Permission Denial: starting instrumentation "
11953 + className + " from pid="
11954 + Binder.getCallingPid()
11955 + ", uid=" + Binder.getCallingPid()
11956 + " not allowed because package " + ii.packageName
11957 + " does not have a signature matching the target "
11958 + ii.targetPackage;
11959 reportStartInstrumentationFailure(watcher, className, msg);
11960 throw new SecurityException(msg);
11961 }
11962
11963 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011964 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011965 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011966 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011967 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011968 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 app.instrumentationProfileFile = profileFile;
11970 app.instrumentationArguments = arguments;
11971 app.instrumentationWatcher = watcher;
11972 app.instrumentationResultClass = className;
11973 Binder.restoreCallingIdentity(origId);
11974 }
11975
11976 return true;
11977 }
11978
11979 /**
11980 * Report errors that occur while attempting to start Instrumentation. Always writes the
11981 * error to the logs, but if somebody is watching, send the report there too. This enables
11982 * the "am" command to report errors with more information.
11983 *
11984 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11985 * @param cn The component name of the instrumentation.
11986 * @param report The error report.
11987 */
11988 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11989 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011990 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 try {
11992 if (watcher != null) {
11993 Bundle results = new Bundle();
11994 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11995 results.putString("Error", report);
11996 watcher.instrumentationStatus(cn, -1, results);
11997 }
11998 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011999 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 }
12001 }
12002
12003 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12004 if (app.instrumentationWatcher != null) {
12005 try {
12006 // NOTE: IInstrumentationWatcher *must* be oneway here
12007 app.instrumentationWatcher.instrumentationFinished(
12008 app.instrumentationClass,
12009 resultCode,
12010 results);
12011 } catch (RemoteException e) {
12012 }
12013 }
12014 app.instrumentationWatcher = null;
12015 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012016 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 app.instrumentationProfileFile = null;
12018 app.instrumentationArguments = null;
12019
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012020 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 }
12022
12023 public void finishInstrumentation(IApplicationThread target,
12024 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012025 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012026 // Refuse possible leaked file descriptors
12027 if (results != null && results.hasFileDescriptors()) {
12028 throw new IllegalArgumentException("File descriptors passed in Intent");
12029 }
12030
12031 synchronized(this) {
12032 ProcessRecord app = getRecordForAppLocked(target);
12033 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012034 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 return;
12036 }
12037 final long origId = Binder.clearCallingIdentity();
12038 finishInstrumentationLocked(app, resultCode, results);
12039 Binder.restoreCallingIdentity(origId);
12040 }
12041 }
12042
12043 // =========================================================
12044 // CONFIGURATION
12045 // =========================================================
12046
12047 public ConfigurationInfo getDeviceConfigurationInfo() {
12048 ConfigurationInfo config = new ConfigurationInfo();
12049 synchronized (this) {
12050 config.reqTouchScreen = mConfiguration.touchscreen;
12051 config.reqKeyboardType = mConfiguration.keyboard;
12052 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012053 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12054 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12056 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012057 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12058 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12060 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012061 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012062 }
12063 return config;
12064 }
12065
12066 public Configuration getConfiguration() {
12067 Configuration ci;
12068 synchronized(this) {
12069 ci = new Configuration(mConfiguration);
12070 }
12071 return ci;
12072 }
12073
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012074 public void updatePersistentConfiguration(Configuration values) {
12075 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12076 "updateConfiguration()");
12077 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12078 "updateConfiguration()");
12079 if (values == null) {
12080 throw new NullPointerException("Configuration must not be null");
12081 }
12082
12083 synchronized(this) {
12084 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012085 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012086 Binder.restoreCallingIdentity(origId);
12087 }
12088 }
12089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 public void updateConfiguration(Configuration values) {
12091 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12092 "updateConfiguration()");
12093
12094 synchronized(this) {
12095 if (values == null && mWindowManager != null) {
12096 // sentinel: fetch the current configuration from the window manager
12097 values = mWindowManager.computeNewConfiguration();
12098 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012099
12100 if (mWindowManager != null) {
12101 mProcessList.applyDisplaySize(mWindowManager);
12102 }
12103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012104 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012105 if (values != null) {
12106 Settings.System.clearConfiguration(values);
12107 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012108 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109 Binder.restoreCallingIdentity(origId);
12110 }
12111 }
12112
12113 /**
12114 * Do either or both things: (1) change the current configuration, and (2)
12115 * make sure the given activity is running with the (now) current
12116 * configuration. Returns true if the activity has been left running, or
12117 * false if <var>starting</var> is being destroyed to match the new
12118 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012119 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012121 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012122 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012123 // do nothing if we are headless
12124 if (mHeadless) return true;
12125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126 int changes = 0;
12127
12128 boolean kept = true;
12129
12130 if (values != null) {
12131 Configuration newConfig = new Configuration(mConfiguration);
12132 changes = newConfig.updateFrom(values);
12133 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012134 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012135 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012136 }
12137
Doug Zongker2bec3d42009-12-04 12:52:44 -080012138 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012139
Dianne Hackborn813075a62011-11-14 17:45:19 -080012140 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012141 saveLocaleLocked(values.locale,
12142 !values.locale.equals(mConfiguration.locale),
12143 values.userSetLocale);
12144 }
12145
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012146 mConfigurationSeq++;
12147 if (mConfigurationSeq <= 0) {
12148 mConfigurationSeq = 1;
12149 }
12150 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012152 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012153
12154 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012155
12156 // TODO: If our config changes, should we auto dismiss any currently
12157 // showing dialogs?
12158 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012159
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012160 AttributeCache ac = AttributeCache.instance();
12161 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012162 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012164
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012165 // Make sure all resources in our process are updated
12166 // right now, so that anyone who is going to retrieve
12167 // resource values after we return will be sure to get
12168 // the new ones. This is especially important during
12169 // boot, where the first config change needs to guarantee
12170 // all resources have that config before following boot
12171 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012172 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012173
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012174 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012175 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012176 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012177 mHandler.sendMessage(msg);
12178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012179
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012180 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12181 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012182 try {
12183 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012184 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012185 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012186 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012187 }
12188 } catch (Exception e) {
12189 }
12190 }
12191 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012192 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12193 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012195 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012196 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12197 broadcastIntentLocked(null, null,
12198 new Intent(Intent.ACTION_LOCALE_CHANGED),
12199 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012200 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 }
12203 }
12204
12205 if (changes != 0 && starting == null) {
12206 // If the configuration changed, and the caller is not already
12207 // in the process of starting an activity, then find the top
12208 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012209 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 }
12211
12212 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012213 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012214 // And we need to make sure at this point that all other activities
12215 // are made visible with the correct configuration.
12216 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 }
12218
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012219 if (values != null && mWindowManager != null) {
12220 mWindowManager.setNewConfiguration(mConfiguration);
12221 }
12222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 return kept;
12224 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012225
12226 /**
12227 * Decide based on the configuration whether we should shouw the ANR,
12228 * crash, etc dialogs. The idea is that if there is no affordnace to
12229 * press the on-screen buttons, we shouldn't show the dialog.
12230 *
12231 * A thought: SystemUI might also want to get told about this, the Power
12232 * dialog / global actions also might want different behaviors.
12233 */
12234 private static final boolean shouldShowDialogs(Configuration config) {
12235 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12236 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12237 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012238
12239 /**
12240 * Save the locale. You must be inside a synchronized (this) block.
12241 */
12242 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12243 if(isDiff) {
12244 SystemProperties.set("user.language", l.getLanguage());
12245 SystemProperties.set("user.region", l.getCountry());
12246 }
12247
12248 if(isPersist) {
12249 SystemProperties.set("persist.sys.language", l.getLanguage());
12250 SystemProperties.set("persist.sys.country", l.getCountry());
12251 SystemProperties.set("persist.sys.localevar", l.getVariant());
12252 }
12253 }
12254
Adam Powelldd8fab22012-03-22 17:47:27 -070012255 @Override
12256 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12257 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012258 return srec != null && srec.task.affinity != null &&
12259 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012260 }
12261
12262 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12263 Intent resultData) {
12264 ComponentName dest = destIntent.getComponent();
12265
12266 synchronized (this) {
12267 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012268 if (srec == null) {
12269 return false;
12270 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012271 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12272 final int start = history.indexOf(srec);
12273 if (start < 0) {
12274 // Current activity is not in history stack; do nothing.
12275 return false;
12276 }
12277 int finishTo = start - 1;
12278 ActivityRecord parent = null;
12279 boolean foundParentInTask = false;
12280 if (dest != null) {
12281 TaskRecord tr = srec.task;
12282 for (int i = start - 1; i >= 0; i--) {
12283 ActivityRecord r = history.get(i);
12284 if (tr != r.task) {
12285 // Couldn't find parent in the same task; stop at the one above this.
12286 // (Root of current task; in-app "home" behavior)
12287 // Always at least finish the current activity.
12288 finishTo = Math.min(start - 1, i + 1);
12289 parent = history.get(finishTo);
12290 break;
12291 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12292 r.info.name.equals(dest.getClassName())) {
12293 finishTo = i;
12294 parent = r;
12295 foundParentInTask = true;
12296 break;
12297 }
12298 }
12299 }
12300
12301 if (mController != null) {
12302 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12303 if (next != null) {
12304 // ask watcher if this is allowed
12305 boolean resumeOK = true;
12306 try {
12307 resumeOK = mController.activityResuming(next.packageName);
12308 } catch (RemoteException e) {
12309 mController = null;
12310 }
12311
12312 if (!resumeOK) {
12313 return false;
12314 }
12315 }
12316 }
12317 final long origId = Binder.clearCallingIdentity();
12318 for (int i = start; i > finishTo; i--) {
12319 ActivityRecord r = history.get(i);
12320 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012321 "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012322 // Only return the supplied result for the first activity finished
12323 resultCode = Activity.RESULT_CANCELED;
12324 resultData = null;
12325 }
12326
12327 if (parent != null && foundParentInTask) {
12328 final int parentLaunchMode = parent.info.launchMode;
12329 final int destIntentFlags = destIntent.getFlags();
12330 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12331 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12332 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12333 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012334 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012335 } else {
12336 try {
12337 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012338 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012339 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12340 null, aInfo, parent.appToken, null,
12341 0, -1, parent.launchedFromUid, 0, null, true, null);
12342 foundParentInTask = res == ActivityManager.START_SUCCESS;
12343 } catch (RemoteException e) {
12344 foundParentInTask = false;
12345 }
12346 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -070012347 resultData, "navigate-up", true);
Adam Powelldd8fab22012-03-22 17:47:27 -070012348 }
12349 }
12350 Binder.restoreCallingIdentity(origId);
12351 return foundParentInTask;
12352 }
12353 }
12354
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012355 public int getLaunchedFromUid(IBinder activityToken) {
12356 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12357 if (srec == null) {
12358 return -1;
12359 }
12360 return srec.launchedFromUid;
12361 }
12362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012363 // =========================================================
12364 // LIFETIME MANAGEMENT
12365 // =========================================================
12366
Christopher Tatef46723b2012-01-26 14:19:24 -080012367 // Returns which broadcast queue the app is the current [or imminent] receiver
12368 // on, or 'null' if the app is not an active broadcast recipient.
12369 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12370 BroadcastRecord r = app.curReceiver;
12371 if (r != null) {
12372 return r.queue;
12373 }
12374
12375 // It's not the current receiver, but it might be starting up to become one
12376 synchronized (this) {
12377 for (BroadcastQueue queue : mBroadcastQueues) {
12378 r = queue.mPendingBroadcast;
12379 if (r != null && r.curApp == app) {
12380 // found it; report which queue it's in
12381 return queue;
12382 }
12383 }
12384 }
12385
12386 return null;
12387 }
12388
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012389 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012390 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012391 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012392 // This adjustment has already been computed. If we are calling
12393 // from the top, we may have already computed our adjustment with
12394 // an earlier hidden adjustment that isn't really for us... if
12395 // so, use the new hidden adjustment.
12396 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012397 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12398 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012399 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012400 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012401 }
12402
12403 if (app.thread == null) {
12404 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012405 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012406 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012407 }
12408
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012409 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12410 app.adjSource = null;
12411 app.adjTarget = null;
12412 app.empty = false;
12413 app.hidden = false;
12414
12415 final int activitiesSize = app.activities.size();
12416
Dianne Hackborn7d608422011-08-07 16:24:18 -070012417 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012418 // The max adjustment doesn't allow this app to be anything
12419 // below foreground, so it is not worth doing work for it.
12420 app.adjType = "fixed";
12421 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012422 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012423 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012424 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012425 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012426 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012427 // System process can do UI, and when they do we want to have
12428 // them trim their memory after the user leaves the UI. To
12429 // facilitate this, here we need to determine whether or not it
12430 // is currently showing UI.
12431 app.systemNoUi = true;
12432 if (app == TOP_APP) {
12433 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012434 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012435 } else if (activitiesSize > 0) {
12436 for (int j = 0; j < activitiesSize; j++) {
12437 final ActivityRecord r = app.activities.get(j);
12438 if (r.visible) {
12439 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012440 }
12441 if (r.app == app) {
12442 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012443 }
12444 }
12445 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012446 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012447 }
12448
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012449 app.keeping = false;
12450 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012451 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452
The Android Open Source Project4df24232009-03-05 14:34:35 -080012453 // Determine the importance of the process, starting with most
12454 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012456 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012457 boolean foregroundActivities = false;
12458 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012459 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012460 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012462 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012463 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012464 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012465 foregroundActivities = true;
12466 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012467 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012468 } else if (app.instrumentationClass != null) {
12469 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012470 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012471 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012472 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012473 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012474 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012475 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012476 // counts as being in the foreground for OOM killer purposes.
12477 // It's placed in a sched group based on the nature of the
12478 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012479 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012480 schedGroup = (queue == mFgBroadcastQueue)
12481 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012482 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 } else if (app.executingServices.size() > 0) {
12484 // An app that is currently executing a service callback also
12485 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012486 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012487 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012488 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012489 } else {
12490 // Assume process is hidden (has activities); we will correct
12491 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012493 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012494 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012495 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012496 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012497
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012498 boolean hasStoppingActivities = false;
12499
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012500 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012501 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012502 for (int j = 0; j < activitiesSize; j++) {
12503 final ActivityRecord r = app.activities.get(j);
12504 if (r.visible) {
12505 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012506 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12507 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012508 app.adjType = "visible";
12509 }
12510 schedGroup = Process.THREAD_GROUP_DEFAULT;
12511 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012512 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012513 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012514 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012515 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012516 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12517 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012518 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012519 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012520 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012521 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012522 } else if (r.state == ActivityState.STOPPING) {
12523 // We will apply the actual adjustment later, because
12524 // we want to allow this process to immediately go through
12525 // any memory trimming that is in effect.
12526 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012527 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012528 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012529 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012530 if (r.app == app) {
12531 app.hasActivities = true;
12532 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012533 }
12534 }
12535
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012536 if (adj == hiddenAdj && !app.hasActivities) {
12537 // Whoops, this process is completely empty as far as we know
12538 // at this point.
12539 adj = emptyAdj;
12540 app.empty = true;
12541 app.adjType = "bg-empty";
12542 }
12543
Dianne Hackborn7d608422011-08-07 16:24:18 -070012544 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012545 if (app.foregroundServices) {
12546 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012547 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012548 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012549 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012550 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012551 } else if (app.forcingToForeground != null) {
12552 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012553 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012554 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012555 app.adjType = "force-foreground";
12556 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012557 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012558 }
12559 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012560
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012561 if (app.foregroundServices) {
12562 interesting = true;
12563 }
12564
Dianne Hackborn7d608422011-08-07 16:24:18 -070012565 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012566 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012567 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012568 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012569 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012570 app.adjType = "heavy";
12571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012572
Dianne Hackborn7d608422011-08-07 16:24:18 -070012573 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012574 // This process is hosting what we currently consider to be the
12575 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012576 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012577 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012578 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012579 app.adjType = "home";
12580 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012581
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012582 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12583 && app.activities.size() > 0) {
12584 // This was the previous process that showed UI to the user.
12585 // We want to try to keep it around more aggressively, to give
12586 // a good experience around switching between two apps.
12587 adj = ProcessList.PREVIOUS_APP_ADJ;
12588 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12589 app.hidden = false;
12590 app.adjType = "previous";
12591 }
12592
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012593 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12594 + " reason=" + app.adjType);
12595
The Android Open Source Project4df24232009-03-05 14:34:35 -080012596 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012597 // there are applications dependent on our services or providers, but
12598 // this gives us a baseline and makes sure we don't get into an
12599 // infinite recursion.
12600 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012601 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602
Christopher Tate6fa95972009-06-05 18:43:55 -070012603 if (mBackupTarget != null && app == mBackupTarget.app) {
12604 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012605 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012606 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012607 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012608 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012609 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012610 }
12611 }
12612
Dianne Hackborn7d608422011-08-07 16:24:18 -070012613 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012614 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012615 final long now = SystemClock.uptimeMillis();
12616 // This process is more important if the top activity is
12617 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012618 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012619 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012620 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012622 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012623 // If this process has shown some UI, let it immediately
12624 // go to the LRU list because it may be pretty heavy with
12625 // UI stuff. We'll tag it with a label just to help
12626 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012627 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012628 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012630 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012631 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012632 // This service has seen some activity within
12633 // recent memory, so we will keep its process ahead
12634 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012635 if (adj > ProcessList.SERVICE_ADJ) {
12636 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012637 app.adjType = "started-services";
12638 app.hidden = false;
12639 }
12640 }
12641 // If we have let the service slide into the background
12642 // state, still have some text describing what it is doing
12643 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012644 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012645 app.adjType = "started-bg-services";
12646 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012647 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012648 // Don't kill this process because it is doing work; it
12649 // has said it is doing work.
12650 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012652 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012653 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012654 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012655 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012656 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012657 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012658 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012659 // XXX should compute this based on the max of
12660 // all connected clients.
12661 ConnectionRecord cr = clist.get(i);
12662 if (cr.binding.client == app) {
12663 // Binding to ourself is not interesting.
12664 continue;
12665 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012666 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012667 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012668 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012669 int myHiddenAdj = hiddenAdj;
12670 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012671 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012672 myHiddenAdj = client.hiddenAdj;
12673 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012674 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012675 }
12676 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012677 int myEmptyAdj = emptyAdj;
12678 if (myEmptyAdj > client.emptyAdj) {
12679 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12680 myEmptyAdj = client.emptyAdj;
12681 } else {
12682 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12683 }
12684 }
12685 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12686 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012687 String adjType = null;
12688 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12689 // Not doing bind OOM management, so treat
12690 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012691 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012692 // If this process has shown some UI, let it immediately
12693 // go to the LRU list because it may be pretty heavy with
12694 // UI stuff. We'll tag it with a label just to help
12695 // debug and understand what is going on.
12696 if (adj > clientAdj) {
12697 adjType = "bound-bg-ui-services";
12698 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012699 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012700 clientAdj = adj;
12701 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012702 if (now >= (s.lastActivity
12703 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012704 // This service has not seen activity within
12705 // recent memory, so allow it to drop to the
12706 // LRU list if there is no other reason to keep
12707 // it around. We'll also tag it with a label just
12708 // to help debug and undertand what is going on.
12709 if (adj > clientAdj) {
12710 adjType = "bound-bg-services";
12711 }
12712 clientAdj = adj;
12713 }
12714 }
12715 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012716 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012717 // If this process has recently shown UI, and
12718 // the process that is binding to it is less
12719 // important than being visible, then we don't
12720 // care about the binding as much as we care
12721 // about letting this process get into the LRU
12722 // list to be killed and restarted if needed for
12723 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012724 if (app.hasShownUi && app != mHomeProcess
12725 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012726 adjType = "bound-bg-ui-services";
12727 } else {
12728 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12729 |Context.BIND_IMPORTANT)) != 0) {
12730 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012731 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12732 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12733 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12734 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12735 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012736 adj = clientAdj;
12737 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012738 app.pendingUiClean = true;
12739 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12740 adj = ProcessList.VISIBLE_APP_ADJ;
12741 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012742 }
12743 if (!client.hidden) {
12744 app.hidden = false;
12745 }
12746 if (client.keeping) {
12747 app.keeping = true;
12748 }
12749 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012750 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012751 }
12752 if (adjType != null) {
12753 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012754 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12755 .REASON_SERVICE_IN_USE;
12756 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012757 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012758 app.adjTarget = s.name;
12759 }
12760 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12761 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12762 schedGroup = Process.THREAD_GROUP_DEFAULT;
12763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764 }
12765 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012766 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12767 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012768 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012769 (a.visible || a.state == ActivityState.RESUMED
12770 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012771 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012772 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12773 schedGroup = Process.THREAD_GROUP_DEFAULT;
12774 }
12775 app.hidden = false;
12776 app.adjType = "service";
12777 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12778 .REASON_SERVICE_IN_USE;
12779 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012780 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012781 app.adjTarget = s.name;
12782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 }
12785 }
12786 }
12787 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012788
Dianne Hackborn287952c2010-09-22 22:34:31 -070012789 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012790 // would like to avoid killing it unless it would prevent the current
12791 // application from running. By default we put the process in
12792 // with the rest of the background processes; as we scan through
12793 // its services we may bump it up from there.
12794 if (adj > hiddenAdj) {
12795 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012796 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012797 app.adjType = "bg-services";
12798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012799 }
12800
Dianne Hackborn7d608422011-08-07 16:24:18 -070012801 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012802 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012803 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012804 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012805 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012806 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012807 for (int i = cpr.connections.size()-1;
12808 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12809 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12810 i--) {
12811 ContentProviderConnection conn = cpr.connections.get(i);
12812 ProcessRecord client = conn.client;
12813 if (client == app) {
12814 // Being our own client is not interesting.
12815 continue;
12816 }
12817 int myHiddenAdj = hiddenAdj;
12818 if (myHiddenAdj > client.hiddenAdj) {
12819 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12820 myHiddenAdj = client.hiddenAdj;
12821 } else {
12822 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012823 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012824 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012825 int myEmptyAdj = emptyAdj;
12826 if (myEmptyAdj > client.emptyAdj) {
12827 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12828 myEmptyAdj = client.emptyAdj;
12829 } else {
12830 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12831 }
12832 }
12833 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12834 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012835 if (adj > clientAdj) {
12836 if (app.hasShownUi && app != mHomeProcess
12837 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12838 app.adjType = "bg-ui-provider";
12839 } else {
12840 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12841 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12842 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012844 if (!client.hidden) {
12845 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012847 if (client.keeping) {
12848 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012849 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012850 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12851 .REASON_PROVIDER_IN_USE;
12852 app.adjSource = client;
12853 app.adjSourceOom = clientAdj;
12854 app.adjTarget = cpr.name;
12855 }
12856 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12857 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 }
12859 }
12860 // If the provider has external (non-framework) process
12861 // dependencies, ensure that its adjustment is at least
12862 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012863 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012864 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12865 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012866 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012867 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012868 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012869 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012870 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012871 }
12872 }
12873 }
12874 }
12875
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012876 if (adj == ProcessList.SERVICE_ADJ) {
12877 if (doingAll) {
12878 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12879 mNewNumServiceProcs++;
12880 }
12881 if (app.serviceb) {
12882 adj = ProcessList.SERVICE_B_ADJ;
12883 }
12884 } else {
12885 app.serviceb = false;
12886 }
12887
12888 app.nonStoppingAdj = adj;
12889
12890 if (hasStoppingActivities) {
12891 // Only upgrade adjustment.
12892 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12893 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12894 app.adjType = "stopping";
12895 }
12896 }
12897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898 app.curRawAdj = adj;
12899
Joe Onorato8a9b2202010-02-26 18:56:32 -080012900 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12902 if (adj > app.maxAdj) {
12903 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012904 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012905 schedGroup = Process.THREAD_GROUP_DEFAULT;
12906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012907 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012908 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012909 app.keeping = true;
12910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012912 if (app.hasAboveClient) {
12913 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12914 // then we need to drop its adjustment to be lower than the service's
12915 // in order to honor the request. We want to drop it by one adjustment
12916 // level... but there is special meaning applied to various levels so
12917 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012918 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012919 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012920 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12921 adj = ProcessList.VISIBLE_APP_ADJ;
12922 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12923 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12924 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12925 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012926 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012927 adj++;
12928 }
12929 }
12930
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012931 int importance = app.memImportance;
12932 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12933 app.curAdj = adj;
12934 app.curSchedGroup = schedGroup;
12935 if (!interesting) {
12936 // For this reporting, if there is not something explicitly
12937 // interesting in this process then we will push it to the
12938 // background importance.
12939 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12940 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12941 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12942 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12943 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12944 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12945 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12946 } else if (adj >= ProcessList.SERVICE_ADJ) {
12947 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12948 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12949 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12950 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12951 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12952 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12953 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12954 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12955 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12956 } else {
12957 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12958 }
12959 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012960
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012961 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12962 if (foregroundActivities != app.foregroundActivities) {
12963 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12964 }
12965 if (changes != 0) {
12966 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12967 app.memImportance = importance;
12968 app.foregroundActivities = foregroundActivities;
12969 int i = mPendingProcessChanges.size()-1;
12970 ProcessChangeItem item = null;
12971 while (i >= 0) {
12972 item = mPendingProcessChanges.get(i);
12973 if (item.pid == app.pid) {
12974 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12975 break;
12976 }
12977 i--;
12978 }
12979 if (i < 0) {
12980 // No existing item in pending changes; need a new one.
12981 final int NA = mAvailProcessChanges.size();
12982 if (NA > 0) {
12983 item = mAvailProcessChanges.remove(NA-1);
12984 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12985 } else {
12986 item = new ProcessChangeItem();
12987 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12988 }
12989 item.changes = 0;
12990 item.pid = app.pid;
12991 item.uid = app.info.uid;
12992 if (mPendingProcessChanges.size() == 0) {
12993 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12994 "*** Enqueueing dispatch processes changed!");
12995 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12996 }
12997 mPendingProcessChanges.add(item);
12998 }
12999 item.changes |= changes;
13000 item.importance = importance;
13001 item.foregroundActivities = foregroundActivities;
13002 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
13003 + Integer.toHexString(System.identityHashCode(item))
13004 + " " + app.toShortString() + ": changes=" + item.changes
13005 + " importance=" + item.importance
13006 + " foreground=" + item.foregroundActivities
13007 + " type=" + app.adjType + " source=" + app.adjSource
13008 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013009 }
13010
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013011 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 }
13013
13014 /**
13015 * Ask a given process to GC right now.
13016 */
13017 final void performAppGcLocked(ProcessRecord app) {
13018 try {
13019 app.lastRequestedGc = SystemClock.uptimeMillis();
13020 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013021 if (app.reportLowMemory) {
13022 app.reportLowMemory = false;
13023 app.thread.scheduleLowMemory();
13024 } else {
13025 app.thread.processInBackground();
13026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013027 }
13028 } catch (Exception e) {
13029 // whatever.
13030 }
13031 }
13032
13033 /**
13034 * Returns true if things are idle enough to perform GCs.
13035 */
Josh Bartel7f208742010-02-25 11:01:44 -060013036 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013037 boolean processingBroadcasts = false;
13038 for (BroadcastQueue q : mBroadcastQueues) {
13039 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13040 processingBroadcasts = true;
13041 }
13042 }
13043 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013044 && (mSleeping || (mMainStack.mResumedActivity != null &&
13045 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013046 }
13047
13048 /**
13049 * Perform GCs on all processes that are waiting for it, but only
13050 * if things are idle.
13051 */
13052 final void performAppGcsLocked() {
13053 final int N = mProcessesToGc.size();
13054 if (N <= 0) {
13055 return;
13056 }
Josh Bartel7f208742010-02-25 11:01:44 -060013057 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013058 while (mProcessesToGc.size() > 0) {
13059 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013060 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013061 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13062 <= SystemClock.uptimeMillis()) {
13063 // To avoid spamming the system, we will GC processes one
13064 // at a time, waiting a few seconds between each.
13065 performAppGcLocked(proc);
13066 scheduleAppGcsLocked();
13067 return;
13068 } else {
13069 // It hasn't been long enough since we last GCed this
13070 // process... put it in the list to wait for its time.
13071 addProcessToGcListLocked(proc);
13072 break;
13073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013074 }
13075 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013076
13077 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013078 }
13079 }
13080
13081 /**
13082 * If all looks good, perform GCs on all processes waiting for them.
13083 */
13084 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013085 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 performAppGcsLocked();
13087 return;
13088 }
13089 // Still not idle, wait some more.
13090 scheduleAppGcsLocked();
13091 }
13092
13093 /**
13094 * Schedule the execution of all pending app GCs.
13095 */
13096 final void scheduleAppGcsLocked() {
13097 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013098
13099 if (mProcessesToGc.size() > 0) {
13100 // Schedule a GC for the time to the next process.
13101 ProcessRecord proc = mProcessesToGc.get(0);
13102 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13103
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013104 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013105 long now = SystemClock.uptimeMillis();
13106 if (when < (now+GC_TIMEOUT)) {
13107 when = now + GC_TIMEOUT;
13108 }
13109 mHandler.sendMessageAtTime(msg, when);
13110 }
13111 }
13112
13113 /**
13114 * Add a process to the array of processes waiting to be GCed. Keeps the
13115 * list in sorted order by the last GC time. The process can't already be
13116 * on the list.
13117 */
13118 final void addProcessToGcListLocked(ProcessRecord proc) {
13119 boolean added = false;
13120 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13121 if (mProcessesToGc.get(i).lastRequestedGc <
13122 proc.lastRequestedGc) {
13123 added = true;
13124 mProcessesToGc.add(i+1, proc);
13125 break;
13126 }
13127 }
13128 if (!added) {
13129 mProcessesToGc.add(0, proc);
13130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013131 }
13132
13133 /**
13134 * Set up to ask a process to GC itself. This will either do it
13135 * immediately, or put it on the list of processes to gc the next
13136 * time things are idle.
13137 */
13138 final void scheduleAppGcLocked(ProcessRecord app) {
13139 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013140 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013141 return;
13142 }
13143 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013144 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145 scheduleAppGcsLocked();
13146 }
13147 }
13148
Dianne Hackborn287952c2010-09-22 22:34:31 -070013149 final void checkExcessivePowerUsageLocked(boolean doKills) {
13150 updateCpuStatsNow();
13151
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013152 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013153 boolean doWakeKills = doKills;
13154 boolean doCpuKills = doKills;
13155 if (mLastPowerCheckRealtime == 0) {
13156 doWakeKills = false;
13157 }
13158 if (mLastPowerCheckUptime == 0) {
13159 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013160 }
13161 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013162 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013163 }
13164 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013165 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13166 final long curUptime = SystemClock.uptimeMillis();
13167 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13168 mLastPowerCheckRealtime = curRealtime;
13169 mLastPowerCheckUptime = curUptime;
13170 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13171 doWakeKills = false;
13172 }
13173 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13174 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013175 }
13176 int i = mLruProcesses.size();
13177 while (i > 0) {
13178 i--;
13179 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013180 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013181 long wtime;
13182 synchronized (stats) {
13183 wtime = stats.getProcessWakeTime(app.info.uid,
13184 app.pid, curRealtime);
13185 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013186 long wtimeUsed = wtime - app.lastWakeTime;
13187 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13188 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013189 StringBuilder sb = new StringBuilder(128);
13190 sb.append("Wake for ");
13191 app.toShortString(sb);
13192 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013193 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013194 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013195 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013196 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013197 sb.append((wtimeUsed*100)/realtimeSince);
13198 sb.append("%)");
13199 Slog.i(TAG, sb.toString());
13200 sb.setLength(0);
13201 sb.append("CPU for ");
13202 app.toShortString(sb);
13203 sb.append(": over ");
13204 TimeUtils.formatDuration(uptimeSince, sb);
13205 sb.append(" used ");
13206 TimeUtils.formatDuration(cputimeUsed, sb);
13207 sb.append(" (");
13208 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013209 sb.append("%)");
13210 Slog.i(TAG, sb.toString());
13211 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013212 // If a process has held a wake lock for more
13213 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013214 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013215 if (doWakeKills && realtimeSince > 0
13216 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13217 synchronized (stats) {
13218 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13219 realtimeSince, wtimeUsed);
13220 }
13221 Slog.w(TAG, "Excessive wake lock in " + app.processName
13222 + " (pid " + app.pid + "): held " + wtimeUsed
13223 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013224 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13225 app.processName, app.setAdj, "excessive wake lock");
13226 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013227 } else if (doCpuKills && uptimeSince > 0
13228 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13229 synchronized (stats) {
13230 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13231 uptimeSince, cputimeUsed);
13232 }
13233 Slog.w(TAG, "Excessive CPU in " + app.processName
13234 + " (pid " + app.pid + "): used " + cputimeUsed
13235 + " during " + uptimeSince);
13236 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13237 app.processName, app.setAdj, "excessive cpu");
13238 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013239 } else {
13240 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013241 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013242 }
13243 }
13244 }
13245 }
13246
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013247 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13248 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013250 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251
13252 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013253 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013254 }
13255
Dianne Hackborn287952c2010-09-22 22:34:31 -070013256 final boolean wasKeeping = app.keeping;
13257
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013258 boolean success = true;
13259
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013260 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261
Jeff Brown10e89712011-07-08 18:52:57 -070013262 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013263 if (wasKeeping && !app.keeping) {
13264 // This app is no longer something we want to keep. Note
13265 // its current wake lock time to later know to kill it if
13266 // it is not behaving well.
13267 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13268 synchronized (stats) {
13269 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13270 app.pid, SystemClock.elapsedRealtime());
13271 }
13272 app.lastCpuTime = app.curCpuTime;
13273 }
13274
13275 app.setRawAdj = app.curRawAdj;
13276 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013277
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013278 if (app.curAdj != app.setAdj) {
13279 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013280 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013281 TAG, "Set " + app.pid + " " + app.processName +
13282 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013283 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013284 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013285 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013286 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013287 }
13288 }
13289 if (app.setSchedGroup != app.curSchedGroup) {
13290 app.setSchedGroup = app.curSchedGroup;
13291 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13292 "Setting process group of " + app.processName
13293 + " to " + app.curSchedGroup);
13294 if (app.waitingToKill != null &&
13295 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13296 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13297 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13298 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013299 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013300 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013301 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013302 } else {
13303 if (true) {
13304 long oldId = Binder.clearCallingIdentity();
13305 try {
13306 Process.setProcessGroup(app.pid, app.curSchedGroup);
13307 } catch (Exception e) {
13308 Slog.w(TAG, "Failed setting process group of " + app.pid
13309 + " to " + app.curSchedGroup);
13310 e.printStackTrace();
13311 } finally {
13312 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013313 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013314 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013315 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013316 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013317 app.thread.setSchedulingGroup(app.curSchedGroup);
13318 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013319 }
13320 }
13321 }
13322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013323 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013324 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013325 }
13326
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013327 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013328 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013330 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013332 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013333 }
13334 }
13335 return resumedActivity;
13336 }
13337
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013338 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013339 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13341 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013342 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13343 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344
13345 mAdjSeq++;
13346
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013347 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13348 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013349 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13350 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013351 if (nowHidden != wasHidden) {
13352 // Changed to/from hidden state, so apps after it in the LRU
13353 // list may also be changed.
13354 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013355 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013356 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013357 }
13358
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013359 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013360 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13362
13363 if (false) {
13364 RuntimeException e = new RuntimeException();
13365 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013366 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013367 }
13368
13369 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013370 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013371
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013372 // Let's determine how many processes we have running vs.
13373 // how many slots we have for background processes; we may want
13374 // to put multiple processes in a slot of there are enough of
13375 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013376 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13377 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13378 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13379 if (emptyFactor < 1) emptyFactor = 1;
13380 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13381 if (hiddenFactor < 1) hiddenFactor = 1;
13382 int stepHidden = 0;
13383 int stepEmpty = 0;
13384 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13385 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013386 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013387 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013388 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013389
13390 mNumNonHiddenProcs = 0;
13391 mNumHiddenProcs = 0;
13392
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013393 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013394 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013395 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013396 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013397 int nextHiddenAdj = curHiddenAdj+1;
13398 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13399 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013400 while (i > 0) {
13401 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013402 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013403 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013404 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013405 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013406 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13407 // This process was assigned as a hidden process... step the
13408 // hidden level.
13409 mNumHiddenProcs++;
13410 if (curHiddenAdj != nextHiddenAdj) {
13411 stepHidden++;
13412 if (stepHidden >= hiddenFactor) {
13413 stepHidden = 0;
13414 curHiddenAdj = nextHiddenAdj;
13415 nextHiddenAdj += 2;
13416 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13417 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13418 }
13419 }
13420 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013421 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013422 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013423 Slog.i(TAG, "No longer want " + app.processName
13424 + " (pid " + app.pid + "): hidden #" + numHidden);
13425 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13426 app.processName, app.setAdj, "too many background");
13427 app.killedBackground = true;
13428 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013429 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013430 } else {
13431 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13432 // This process was assigned as an empty process... step the
13433 // empty level.
13434 if (curEmptyAdj != nextEmptyAdj) {
13435 stepEmpty++;
13436 if (stepEmpty >= emptyFactor) {
13437 stepEmpty = 0;
13438 curEmptyAdj = nextEmptyAdj;
13439 nextEmptyAdj += 2;
13440 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13441 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13442 }
13443 }
13444 }
13445 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13446 mNumNonHiddenProcs++;
13447 }
13448 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13449 numEmpty++;
13450 if (numEmpty > emptyProcessLimit) {
13451 Slog.i(TAG, "No longer want " + app.processName
13452 + " (pid " + app.pid + "): empty #" + numEmpty);
13453 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13454 app.processName, app.setAdj, "too many background");
13455 app.killedBackground = true;
13456 Process.killProcessQuiet(app.pid);
13457 }
13458 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013459 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013460 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013461 // If this is an isolated process, and there are no
13462 // services running in it, then the process is no longer
13463 // needed. We agressively kill these because we can by
13464 // definition not re-use the same process again, and it is
13465 // good to avoid having whatever code was running in them
13466 // left sitting around after no longer needed.
13467 Slog.i(TAG, "Isolated process " + app.processName
13468 + " (pid " + app.pid + ") no longer needed");
13469 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13470 app.processName, app.setAdj, "isolated not needed");
13471 app.killedBackground = true;
13472 Process.killProcessQuiet(app.pid);
13473 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013474 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13475 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13476 && !app.killedBackground) {
13477 numTrimming++;
13478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 }
13480 }
13481
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013482 mNumServiceProcs = mNewNumServiceProcs;
13483
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013484 // Now determine the memory trimming level of background processes.
13485 // Unfortunately we need to start at the back of the list to do this
13486 // properly. We only do this if the number of background apps we
13487 // are managing to keep around is less than half the maximum we desire;
13488 // if we are keeping a good number around, we'll let them use whatever
13489 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013490 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13491 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13492 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013493 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013494 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013495 int minFactor = 2;
13496 if (mHomeProcess != null) minFactor++;
13497 if (mPreviousProcess != null) minFactor++;
13498 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013499 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013500 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013501 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013502 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013503 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013504 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13505 } else {
13506 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13507 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013508 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013509 for (i=0; i<N; i++) {
13510 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013511 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13512 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013513 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013514 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13515 try {
13516 app.thread.scheduleTrimMemory(curLevel);
13517 } catch (RemoteException e) {
13518 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013519 if (false) {
13520 // For now we won't do this; our memory trimming seems
13521 // to be good enough at this point that destroying
13522 // activities causes more harm than good.
13523 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13524 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013525 // Need to do this on its own message because the stack may not
13526 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013527 // For these apps we will also finish their activities
13528 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013529 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013530 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013531 }
13532 }
13533 app.trimMemoryLevel = curLevel;
13534 step++;
13535 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013536 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013537 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013538 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13539 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013540 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013541 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13542 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013543 break;
13544 }
13545 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013546 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013547 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013548 && app.thread != null) {
13549 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013550 app.thread.scheduleTrimMemory(
13551 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013552 } catch (RemoteException e) {
13553 }
13554 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013555 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013556 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013557 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013558 && app.pendingUiClean) {
13559 // If this application is now in the background and it
13560 // had done UI, then give it the special trim level to
13561 // have it free UI resources.
13562 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13563 if (app.trimMemoryLevel < level && app.thread != null) {
13564 try {
13565 app.thread.scheduleTrimMemory(level);
13566 } catch (RemoteException e) {
13567 }
13568 }
13569 app.pendingUiClean = false;
13570 }
13571 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013572 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013573 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013574 } catch (RemoteException e) {
13575 }
13576 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013577 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013578 }
13579 }
13580 } else {
13581 final int N = mLruProcesses.size();
13582 for (i=0; i<N; i++) {
13583 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013584 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013585 && app.pendingUiClean) {
13586 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13587 && app.thread != null) {
13588 try {
13589 app.thread.scheduleTrimMemory(
13590 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13591 } catch (RemoteException e) {
13592 }
13593 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013594 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013595 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013596 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013597 }
13598 }
13599
13600 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013601 // Need to do this on its own message because the stack may not
13602 // be in a consistent state at this point.
13603 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605 }
13606
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013607 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 synchronized (this) {
13609 int i;
13610
13611 // First remove any unused application processes whose package
13612 // has been removed.
13613 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13614 final ProcessRecord app = mRemovedProcesses.get(i);
13615 if (app.activities.size() == 0
13616 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013617 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618 TAG, "Exiting empty application process "
13619 + app.processName + " ("
13620 + (app.thread != null ? app.thread.asBinder() : null)
13621 + ")\n");
13622 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013623 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13624 app.processName, app.setAdj, "empty");
13625 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 } else {
13627 try {
13628 app.thread.scheduleExit();
13629 } catch (Exception e) {
13630 // Ignore exceptions.
13631 }
13632 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013633 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013634 mRemovedProcesses.remove(i);
13635
13636 if (app.persistent) {
13637 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013638 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013639 }
13640 }
13641 }
13642 }
13643
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013644 // Now update the oom adj for all processes.
13645 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013646 }
13647 }
13648
13649 /** This method sends the specified signal to each of the persistent apps */
13650 public void signalPersistentProcesses(int sig) throws RemoteException {
13651 if (sig != Process.SIGNAL_USR1) {
13652 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13653 }
13654
13655 synchronized (this) {
13656 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13657 != PackageManager.PERMISSION_GRANTED) {
13658 throw new SecurityException("Requires permission "
13659 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13660 }
13661
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013662 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13663 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013664 if (r.thread != null && r.persistent) {
13665 Process.sendSignal(r.pid, sig);
13666 }
13667 }
13668 }
13669 }
13670
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013671 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13672 if (proc == null || proc == mProfileProc) {
13673 proc = mProfileProc;
13674 path = mProfileFile;
13675 profileType = mProfileType;
13676 clearProfilerLocked();
13677 }
13678 if (proc == null) {
13679 return;
13680 }
13681 try {
13682 proc.thread.profilerControl(false, path, null, profileType);
13683 } catch (RemoteException e) {
13684 throw new IllegalStateException("Process disappeared");
13685 }
13686 }
13687
13688 private void clearProfilerLocked() {
13689 if (mProfileFd != null) {
13690 try {
13691 mProfileFd.close();
13692 } catch (IOException e) {
13693 }
13694 }
13695 mProfileApp = null;
13696 mProfileProc = null;
13697 mProfileFile = null;
13698 mProfileType = 0;
13699 mAutoStopProfiler = false;
13700 }
13701
Dianne Hackborn1676c852012-09-10 14:52:30 -070013702 public boolean profileControl(String process, int userId, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013703 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013704
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013705 try {
13706 synchronized (this) {
13707 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13708 // its own permission.
13709 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13710 != PackageManager.PERMISSION_GRANTED) {
13711 throw new SecurityException("Requires permission "
13712 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013713 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013714
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013715 if (start && fd == null) {
13716 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013717 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013718
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013719 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013720 if (process != null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070013721 proc = findProcessLocked(process, userId, "profileControl");
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013722 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013723
13724 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013725 throw new IllegalArgumentException("Unknown process: " + process);
13726 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013727
13728 if (start) {
13729 stopProfilerLocked(null, null, 0);
13730 setProfileApp(proc.info, proc.processName, path, fd, false);
13731 mProfileProc = proc;
13732 mProfileType = profileType;
13733 try {
13734 fd = fd.dup();
13735 } catch (IOException e) {
13736 fd = null;
13737 }
13738 proc.thread.profilerControl(start, path, fd, profileType);
13739 fd = null;
13740 mProfileFd = null;
13741 } else {
13742 stopProfilerLocked(proc, path, profileType);
13743 if (fd != null) {
13744 try {
13745 fd.close();
13746 } catch (IOException e) {
13747 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013748 }
13749 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013750
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013751 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013752 }
13753 } catch (RemoteException e) {
13754 throw new IllegalStateException("Process disappeared");
13755 } finally {
13756 if (fd != null) {
13757 try {
13758 fd.close();
13759 } catch (IOException e) {
13760 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013761 }
13762 }
13763 }
Andy McFadden824c5102010-07-09 16:26:57 -070013764
Dianne Hackborn1676c852012-09-10 14:52:30 -070013765 private ProcessRecord findProcessLocked(String process, int userId, String callName) {
13766 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
13767 userId, true, true, callName, null);
13768 ProcessRecord proc = null;
13769 try {
13770 int pid = Integer.parseInt(process);
13771 synchronized (mPidsSelfLocked) {
13772 proc = mPidsSelfLocked.get(pid);
13773 }
13774 } catch (NumberFormatException e) {
13775 }
13776
13777 if (proc == null) {
13778 HashMap<String, SparseArray<ProcessRecord>> all
13779 = mProcessNames.getMap();
13780 SparseArray<ProcessRecord> procs = all.get(process);
13781 if (procs != null && procs.size() > 0) {
13782 proc = procs.valueAt(0);
13783 if (userId != UserHandle.USER_ALL && proc.userId != userId) {
13784 for (int i=1; i<procs.size(); i++) {
13785 ProcessRecord thisProc = procs.valueAt(i);
13786 if (thisProc.userId == userId) {
13787 proc = thisProc;
13788 break;
13789 }
13790 }
13791 }
13792 }
13793 }
13794
13795 return proc;
13796 }
13797
13798 public boolean dumpHeap(String process, int userId, boolean managed,
Andy McFadden824c5102010-07-09 16:26:57 -070013799 String path, ParcelFileDescriptor fd) throws RemoteException {
13800
13801 try {
13802 synchronized (this) {
13803 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13804 // its own permission (same as profileControl).
13805 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13806 != PackageManager.PERMISSION_GRANTED) {
13807 throw new SecurityException("Requires permission "
13808 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13809 }
13810
13811 if (fd == null) {
13812 throw new IllegalArgumentException("null fd");
13813 }
13814
Dianne Hackborn1676c852012-09-10 14:52:30 -070013815 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap");
Andy McFadden824c5102010-07-09 16:26:57 -070013816 if (proc == null || proc.thread == null) {
13817 throw new IllegalArgumentException("Unknown process: " + process);
13818 }
13819
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013820 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13821 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013822 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13823 throw new SecurityException("Process not debuggable: " + proc);
13824 }
13825 }
13826
13827 proc.thread.dumpHeap(managed, path, fd);
13828 fd = null;
13829 return true;
13830 }
13831 } catch (RemoteException e) {
13832 throw new IllegalStateException("Process disappeared");
13833 } finally {
13834 if (fd != null) {
13835 try {
13836 fd.close();
13837 } catch (IOException e) {
13838 }
13839 }
13840 }
13841 }
13842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013843 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13844 public void monitor() {
13845 synchronized (this) { }
13846 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013847
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013848 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013849 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13850 ProcessRecord processRecord = mLruProcesses.get(i);
13851 try {
13852 if (processRecord.thread != null) {
13853 processRecord.thread.setCoreSettings(settings);
13854 }
13855 } catch (RemoteException re) {
13856 /* ignore */
13857 }
13858 }
13859 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013860
13861 // Multi-user methods
13862
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013863 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013864 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013865 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13866 != PackageManager.PERMISSION_GRANTED) {
13867 String msg = "Permission Denial: switchUser() from pid="
13868 + Binder.getCallingPid()
13869 + ", uid=" + Binder.getCallingUid()
13870 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13871 Slog.w(TAG, msg);
13872 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013873 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013874 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013875 if (mCurrentUserId == userId) {
13876 return true;
13877 }
13878
13879 // If the user we are switching to is not currently started, then
13880 // we need to start it now.
13881 if (mStartedUsers.get(userId) == null) {
13882 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013883 }
13884
13885 mCurrentUserId = userId;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070013886 Integer userIdInt = Integer.valueOf(userId);
13887 mUserLru.remove(userIdInt);
13888 mUserLru.add(userIdInt);
Amith Yamasani742a6712011-05-04 14:49:28 -070013889 boolean haveActivities = mMainStack.switchUser(userId);
13890 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013891 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013892 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013893 }
Amith Yamasani13593602012-03-22 16:16:17 -070013894
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013895 long ident = Binder.clearCallingIdentity();
13896 try {
13897 // Inform of user switch
13898 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13899 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013900 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13901 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013902 } finally {
13903 Binder.restoreCallingIdentity(ident);
13904 }
Amith Yamasani13593602012-03-22 16:16:17 -070013905
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013906 return true;
13907 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013908
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013909 void finishUserSwitch(UserStartedState uss) {
13910 synchronized (this) {
13911 if (uss.mState == UserStartedState.STATE_BOOTING
13912 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13913 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013914 final int userId = uss.mHandle.getIdentifier();
13915 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13916 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13917 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013918 null, null, 0, null, null,
13919 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013920 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013921 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013922 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013923 }
13924
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013925 @Override
13926 public int stopUser(final int userId, final IStopUserCallback callback) {
13927 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13928 != PackageManager.PERMISSION_GRANTED) {
13929 String msg = "Permission Denial: switchUser() from pid="
13930 + Binder.getCallingPid()
13931 + ", uid=" + Binder.getCallingUid()
13932 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13933 Slog.w(TAG, msg);
13934 throw new SecurityException(msg);
13935 }
13936 if (userId <= 0) {
13937 throw new IllegalArgumentException("Can't stop primary user " + userId);
13938 }
Amith Yamasani13593602012-03-22 16:16:17 -070013939 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013940 if (mCurrentUserId == userId) {
13941 return ActivityManager.USER_OP_IS_CURRENT;
13942 }
13943
13944 final UserStartedState uss = mStartedUsers.get(userId);
13945 if (uss == null) {
13946 // User is not started, nothing to do... but we do need to
13947 // callback if requested.
13948 if (callback != null) {
13949 mHandler.post(new Runnable() {
13950 @Override
13951 public void run() {
13952 try {
13953 callback.userStopped(userId);
13954 } catch (RemoteException e) {
13955 }
13956 }
13957 });
13958 }
13959 return ActivityManager.USER_OP_SUCCESS;
13960 }
13961
13962 if (callback != null) {
13963 uss.mStopCallbacks.add(callback);
13964 }
13965
13966 if (uss.mState != UserStartedState.STATE_STOPPING) {
13967 uss.mState = UserStartedState.STATE_STOPPING;
13968
13969 long ident = Binder.clearCallingIdentity();
13970 try {
13971 // Inform of user switch
13972 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13973 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13974 @Override
13975 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070013976 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013977 finishUserStop(uss);
13978 }
13979 };
13980 broadcastIntentLocked(null, null, intent,
13981 null, resultReceiver, 0, null, null, null,
13982 true, false, MY_PID, Process.SYSTEM_UID, userId);
13983 } finally {
13984 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013985 }
13986 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013987 }
Amith Yamasani13593602012-03-22 16:16:17 -070013988
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013989 return ActivityManager.USER_OP_SUCCESS;
13990 }
13991
13992 void finishUserStop(UserStartedState uss) {
13993 final int userId = uss.mHandle.getIdentifier();
13994 boolean stopped;
13995 ArrayList<IStopUserCallback> callbacks;
13996 synchronized (this) {
13997 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13998 if (uss.mState != UserStartedState.STATE_STOPPING
13999 || mStartedUsers.get(userId) != uss) {
14000 stopped = false;
14001 } else {
14002 stopped = true;
14003 // User can no longer run.
14004 mStartedUsers.remove(userId);
14005
14006 // Clean up all state and processes associated with the user.
14007 // Kill all the processes for the user.
14008 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070014009 }
14010 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014011
14012 for (int i=0; i<callbacks.size(); i++) {
14013 try {
14014 if (stopped) callbacks.get(i).userStopped(userId);
14015 else callbacks.get(i).userStopAborted(userId);
14016 } catch (RemoteException e) {
14017 }
14018 }
14019 }
14020
14021 @Override
14022 public UserInfo getCurrentUser() {
14023 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14024 != PackageManager.PERMISSION_GRANTED) {
14025 String msg = "Permission Denial: getCurrentUser() from pid="
14026 + Binder.getCallingPid()
14027 + ", uid=" + Binder.getCallingUid()
14028 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14029 Slog.w(TAG, msg);
14030 throw new SecurityException(msg);
14031 }
14032 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014033 return getUserManagerLocked().getUserInfo(mCurrentUserId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070014034 }
Amith Yamasani13593602012-03-22 16:16:17 -070014035 }
14036
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014037 @Override
14038 public boolean isUserRunning(int userId) {
14039 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14040 != PackageManager.PERMISSION_GRANTED) {
14041 String msg = "Permission Denial: isUserRunning() from pid="
14042 + Binder.getCallingPid()
14043 + ", uid=" + Binder.getCallingUid()
14044 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14045 Slog.w(TAG, msg);
14046 throw new SecurityException(msg);
14047 }
14048 synchronized (this) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014049 return isUserRunningLocked(userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014050 }
14051 }
14052
Dianne Hackborn1676c852012-09-10 14:52:30 -070014053 boolean isUserRunningLocked(int userId) {
14054 UserStartedState state = mStartedUsers.get(userId);
14055 return state != null && state.mState != UserStartedState.STATE_STOPPING;
Amith Yamasani258848d2012-08-10 17:06:33 -070014056 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014057
Dianne Hackborn1676c852012-09-10 14:52:30 -070014058 private boolean userExists(int userId) {
14059 if (userId == 0) {
14060 return true;
14061 }
14062 UserManagerService ums = getUserManagerLocked();
14063 return ums != null ? (ums.getUserInfo(userId) != null) : false;
14064 }
14065
14066 int[] getUsersLocked() {
14067 UserManagerService ums = getUserManagerLocked();
14068 return ums != null ? ums.getUserIds() : new int[] { 0 };
14069 }
14070
14071 UserManagerService getUserManagerLocked() {
Amith Yamasani258848d2012-08-10 17:06:33 -070014072 if (mUserManager == null) {
Dianne Hackborn1676c852012-09-10 14:52:30 -070014073 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
14074 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b);
Amith Yamasani258848d2012-08-10 17:06:33 -070014075 }
14076 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014077 }
14078
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014079 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014080 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014081
14082 throw new SecurityException("Caller uid=" + uid
14083 + " is not privileged to communicate with user=" + userId);
14084 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014085
14086 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014087 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014088 }
14089
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014090 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014091 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014092 ApplicationInfo newInfo = new ApplicationInfo(info);
14093 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014094 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14095 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014096 return newInfo;
14097 }
14098
14099 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014100 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014101 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014102 return aInfo;
14103 }
14104
14105 ActivityInfo info = new ActivityInfo(aInfo);
14106 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14107 return info;
14108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014109}