blob: 0eb99833285953d669abbfac287701be263405cc [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;
Amith Yamasani258848d2012-08-10 17:06:33 -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;
50import android.app.IThumbnailReceiver;
51import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070052import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070053import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070055import android.app.Service;
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;
103import android.os.Looper;
104import android.os.Message;
105import android.os.Parcel;
106import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700108import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import android.os.RemoteException;
110import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700111import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.SystemClock;
113import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700114import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700115import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700117import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800119import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700122import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700124import android.util.SparseIntArray;
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;
Amith Yamasani742a6712011-05-04 14:49:28 -0700148import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700149import java.util.Collections;
150import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.util.HashMap;
152import java.util.HashSet;
153import java.util.Iterator;
154import java.util.List;
155import java.util.Locale;
156import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700157import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700158import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700159import java.util.concurrent.atomic.AtomicBoolean;
160import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700162public final class ActivityManagerService extends ActivityManagerNative
163 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700166 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400168 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 static final boolean DEBUG_SWITCH = localLOGV || false;
170 static final boolean DEBUG_TASKS = localLOGV || false;
171 static final boolean DEBUG_PAUSE = localLOGV || false;
172 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
173 static final boolean DEBUG_TRANSITION = localLOGV || false;
174 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800175 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700176 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700178 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 static final boolean DEBUG_VISBILITY = localLOGV || false;
180 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700181 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700182 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800183 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700185 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700186 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700187 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700188 static final boolean DEBUG_POWER = localLOGV || false;
189 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700190 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 static final boolean VALIDATE_TOKENS = false;
192 static final boolean SHOW_ACTIVITY_START_TIME = true;
193
194 // Control over CPU and battery monitoring.
195 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
196 static final boolean MONITOR_CPU_USAGE = true;
197 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
198 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
199 static final boolean MONITOR_THREAD_CPU_USAGE = false;
200
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700202 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700203
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800204 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700206 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 // Maximum number of recent tasks that we can remember.
209 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700210
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700211 // Amount of time after a call to stopAppSwitches() during which we will
212 // prevent further untrusted switches from happening.
213 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real.
217 static final int PROC_START_TIMEOUT = 10*1000;
218
Jeff Brown3f9dd282011-07-08 20:02:19 -0700219 // How long we wait for a launched process to attach to the activity manager
220 // before we decide it's never going to come up for real, when the process was
221 // started with a wrapper for instrumentation (such as Valgrind) because it
222 // could take much longer than usual.
223 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 // How long to wait after going idle before forcing apps to GC.
226 static final int GC_TIMEOUT = 5*1000;
227
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700228 // The minimum amount of time between successive GC requests for a process.
229 static final int GC_MIN_INTERVAL = 60*1000;
230
Dianne Hackborn287952c2010-09-22 22:34:31 -0700231 // The rate at which we check for apps using excessive power -- 15 mins.
232 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on wake locks to start killing things.
236 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
237
238 // The minimum sample duration we will allow before deciding we have
239 // enough data on CPU usage to start killing things.
240 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800243 static final int BROADCAST_FG_TIMEOUT = 10*1000;
244 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // How long we wait until we timeout on key dispatching.
247 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // How long we wait until we timeout on key dispatching during instrumentation.
250 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
251
Dan Egnor42471dd2010-01-07 17:25:22 -0800252 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253
254 static final String[] EMPTY_STRING_ARRAY = new String[0];
255
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700256 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700257
258 private final boolean mHeadless;
259
Joe Onorato54a4a412011-11-02 20:50:08 -0700260 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
261 // default actuion automatically. Important for devices without direct input
262 // devices.
263 private boolean mShowDialogs = true;
264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700266 * Description of a request to start a new activity, which has been held
267 * due to app switches being disabled.
268 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700269 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700270 ActivityRecord r;
271 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700272 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700273 }
274
275 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
276 = new ArrayList<PendingActivityLaunch>();
277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800279 BroadcastQueue mFgBroadcastQueue;
280 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800281 // Convenient for easy iteration over the queues. Foreground is first
282 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800283 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800284
285 BroadcastQueue broadcastQueueForIntent(Intent intent) {
286 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
287 if (DEBUG_BACKGROUND_BROADCAST) {
288 Slog.i(TAG, "Broadcast intent " + intent + " on "
289 + (isFg ? "foreground" : "background")
290 + " queue");
291 }
292 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
293 }
294
295 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
296 for (BroadcastQueue queue : mBroadcastQueues) {
297 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
298 if (r != null) {
299 return r;
300 }
301 }
302 return null;
303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304
305 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 * Activity we have told the window manager to have key focus.
307 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700308 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700309 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 * List of intents that were used to start the most recent tasks.
311 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700312 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313
314 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700315 * Process management.
316 */
317 final ProcessList mProcessList = new ProcessList();
318
319 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * All of the applications we currently have running organized by name.
321 * The keys are strings of the application package name (as
322 * returned by the package manager), and the keys are ApplicationRecord
323 * objects.
324 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700325 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800326
327 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800328 * The currently running isolated processes.
329 */
330 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
331
332 /**
333 * Counter for assigning isolated process uids, to avoid frequently reusing the
334 * same ones.
335 */
336 int mNextIsolatedProcessUid = 0;
337
338 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700339 * The currently running heavy-weight process, if any.
340 */
341 ProcessRecord mHeavyWeightProcess = null;
342
343 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 * The last time that various processes have crashed.
345 */
346 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
347
348 /**
349 * Set of applications that we consider to be bad, and will reject
350 * incoming broadcasts from (which the user has no control over).
351 * Processes are added to this set when they have crashed twice within
352 * a minimum amount of time; they are removed from it when they are
353 * later restarted (hopefully due to some user action). The value is the
354 * time it was added to the list.
355 */
356 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
357
358 /**
359 * All of the processes we currently have running organized by pid.
360 * The keys are the pid running the application.
361 *
362 * <p>NOTE: This object is protected by its own lock, NOT the global
363 * activity manager lock!
364 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700365 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366
367 /**
368 * All of the processes that have been forced to be foreground. The key
369 * is the pid of the caller who requested it (we hold a death
370 * link on it).
371 */
372 abstract class ForegroundToken implements IBinder.DeathRecipient {
373 int pid;
374 IBinder token;
375 }
376 final SparseArray<ForegroundToken> mForegroundProcesses
377 = new SparseArray<ForegroundToken>();
378
379 /**
380 * List of records for processes that someone had tried to start before the
381 * system was ready. We don't start them at that point, but ensure they
382 * are started by the time booting is complete.
383 */
384 final ArrayList<ProcessRecord> mProcessesOnHold
385 = new ArrayList<ProcessRecord>();
386
387 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800388 * List of persistent applications that are in the process
389 * of being started.
390 */
391 final ArrayList<ProcessRecord> mPersistentStartingProcesses
392 = new ArrayList<ProcessRecord>();
393
394 /**
395 * Processes that are being forcibly torn down.
396 */
397 final ArrayList<ProcessRecord> mRemovedProcesses
398 = new ArrayList<ProcessRecord>();
399
400 /**
401 * List of running applications, sorted by recent usage.
402 * The first entry in the list is the least recently used.
403 * It contains ApplicationRecord objects. This list does NOT include
404 * any persistent application records (since we never want to exit them).
405 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800406 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 = new ArrayList<ProcessRecord>();
408
409 /**
410 * List of processes that should gc as soon as things are idle.
411 */
412 final ArrayList<ProcessRecord> mProcessesToGc
413 = new ArrayList<ProcessRecord>();
414
415 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800416 * This is the process holding what we currently consider to be
417 * the "home" activity.
418 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700419 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800420
421 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700422 * This is the process holding the activity the user last visited that
423 * is in a different process from the one they are currently in.
424 */
425 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800426
427 /**
428 * The time at which the previous process was last visible.
429 */
430 long mPreviousProcessVisibleTime;
431
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700432 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400433 * Packages that the user has asked to have run in screen size
434 * compatibility mode instead of filling the screen.
435 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700436 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400437
438 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 * Set of PendingResultRecord objects that are currently active.
440 */
441 final HashSet mPendingResultRecords = new HashSet();
442
443 /**
444 * Set of IntentSenderRecord objects that are currently active.
445 */
446 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
447 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
448
449 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800450 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700451 * already logged DropBox entries for. Guarded by itself. If
452 * something (rogue user app) forces this over
453 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
454 */
455 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
456 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
457
458 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700459 * Strict Mode background batched logging state.
460 *
461 * The string buffer is guarded by itself, and its lock is also
462 * used to determine if another batched write is already
463 * in-flight.
464 */
465 private final StringBuilder mStrictModeBuffer = new StringBuilder();
466
467 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 * Keeps track of all IIntentReceivers that have been registered for
469 * broadcasts. Hash keys are the receiver IBinder, hash value is
470 * a ReceiverList.
471 */
472 final HashMap mRegisteredReceivers = new HashMap();
473
474 /**
475 * Resolver for broadcast intents to registered receivers.
476 * Holds BroadcastFilter (subclass of IntentFilter).
477 */
478 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
479 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
480 @Override
481 protected boolean allowFilterResult(
482 BroadcastFilter filter, List<BroadcastFilter> dest) {
483 IBinder target = filter.receiverList.receiver.asBinder();
484 for (int i=dest.size()-1; i>=0; i--) {
485 if (dest.get(i).receiverList.receiver.asBinder() == target) {
486 return false;
487 }
488 }
489 return true;
490 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700491
492 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700493 protected BroadcastFilter[] newArray(int size) {
494 return new BroadcastFilter[size];
495 }
496
497 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700498 protected String packageForFilter(BroadcastFilter filter) {
499 return filter.packageName;
500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 };
502
503 /**
504 * State of all active sticky broadcasts. Keys are the action of the
505 * sticky Intent, values are an ArrayList of all broadcasted intents with
506 * that action (which should usually be one).
507 */
508 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
509 new HashMap<String, ArrayList<Intent>>();
510
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700511 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512
513 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700514 * Backup/restore process management
515 */
516 String mBackupAppName = null;
517 BackupRecord mBackupTarget = null;
518
519 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 * List of PendingThumbnailsRecord objects of clients who are still
521 * waiting to receive all of the thumbnails for a task.
522 */
523 final ArrayList mPendingThumbnails = new ArrayList();
524
525 /**
526 * List of HistoryRecord objects that have been finished and must
527 * still report back to a pending thumbnail receiver.
528 */
529 final ArrayList mCancelledThumbnails = new ArrayList();
530
Amith Yamasani742a6712011-05-04 14:49:28 -0700531 final ProviderMap mProviderMap = new ProviderMap();
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 /**
534 * List of content providers who have clients waiting for them. The
535 * application is currently being launched and the provider will be
536 * removed from this list once it is published.
537 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700538 final ArrayList<ContentProviderRecord> mLaunchingProviders
539 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540
541 /**
542 * Global set of specific Uri permissions that have been granted.
543 */
544 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
545 = new SparseArray<HashMap<Uri, UriPermission>>();
546
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800547 CoreSettingsObserver mCoreSettingsObserver;
548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 /**
550 * Thread-local storage used to carry caller permissions over through
551 * indirect content-provider access.
552 * @see #ActivityManagerService.openContentUri()
553 */
554 private class Identity {
555 public int pid;
556 public int uid;
557
558 Identity(int _pid, int _uid) {
559 pid = _pid;
560 uid = _uid;
561 }
562 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
565
566 /**
567 * All information we have collected about the runtime performance of
568 * any user id that can impact battery performance.
569 */
570 final BatteryStatsService mBatteryStatsService;
571
572 /**
573 * information about component usage
574 */
575 final UsageStatsService mUsageStatsService;
576
577 /**
578 * Current configuration information. HistoryRecord objects are given
579 * a reference to this object to indicate which configuration they are
580 * currently running in, so this object must be kept immutable.
581 */
582 Configuration mConfiguration = new Configuration();
583
584 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800585 * Current sequencing integer of the configuration, for skipping old
586 * configurations.
587 */
588 int mConfigurationSeq = 0;
589
590 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700591 * Hardware-reported OpenGLES version.
592 */
593 final int GL_ES_VERSION;
594
595 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800596 * List of initialization arguments to pass to all processes when binding applications to them.
597 * For example, references to the commonly used services.
598 */
599 HashMap<String, IBinder> mAppBindArgs;
600
601 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700602 * Temporary to avoid allocations. Protected by main lock.
603 */
604 final StringBuilder mStringBuilder = new StringBuilder(256);
605
606 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 * Used to control how we initialize the service.
608 */
609 boolean mStartRunning = false;
610 ComponentName mTopComponent;
611 String mTopAction;
612 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700613 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 boolean mSystemReady = false;
615 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700616 boolean mWaitingUpdate = false;
617 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700618 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700619 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620
621 Context mContext;
622
623 int mFactoryTest;
624
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700625 boolean mCheckedForSetup;
626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800627 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700628 * The time at which we will allow normal application switches again,
629 * after a call to {@link #stopAppSwitches()}.
630 */
631 long mAppSwitchesAllowedTime;
632
633 /**
634 * This is set to true after the first switch after mAppSwitchesAllowedTime
635 * is set; any switches after that will clear the time.
636 */
637 boolean mDidAppSwitch;
638
639 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700640 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700641 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700642 long mLastPowerCheckRealtime;
643
644 /**
645 * Last time (in uptime) at which we checked for power usage.
646 */
647 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700648
649 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 * Set while we are wanting to sleep, to prevent any
651 * activities from being started/resumed.
652 */
653 boolean mSleeping = false;
654
655 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700656 * State of external calls telling us if the device is asleep.
657 */
658 boolean mWentToSleep = false;
659
660 /**
661 * State of external call telling us if the lock screen is shown.
662 */
663 boolean mLockScreenShown = false;
664
665 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700666 * Set if we are shutting down the system, similar to sleeping.
667 */
668 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800669
670 /**
671 * Task identifier that activities are currently being started
672 * in. Incremented each time a new task is created.
673 * todo: Replace this with a TokenSpace class that generates non-repeating
674 * integers that won't wrap.
675 */
676 int mCurTask = 1;
677
678 /**
679 * Current sequence id for oom_adj computation traversal.
680 */
681 int mAdjSeq = 0;
682
683 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700684 * Current sequence id for process LRU updating.
685 */
686 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700689 * Keep track of the non-hidden/empty process we last found, to help
690 * determine how to distribute hidden/empty processes next time.
691 */
692 int mNumNonHiddenProcs = 0;
693
694 /**
695 * Keep track of the number of hidden procs, to balance oom adj
696 * distribution between those and empty procs.
697 */
698 int mNumHiddenProcs = 0;
699
700 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700701 * Keep track of the number of service processes we last found, to
702 * determine on the next iteration which should be B services.
703 */
704 int mNumServiceProcs = 0;
705 int mNewNumServiceProcs = 0;
706
707 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 * System monitoring: number of processes that died since the last
709 * N procs were started.
710 */
711 int[] mProcDeaths = new int[20];
712
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700713 /**
714 * This is set if we had to do a delayed dexopt of an app before launching
715 * it, to increasing the ANR timeouts in that case.
716 */
717 boolean mDidDexOpt;
718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 String mDebugApp = null;
720 boolean mWaitForDebugger = false;
721 boolean mDebugTransient = false;
722 String mOrigDebugApp = null;
723 boolean mOrigWaitForDebugger = false;
724 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700725 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700726 String mProfileApp = null;
727 ProcessRecord mProfileProc = null;
728 String mProfileFile;
729 ParcelFileDescriptor mProfileFd;
730 int mProfileType = 0;
731 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800732 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700734 static class ProcessChangeItem {
735 static final int CHANGE_ACTIVITIES = 1<<0;
736 static final int CHANGE_IMPORTANCE= 1<<1;
737 int changes;
738 int uid;
739 int pid;
740 int importance;
741 boolean foregroundActivities;
742 }
743
Jeff Sharkeya4620792011-05-20 15:29:23 -0700744 final RemoteCallbackList<IProcessObserver> mProcessObservers
745 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700746 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
747
748 final ArrayList<ProcessChangeItem> mPendingProcessChanges
749 = new ArrayList<ProcessChangeItem>();
750 final ArrayList<ProcessChangeItem> mAvailProcessChanges
751 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 /**
754 * Callback of last caller to {@link #requestPss}.
755 */
756 Runnable mRequestPssCallback;
757
758 /**
759 * Remaining processes for which we are waiting results from the last
760 * call to {@link #requestPss}.
761 */
762 final ArrayList<ProcessRecord> mRequestPssList
763 = new ArrayList<ProcessRecord>();
764
765 /**
766 * Runtime statistics collection thread. This object's lock is used to
767 * protect all related state.
768 */
769 final Thread mProcessStatsThread;
770
771 /**
772 * Used to collect process stats when showing not responding dialog.
773 * Protected by mProcessStatsThread.
774 */
775 final ProcessStats mProcessStats = new ProcessStats(
776 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700777 final AtomicLong mLastCpuTime = new AtomicLong(0);
778 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 long mLastWriteTime = 0;
781
782 /**
783 * Set to true after the system has finished booting.
784 */
785 boolean mBooted = false;
786
Dianne Hackborn7d608422011-08-07 16:24:18 -0700787 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700788 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789
790 WindowManagerService mWindowManager;
791
792 static ActivityManagerService mSelf;
793 static ActivityThread mSystemThread;
794
Amith Yamasani258848d2012-08-10 17:06:33 -0700795 private int mCurrentUserId;
796 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
797 private UserManager mUserManager;
798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 private final class AppDeathRecipient implements IBinder.DeathRecipient {
800 final ProcessRecord mApp;
801 final int mPid;
802 final IApplicationThread mAppThread;
803
804 AppDeathRecipient(ProcessRecord app, int pid,
805 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800806 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 TAG, "New death recipient " + this
808 + " for thread " + thread.asBinder());
809 mApp = app;
810 mPid = pid;
811 mAppThread = thread;
812 }
813
814 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800815 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 TAG, "Death received in " + this
817 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 synchronized(ActivityManagerService.this) {
819 appDiedLocked(mApp, mPid, mAppThread);
820 }
821 }
822 }
823
824 static final int SHOW_ERROR_MSG = 1;
825 static final int SHOW_NOT_RESPONDING_MSG = 2;
826 static final int SHOW_FACTORY_ERROR_MSG = 3;
827 static final int UPDATE_CONFIGURATION_MSG = 4;
828 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
829 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 static final int SERVICE_TIMEOUT_MSG = 12;
831 static final int UPDATE_TIME_ZONE = 13;
832 static final int SHOW_UID_ERROR_MSG = 14;
833 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700835 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700836 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800837 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700838 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
839 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700840 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700841 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700842 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700843 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700844 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700845 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700846 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700847 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800849 static final int FIRST_ACTIVITY_STACK_MSG = 100;
850 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
851 static final int FIRST_COMPAT_MODE_MSG = 300;
852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700854 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700855 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856
857 final Handler mHandler = new Handler() {
858 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800859 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 //}
861
862 public void handleMessage(Message msg) {
863 switch (msg.what) {
864 case SHOW_ERROR_MSG: {
865 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 synchronized (ActivityManagerService.this) {
867 ProcessRecord proc = (ProcessRecord)data.get("app");
868 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800869 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 return;
871 }
872 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700873 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800874 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 d.show();
876 proc.crashDialog = d;
877 } else {
878 // The device is asleep, so just pretend that the user
879 // saw a crash dialog and hit "force quit".
880 res.set(0);
881 }
882 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700883
884 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 } break;
886 case SHOW_NOT_RESPONDING_MSG: {
887 synchronized (ActivityManagerService.this) {
888 HashMap data = (HashMap) msg.obj;
889 ProcessRecord proc = (ProcessRecord)data.get("app");
890 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800891 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 return;
893 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800894
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700895 Intent intent = new Intent("android.intent.action.ANR");
896 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800897 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
898 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700899 }
900 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800901 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700902 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800903
Justin Kohbc52ca22012-03-29 15:11:44 -0700904 if (mShowDialogs) {
905 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700906 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700907 d.show();
908 proc.anrDialog = d;
909 } else {
910 // Just kill the app if there is no dialog to be shown.
911 killAppAtUsersRequest(proc, null);
912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700914
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700915 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700917 case SHOW_STRICT_MODE_VIOLATION_MSG: {
918 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
919 synchronized (ActivityManagerService.this) {
920 ProcessRecord proc = (ProcessRecord) data.get("app");
921 if (proc == null) {
922 Slog.e(TAG, "App not found when showing strict mode dialog.");
923 break;
924 }
925 if (proc.crashDialog != null) {
926 Slog.e(TAG, "App already has strict mode dialog: " + proc);
927 return;
928 }
929 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700930 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700931 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
932 d.show();
933 proc.crashDialog = d;
934 } else {
935 // The device is asleep, so just pretend that the user
936 // saw a crash dialog and hit "force quit".
937 res.set(0);
938 }
939 }
940 ensureBootCompleted();
941 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 case SHOW_FACTORY_ERROR_MSG: {
943 Dialog d = new FactoryErrorDialog(
944 mContext, msg.getData().getCharSequence("msg"));
945 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700946 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 } break;
948 case UPDATE_CONFIGURATION_MSG: {
949 final ContentResolver resolver = mContext.getContentResolver();
950 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
951 } break;
952 case GC_BACKGROUND_PROCESSES_MSG: {
953 synchronized (ActivityManagerService.this) {
954 performAppGcsIfAppropriateLocked();
955 }
956 } break;
957 case WAIT_FOR_DEBUGGER_MSG: {
958 synchronized (ActivityManagerService.this) {
959 ProcessRecord app = (ProcessRecord)msg.obj;
960 if (msg.arg1 != 0) {
961 if (!app.waitedForDebugger) {
962 Dialog d = new AppWaitingForDebuggerDialog(
963 ActivityManagerService.this,
964 mContext, app);
965 app.waitDialog = d;
966 app.waitedForDebugger = true;
967 d.show();
968 }
969 } else {
970 if (app.waitDialog != null) {
971 app.waitDialog.dismiss();
972 app.waitDialog = null;
973 }
974 }
975 }
976 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700978 if (mDidDexOpt) {
979 mDidDexOpt = false;
980 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
981 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700982 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700983 return;
984 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700985 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 } break;
987 case UPDATE_TIME_ZONE: {
988 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800989 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
990 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 if (r.thread != null) {
992 try {
993 r.thread.updateTimeZone();
994 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800995 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
997 }
998 }
999 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001000 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001001 case CLEAR_DNS_CACHE: {
1002 synchronized (ActivityManagerService.this) {
1003 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1004 ProcessRecord r = mLruProcesses.get(i);
1005 if (r.thread != null) {
1006 try {
1007 r.thread.clearDnsCache();
1008 } catch (RemoteException ex) {
1009 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1010 }
1011 }
1012 }
1013 }
1014 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001015 case UPDATE_HTTP_PROXY: {
1016 ProxyProperties proxy = (ProxyProperties)msg.obj;
1017 String host = "";
1018 String port = "";
1019 String exclList = "";
1020 if (proxy != null) {
1021 host = proxy.getHost();
1022 port = Integer.toString(proxy.getPort());
1023 exclList = proxy.getExclusionList();
1024 }
1025 synchronized (ActivityManagerService.this) {
1026 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1027 ProcessRecord r = mLruProcesses.get(i);
1028 if (r.thread != null) {
1029 try {
1030 r.thread.setHttpProxy(host, port, exclList);
1031 } catch (RemoteException ex) {
1032 Slog.w(TAG, "Failed to update http proxy for: " +
1033 r.info.processName);
1034 }
1035 }
1036 }
1037 }
1038 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001040 String title = "System UIDs Inconsistent";
1041 String text = "UIDs on the system are inconsistent, you need to wipe your"
1042 + " data partition or your device will be unstable.";
1043 Log.e(TAG, title + ": " + text);
1044 if (mShowDialogs) {
1045 // XXX This is a temporary dialog, no need to localize.
1046 AlertDialog d = new BaseErrorDialog(mContext);
1047 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1048 d.setCancelable(false);
1049 d.setTitle(title);
1050 d.setMessage(text);
1051 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1052 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1053 mUidAlert = d;
1054 d.show();
1055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 } break;
1057 case IM_FEELING_LUCKY_MSG: {
1058 if (mUidAlert != null) {
1059 mUidAlert.dismiss();
1060 mUidAlert = null;
1061 }
1062 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001064 if (mDidDexOpt) {
1065 mDidDexOpt = false;
1066 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1067 nmsg.obj = msg.obj;
1068 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1069 return;
1070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 ProcessRecord app = (ProcessRecord)msg.obj;
1072 synchronized (ActivityManagerService.this) {
1073 processStartTimedOutLocked(app);
1074 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001075 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001076 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1077 synchronized (ActivityManagerService.this) {
1078 doPendingActivityLaunchesLocked(true);
1079 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001080 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001081 case KILL_APPLICATION_MSG: {
1082 synchronized (ActivityManagerService.this) {
1083 int uid = msg.arg1;
1084 boolean restart = (msg.arg2 == 1);
1085 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001086 forceStopPackageLocked(pkg, uid, restart, false, true, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001087 UserHandle.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001088 }
1089 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001090 case FINALIZE_PENDING_INTENT_MSG: {
1091 ((PendingIntentRecord)msg.obj).completeFinalize();
1092 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001093 case POST_HEAVY_NOTIFICATION_MSG: {
1094 INotificationManager inm = NotificationManager.getService();
1095 if (inm == null) {
1096 return;
1097 }
1098
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001099 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001100 ProcessRecord process = root.app;
1101 if (process == null) {
1102 return;
1103 }
1104
1105 try {
1106 Context context = mContext.createPackageContext(process.info.packageName, 0);
1107 String text = mContext.getString(R.string.heavy_weight_notification,
1108 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1109 Notification notification = new Notification();
1110 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1111 notification.when = 0;
1112 notification.flags = Notification.FLAG_ONGOING_EVENT;
1113 notification.tickerText = text;
1114 notification.defaults = 0; // please be quiet
1115 notification.sound = null;
1116 notification.vibrate = null;
1117 notification.setLatestEventInfo(context, text,
1118 mContext.getText(R.string.heavy_weight_notification_detail),
1119 PendingIntent.getActivity(mContext, 0, root.intent,
1120 PendingIntent.FLAG_CANCEL_CURRENT));
1121
1122 try {
1123 int[] outId = new int[1];
1124 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1125 notification, outId);
1126 } catch (RuntimeException e) {
1127 Slog.w(ActivityManagerService.TAG,
1128 "Error showing notification for heavy-weight app", e);
1129 } catch (RemoteException e) {
1130 }
1131 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001132 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001133 }
1134 } break;
1135 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1136 INotificationManager inm = NotificationManager.getService();
1137 if (inm == null) {
1138 return;
1139 }
1140 try {
1141 inm.cancelNotification("android",
1142 R.string.heavy_weight_notification);
1143 } catch (RuntimeException e) {
1144 Slog.w(ActivityManagerService.TAG,
1145 "Error canceling notification for service", e);
1146 } catch (RemoteException e) {
1147 }
1148 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001149 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1150 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001151 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001152 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001153 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1154 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001155 }
1156 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001157 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1158 synchronized (ActivityManagerService.this) {
1159 ActivityRecord ar = (ActivityRecord)msg.obj;
1160 if (mCompatModeDialog != null) {
1161 if (mCompatModeDialog.mAppInfo.packageName.equals(
1162 ar.info.applicationInfo.packageName)) {
1163 return;
1164 }
1165 mCompatModeDialog.dismiss();
1166 mCompatModeDialog = null;
1167 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001168 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001169 if (mCompatModePackages.getPackageAskCompatModeLocked(
1170 ar.packageName)) {
1171 int mode = mCompatModePackages.computeCompatModeLocked(
1172 ar.info.applicationInfo);
1173 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1174 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1175 mCompatModeDialog = new CompatModeDialog(
1176 ActivityManagerService.this, mContext,
1177 ar.info.applicationInfo);
1178 mCompatModeDialog.show();
1179 }
1180 }
1181 }
1182 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001183 break;
1184 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001185 case DISPATCH_PROCESSES_CHANGED: {
1186 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 break;
1188 }
1189 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001190 final int pid = msg.arg1;
1191 final int uid = msg.arg2;
1192 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001193 break;
1194 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001195 case REPORT_MEM_USAGE: {
1196 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1197 if (!isDebuggable) {
1198 return;
1199 }
1200 synchronized (ActivityManagerService.this) {
1201 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001202 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1203 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001204 // avoid spamming.
1205 return;
1206 }
1207 mLastMemUsageReportTime = now;
1208 }
1209 Thread thread = new Thread() {
1210 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001211 StringBuilder dropBuilder = new StringBuilder(1024);
1212 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001213 StringWriter oomSw = new StringWriter();
1214 PrintWriter oomPw = new PrintWriter(oomSw);
1215 StringWriter catSw = new StringWriter();
1216 PrintWriter catPw = new PrintWriter(catSw);
1217 String[] emptyArgs = new String[] { };
1218 StringBuilder tag = new StringBuilder(128);
1219 StringBuilder stack = new StringBuilder(128);
1220 tag.append("Low on memory -- ");
1221 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1222 tag, stack);
1223 dropBuilder.append(stack);
1224 dropBuilder.append('\n');
1225 dropBuilder.append('\n');
1226 String oomString = oomSw.toString();
1227 dropBuilder.append(oomString);
1228 dropBuilder.append('\n');
1229 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001230 try {
1231 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1232 "procrank", });
1233 final InputStreamReader converter = new InputStreamReader(
1234 proc.getInputStream());
1235 BufferedReader in = new BufferedReader(converter);
1236 String line;
1237 while (true) {
1238 line = in.readLine();
1239 if (line == null) {
1240 break;
1241 }
1242 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001243 logBuilder.append(line);
1244 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001246 dropBuilder.append(line);
1247 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001248 }
1249 converter.close();
1250 } catch (IOException e) {
1251 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001253 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001254 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001255 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001256 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1257 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001258 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001259 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001262 addErrorToDropBox("lowmem", null, "system_server", null,
1263 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001264 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001265 synchronized (ActivityManagerService.this) {
1266 long now = SystemClock.uptimeMillis();
1267 if (mLastMemUsageReportTime < now) {
1268 mLastMemUsageReportTime = now;
1269 }
1270 }
1271 }
1272 };
1273 thread.start();
1274 break;
1275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
1277 }
1278 };
1279
1280 public static void setSystemProcess() {
1281 try {
1282 ActivityManagerService m = mSelf;
1283
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001284 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001286 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001287 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (MONITOR_CPU_USAGE) {
1289 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 ServiceManager.addService("permission", new PermissionController(m));
1292
1293 ApplicationInfo info =
1294 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001295 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001296 mSystemThread.installSystemApplicationInfo(info);
1297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 synchronized (mSelf) {
1299 ProcessRecord app = mSelf.newProcessRecordLocked(
1300 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001301 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001303 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001304 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001305 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 synchronized (mSelf.mPidsSelfLocked) {
1307 mSelf.mPidsSelfLocked.put(app.pid, app);
1308 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001309 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 }
1311 } catch (PackageManager.NameNotFoundException e) {
1312 throw new RuntimeException(
1313 "Unable to find android system package", e);
1314 }
1315 }
1316
1317 public void setWindowManager(WindowManagerService wm) {
1318 mWindowManager = wm;
1319 }
1320
1321 public static final Context main(int factoryTest) {
1322 AThread thr = new AThread();
1323 thr.start();
1324
1325 synchronized (thr) {
1326 while (thr.mService == null) {
1327 try {
1328 thr.wait();
1329 } catch (InterruptedException e) {
1330 }
1331 }
1332 }
1333
1334 ActivityManagerService m = thr.mService;
1335 mSelf = m;
1336 ActivityThread at = ActivityThread.systemMain();
1337 mSystemThread = at;
1338 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001339 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 m.mContext = context;
1341 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001342 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343
1344 m.mBatteryStatsService.publish(context);
1345 m.mUsageStatsService.publish(context);
1346
1347 synchronized (thr) {
1348 thr.mReady = true;
1349 thr.notifyAll();
1350 }
1351
1352 m.startRunning(null, null, null, null);
1353
1354 return context;
1355 }
1356
1357 public static ActivityManagerService self() {
1358 return mSelf;
1359 }
1360
1361 static class AThread extends Thread {
1362 ActivityManagerService mService;
1363 boolean mReady = false;
1364
1365 public AThread() {
1366 super("ActivityManager");
1367 }
1368
1369 public void run() {
1370 Looper.prepare();
1371
1372 android.os.Process.setThreadPriority(
1373 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001374 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375
1376 ActivityManagerService m = new ActivityManagerService();
1377
1378 synchronized (this) {
1379 mService = m;
1380 notifyAll();
1381 }
1382
1383 synchronized (this) {
1384 while (!mReady) {
1385 try {
1386 wait();
1387 } catch (InterruptedException e) {
1388 }
1389 }
1390 }
1391
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001392 // For debug builds, log event loop stalls to dropbox for analysis.
1393 if (StrictMode.conditionallyEnableDebugLogging()) {
1394 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 Looper.loop();
1398 }
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 static class MemBinder extends Binder {
1402 ActivityManagerService mActivityManagerService;
1403 MemBinder(ActivityManagerService activityManagerService) {
1404 mActivityManagerService = activityManagerService;
1405 }
1406
1407 @Override
1408 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001409 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1410 != PackageManager.PERMISSION_GRANTED) {
1411 pw.println("Permission Denial: can't dump meminfo from from pid="
1412 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1413 + " without permission " + android.Manifest.permission.DUMP);
1414 return;
1415 }
1416
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001417 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001418 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 }
1421
Chet Haase9c1e23b2011-03-24 10:51:31 -07001422 static class GraphicsBinder extends Binder {
1423 ActivityManagerService mActivityManagerService;
1424 GraphicsBinder(ActivityManagerService activityManagerService) {
1425 mActivityManagerService = activityManagerService;
1426 }
1427
1428 @Override
1429 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001430 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1431 != PackageManager.PERMISSION_GRANTED) {
1432 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1433 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1434 + " without permission " + android.Manifest.permission.DUMP);
1435 return;
1436 }
1437
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001438 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001439 }
1440 }
1441
Jeff Brown6754ba22011-12-14 20:20:01 -08001442 static class DbBinder extends Binder {
1443 ActivityManagerService mActivityManagerService;
1444 DbBinder(ActivityManagerService activityManagerService) {
1445 mActivityManagerService = activityManagerService;
1446 }
1447
1448 @Override
1449 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1450 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1451 != PackageManager.PERMISSION_GRANTED) {
1452 pw.println("Permission Denial: can't dump dbinfo from from pid="
1453 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1454 + " without permission " + android.Manifest.permission.DUMP);
1455 return;
1456 }
1457
1458 mActivityManagerService.dumpDbInfo(fd, pw, args);
1459 }
1460 }
1461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 static class CpuBinder extends Binder {
1463 ActivityManagerService mActivityManagerService;
1464 CpuBinder(ActivityManagerService activityManagerService) {
1465 mActivityManagerService = activityManagerService;
1466 }
1467
1468 @Override
1469 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001470 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1471 != PackageManager.PERMISSION_GRANTED) {
1472 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1473 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1474 + " without permission " + android.Manifest.permission.DUMP);
1475 return;
1476 }
1477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001479 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1480 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1481 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 }
1483 }
1484 }
1485
1486 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001487 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001488
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001489 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1490 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1491 mBroadcastQueues[0] = mFgBroadcastQueue;
1492 mBroadcastQueues[1] = mBgBroadcastQueue;
1493
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001494 mServices = new ActiveServices(this);
1495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 File dataDir = Environment.getDataDirectory();
1497 File systemDir = new File(dataDir, "system");
1498 systemDir.mkdirs();
1499 mBatteryStatsService = new BatteryStatsService(new File(
1500 systemDir, "batterystats.bin").toString());
1501 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001502 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001503 mOnBattery = DEBUG_POWER ? true
1504 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001505 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001507 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001508 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001509 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510
Jack Palevichb90d28c2009-07-22 15:35:24 -07001511 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1512 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1513
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001514 mConfiguration.setToDefaults();
1515 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001516 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 mProcessStats.init();
1518
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001519 mCompatModePackages = new CompatModePackages(this, systemDir);
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 // Add ourself to the Watchdog monitors.
1522 Watchdog.getInstance().addMonitor(this);
1523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 mProcessStatsThread = new Thread("ProcessStats") {
1525 public void run() {
1526 while (true) {
1527 try {
1528 try {
1529 synchronized(this) {
1530 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001531 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001533 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 // + ", write delay=" + nextWriteDelay);
1535 if (nextWriteDelay < nextCpuDelay) {
1536 nextCpuDelay = nextWriteDelay;
1537 }
1538 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001539 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 this.wait(nextCpuDelay);
1541 }
1542 }
1543 } catch (InterruptedException e) {
1544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 updateCpuStatsNow();
1546 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001547 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 }
1550 }
1551 };
1552 mProcessStatsThread.start();
1553 }
1554
1555 @Override
1556 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1557 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001558 if (code == SYSPROPS_TRANSACTION) {
1559 // We need to tell all apps about the system property change.
1560 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1561 synchronized(this) {
1562 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1563 final int NA = apps.size();
1564 for (int ia=0; ia<NA; ia++) {
1565 ProcessRecord app = apps.valueAt(ia);
1566 if (app.thread != null) {
1567 procs.add(app.thread.asBinder());
1568 }
1569 }
1570 }
1571 }
1572
1573 int N = procs.size();
1574 for (int i=0; i<N; i++) {
1575 Parcel data2 = Parcel.obtain();
1576 try {
1577 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1578 } catch (RemoteException e) {
1579 }
1580 data2.recycle();
1581 }
1582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 try {
1584 return super.onTransact(code, data, reply, flags);
1585 } catch (RuntimeException e) {
1586 // The activity manager only throws security exceptions, so let's
1587 // log all others.
1588 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001589 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 }
1591 throw e;
1592 }
1593 }
1594
1595 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001596 final long now = SystemClock.uptimeMillis();
1597 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1598 return;
1599 }
1600 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1601 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 mProcessStatsThread.notify();
1603 }
1604 }
1605 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 void updateCpuStatsNow() {
1608 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001609 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 final long now = SystemClock.uptimeMillis();
1611 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001614 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1615 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001616 haveNewCpuStats = true;
1617 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001618 //Slog.i(TAG, mProcessStats.printCurrentState());
1619 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 // + mProcessStats.getTotalCpuPercent() + "%");
1621
Joe Onorato8a9b2202010-02-26 18:56:32 -08001622 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 if ("true".equals(SystemProperties.get("events.cpu"))) {
1624 int user = mProcessStats.getLastUserTime();
1625 int system = mProcessStats.getLastSystemTime();
1626 int iowait = mProcessStats.getLastIoWaitTime();
1627 int irq = mProcessStats.getLastIrqTime();
1628 int softIrq = mProcessStats.getLastSoftIrqTime();
1629 int idle = mProcessStats.getLastIdleTime();
1630
1631 int total = user + system + iowait + irq + softIrq + idle;
1632 if (total == 0) total = 1;
1633
Doug Zongker2bec3d42009-12-04 12:52:44 -08001634 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 ((user+system+iowait+irq+softIrq) * 100) / total,
1636 (user * 100) / total,
1637 (system * 100) / total,
1638 (iowait * 100) / total,
1639 (irq * 100) / total,
1640 (softIrq * 100) / total);
1641 }
1642 }
1643
Amith Yamasanie43530a2009-08-21 13:11:37 -07001644 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001645 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001646 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 synchronized(mPidsSelfLocked) {
1648 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001649 if (mOnBattery) {
1650 int perc = bstats.startAddingCpuLocked();
1651 int totalUTime = 0;
1652 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001653 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001655 ProcessStats.Stats st = mProcessStats.getStats(i);
1656 if (!st.working) {
1657 continue;
1658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001660 int otherUTime = (st.rel_utime*perc)/100;
1661 int otherSTime = (st.rel_stime*perc)/100;
1662 totalUTime += otherUTime;
1663 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 if (pr != null) {
1665 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001666 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1667 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001668 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001669 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001670 } else {
1671 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001672 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001673 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001674 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1675 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001676 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
1679 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001680 bstats.finishAddingCpuLocked(perc, totalUTime,
1681 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 }
1684 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1687 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001688 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
1691 }
1692 }
1693
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001694 @Override
1695 public void batteryNeedsCpuUpdate() {
1696 updateCpuStatsNow();
1697 }
1698
1699 @Override
1700 public void batteryPowerChanged(boolean onBattery) {
1701 // When plugging in, update the CPU stats first before changing
1702 // the plug state.
1703 updateCpuStatsNow();
1704 synchronized (this) {
1705 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001706 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001707 }
1708 }
1709 }
1710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 /**
1712 * Initialize the application bind args. These are passed to each
1713 * process when the bindApplication() IPC is sent to the process. They're
1714 * lazily setup to make sure the services are running when they're asked for.
1715 */
1716 private HashMap<String, IBinder> getCommonServicesLocked() {
1717 if (mAppBindArgs == null) {
1718 mAppBindArgs = new HashMap<String, IBinder>();
1719
1720 // Setup the application init args
1721 mAppBindArgs.put("package", ServiceManager.getService("package"));
1722 mAppBindArgs.put("window", ServiceManager.getService("window"));
1723 mAppBindArgs.put(Context.ALARM_SERVICE,
1724 ServiceManager.getService(Context.ALARM_SERVICE));
1725 }
1726 return mAppBindArgs;
1727 }
1728
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 if (mFocusedActivity != r) {
1731 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001732 if (r != null) {
1733 mWindowManager.setFocusedApp(r.appToken, true);
1734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 }
1736 }
1737
Dianne Hackborn906497c2010-05-10 15:57:38 -07001738 private final void updateLruProcessInternalLocked(ProcessRecord app,
1739 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001741 int lrui = mLruProcesses.indexOf(app);
1742 if (lrui >= 0) mLruProcesses.remove(lrui);
1743
1744 int i = mLruProcesses.size()-1;
1745 int skipTop = 0;
1746
Dianne Hackborn906497c2010-05-10 15:57:38 -07001747 app.lruSeq = mLruSeq;
1748
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001749 // compute the new weight for this process.
1750 if (updateActivityTime) {
1751 app.lastActivityTime = SystemClock.uptimeMillis();
1752 }
1753 if (app.activities.size() > 0) {
1754 // If this process has activities, we more strongly want to keep
1755 // it around.
1756 app.lruWeight = app.lastActivityTime;
1757 } else if (app.pubProviders.size() > 0) {
1758 // If this process contains content providers, we want to keep
1759 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001760 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001761 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001762 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001763 } else {
1764 // If this process doesn't have activities, we less strongly
1765 // want to keep it around, and generally want to avoid getting
1766 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001767 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001768 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001769 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001770 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001771
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001772 while (i >= 0) {
1773 ProcessRecord p = mLruProcesses.get(i);
1774 // If this app shouldn't be in front of the first N background
1775 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001776 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001777 skipTop--;
1778 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001779 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001780 mLruProcesses.add(i+1, app);
1781 break;
1782 }
1783 i--;
1784 }
1785 if (i < 0) {
1786 mLruProcesses.add(0, app);
1787 }
1788
Dianne Hackborn906497c2010-05-10 15:57:38 -07001789 // If the app is currently using a content provider or service,
1790 // bump those processes as well.
1791 if (app.connections.size() > 0) {
1792 for (ConnectionRecord cr : app.connections) {
1793 if (cr.binding != null && cr.binding.service != null
1794 && cr.binding.service.app != null
1795 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001796 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001797 updateActivityTime, i+1);
1798 }
1799 }
1800 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001801 for (int j=app.conProviders.size()-1; j>=0; j--) {
1802 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1803 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001804 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001805 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001806 }
1807 }
1808
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 if (oomAdj) {
1811 updateOomAdjLocked();
1812 }
1813 }
1814
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001816 boolean oomAdj, boolean updateActivityTime) {
1817 mLruSeq++;
1818 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1819 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001823 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001824 // The system gets to run in any process. If there are multiple
1825 // processes with the same uid, just pick the first (this
1826 // should never happen).
1827 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1828 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001829 if (procs == null) return null;
1830 final int N = procs.size();
1831 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001832 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
1835 ProcessRecord proc = mProcessNames.get(processName, uid);
1836 return proc;
1837 }
1838
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001839 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001840 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001841 try {
1842 if (pm.performDexOpt(packageName)) {
1843 mDidDexOpt = true;
1844 }
1845 } catch (RemoteException e) {
1846 }
1847 }
1848
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001849 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 int transit = mWindowManager.getPendingAppTransition();
1851 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1852 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1853 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1854 }
1855
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001856 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001858 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1859 boolean isolated) {
1860 ProcessRecord app;
1861 if (!isolated) {
1862 app = getProcessRecordLocked(processName, info.uid);
1863 } else {
1864 // If this is an isolated process, it can't re-use an existing process.
1865 app = null;
1866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 // We don't have to do anything more if:
1868 // (1) There is an existing application record; and
1869 // (2) The caller doesn't think it is dead, OR there is no thread
1870 // object attached to it so we know it couldn't have crashed; and
1871 // (3) There is a pid assigned to it, so it is either starting or
1872 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001873 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 + " app=" + app + " knownToBeDead=" + knownToBeDead
1875 + " thread=" + (app != null ? app.thread : null)
1876 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001877 if (app != null && app.pid > 0) {
1878 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001879 // We already have the app running, or are waiting for it to
1880 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001881 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001882 // If this is a new package in the process, add the package to the list
1883 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001884 return app;
1885 } else {
1886 // An application record is attached to a previous process,
1887 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001888 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001889 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 String hostingNameStr = hostingName != null
1894 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001895
1896 if (!isolated) {
1897 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1898 // If we are in the background, then check to see if this process
1899 // is bad. If so, we will just silently fail.
1900 if (mBadProcesses.get(info.processName, info.uid) != null) {
1901 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1902 + "/" + info.processName);
1903 return null;
1904 }
1905 } else {
1906 // When the user is explicitly starting a process, then clear its
1907 // crash count so that we won't make it bad until they see at
1908 // least one crash dialog again, and make the process good again
1909 // if it had been bad.
1910 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001911 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001912 mProcessCrashTimes.remove(info.processName, info.uid);
1913 if (mBadProcesses.get(info.processName, info.uid) != null) {
1914 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1915 info.processName);
1916 mBadProcesses.remove(info.processName, info.uid);
1917 if (app != null) {
1918 app.bad = false;
1919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921 }
1922 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001925 app = newProcessRecordLocked(null, info, processName, isolated);
1926 if (app == null) {
1927 Slog.w(TAG, "Failed making new process record for "
1928 + processName + "/" + info.uid + " isolated=" + isolated);
1929 return null;
1930 }
1931 mProcessNames.put(processName, app.uid, app);
1932 if (isolated) {
1933 mIsolatedProcesses.put(app.uid, app);
1934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 } else {
1936 // If this is a new package in the process, add the package to the list
1937 app.addPackage(info.packageName);
1938 }
1939
1940 // If the system is not ready yet, then hold off on starting this
1941 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001942 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001943 && !isAllowedWhileBooting(info)
1944 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 if (!mProcessesOnHold.contains(app)) {
1946 mProcessesOnHold.add(app);
1947 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001948 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 return app;
1950 }
1951
1952 startProcessLocked(app, hostingType, hostingNameStr);
1953 return (app.pid != 0) ? app : null;
1954 }
1955
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001956 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1957 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 private final void startProcessLocked(ProcessRecord app,
1961 String hostingType, String hostingNameStr) {
1962 if (app.pid > 0 && app.pid != MY_PID) {
1963 synchronized (mPidsSelfLocked) {
1964 mPidsSelfLocked.remove(app.pid);
1965 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1966 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001967 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
1969
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001970 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1971 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 mProcessesOnHold.remove(app);
1973
1974 updateCpuStats();
1975
1976 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1977 mProcDeaths[0] = 0;
1978
1979 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001980 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001983 if (!app.isolated) {
1984 try {
1985 gids = mContext.getPackageManager().getPackageGids(
1986 app.info.packageName);
1987 } catch (PackageManager.NameNotFoundException e) {
1988 Slog.w(TAG, "Unable to retrieve gids", e);
1989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1992 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1993 && mTopComponent != null
1994 && app.processName.equals(mTopComponent.getPackageName())) {
1995 uid = 0;
1996 }
1997 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1998 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1999 uid = 0;
2000 }
2001 }
2002 int debugFlags = 0;
2003 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2004 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002005 // Also turn on CheckJNI for debuggable apps. It's quite
2006 // awkward to turn on otherwise.
2007 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002008 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002009 // Run the app in safe mode if its manifest requests so or the
2010 // system is booted in safe mode.
2011 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2012 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002013 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2016 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2017 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002018 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2019 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 if ("1".equals(SystemProperties.get("debug.assert"))) {
2022 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2023 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002024
2025 // Start the process. It will either succeed and return a result containing
2026 // the PID of the new process, or else throw a RuntimeException.
2027 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002028 app.processName, uid, uid, gids, debugFlags,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002029 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2032 synchronized (bs) {
2033 if (bs.isOnBattery()) {
2034 app.batteryStats.incStartsLocked();
2035 }
2036 }
2037
Jeff Brown3f9dd282011-07-08 20:02:19 -07002038 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 app.processName, hostingType,
2040 hostingNameStr != null ? hostingNameStr : "");
2041
2042 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002043 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002046 StringBuilder buf = mStringBuilder;
2047 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 buf.append("Start proc ");
2049 buf.append(app.processName);
2050 buf.append(" for ");
2051 buf.append(hostingType);
2052 if (hostingNameStr != null) {
2053 buf.append(" ");
2054 buf.append(hostingNameStr);
2055 }
2056 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002057 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 buf.append(" uid=");
2059 buf.append(uid);
2060 buf.append(" gids={");
2061 if (gids != null) {
2062 for (int gi=0; gi<gids.length; gi++) {
2063 if (gi != 0) buf.append(", ");
2064 buf.append(gids[gi]);
2065
2066 }
2067 }
2068 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002069 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002070 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002071 app.usingWrapper = startResult.usingWrapper;
2072 app.removed = false;
2073 synchronized (mPidsSelfLocked) {
2074 this.mPidsSelfLocked.put(startResult.pid, app);
2075 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2076 msg.obj = app;
2077 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2078 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 } catch (RuntimeException e) {
2081 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002082 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002083 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002084 }
2085 }
2086
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002087 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 if (resumed) {
2089 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2090 } else {
2091 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2092 }
2093 }
2094
Amith Yamasani742a6712011-05-04 14:49:28 -07002095 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002096 if (mHeadless) {
2097 // Added because none of the other calls to ensureBootCompleted seem to fire
2098 // when running headless.
2099 ensureBootCompleted();
2100 return false;
2101 }
2102
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2104 && mTopAction == null) {
2105 // We are running in factory test mode, but unable to find
2106 // the factory test app, so just sit around displaying the
2107 // error message and don't try to start anything.
2108 return false;
2109 }
2110 Intent intent = new Intent(
2111 mTopAction,
2112 mTopData != null ? Uri.parse(mTopData) : null);
2113 intent.setComponent(mTopComponent);
2114 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2115 intent.addCategory(Intent.CATEGORY_HOME);
2116 }
2117 ActivityInfo aInfo =
2118 intent.resolveActivityInfo(mContext.getPackageManager(),
2119 STOCK_PM_FLAGS);
2120 if (aInfo != null) {
2121 intent.setComponent(new ComponentName(
2122 aInfo.applicationInfo.packageName, aInfo.name));
2123 // Don't do this if the home app is currently being
2124 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002125 aInfo = new ActivityInfo(aInfo);
2126 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002127 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2128 aInfo.applicationInfo.uid);
2129 if (app == null || app.instrumentationClass == null) {
2130 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002131 mMainStack.startActivityLocked(null, intent, null, aInfo,
2132 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002133 }
2134 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002135
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002136 return true;
2137 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002138
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002139 /**
2140 * Starts the "new version setup screen" if appropriate.
2141 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002142 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002143 // Only do this once per boot.
2144 if (mCheckedForSetup) {
2145 return;
2146 }
2147
2148 // We will show this screen if the current one is a different
2149 // version than the last one shown, and we are not running in
2150 // low-level factory test mode.
2151 final ContentResolver resolver = mContext.getContentResolver();
2152 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2153 Settings.Secure.getInt(resolver,
2154 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2155 mCheckedForSetup = true;
2156
2157 // See if we should be showing the platform update setup UI.
2158 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2159 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2160 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2161
2162 // We don't allow third party apps to replace this.
2163 ResolveInfo ri = null;
2164 for (int i=0; ris != null && i<ris.size(); i++) {
2165 if ((ris.get(i).activityInfo.applicationInfo.flags
2166 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2167 ri = ris.get(i);
2168 break;
2169 }
2170 }
2171
2172 if (ri != null) {
2173 String vers = ri.activityInfo.metaData != null
2174 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2175 : null;
2176 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2177 vers = ri.activityInfo.applicationInfo.metaData.getString(
2178 Intent.METADATA_SETUP_VERSION);
2179 }
2180 String lastVers = Settings.Secure.getString(
2181 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2182 if (vers != null && !vers.equals(lastVers)) {
2183 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2184 intent.setComponent(new ComponentName(
2185 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002186 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2187 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002188 }
2189 }
2190 }
2191 }
2192
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002195 }
2196
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002197 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002198 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002199 throw new SecurityException("Isolated process not allowed to call " + caller);
2200 }
2201 }
2202
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002203 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002204 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002205 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002206 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2207 }
2208 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002209
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002210 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002211 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2212 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002213 synchronized (this) {
2214 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2215 }
2216 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002217
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002218 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002219 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002220 synchronized (this) {
2221 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2222 }
2223 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002224
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002225 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002226 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2227 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002228 synchronized (this) {
2229 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002230 }
2231 }
2232
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002233 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002234 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002235 synchronized (this) {
2236 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2237 }
2238 }
2239
2240 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002241 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2242 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002243 synchronized (this) {
2244 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2245 }
2246 }
2247
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002248 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002249 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002250 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002253 private void dispatchProcessesChanged() {
2254 int N;
2255 synchronized (this) {
2256 N = mPendingProcessChanges.size();
2257 if (mActiveProcessChanges.length < N) {
2258 mActiveProcessChanges = new ProcessChangeItem[N];
2259 }
2260 mPendingProcessChanges.toArray(mActiveProcessChanges);
2261 mAvailProcessChanges.addAll(mPendingProcessChanges);
2262 mPendingProcessChanges.clear();
2263 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2264 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002265 int i = mProcessObservers.beginBroadcast();
2266 while (i > 0) {
2267 i--;
2268 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2269 if (observer != null) {
2270 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002271 for (int j=0; j<N; j++) {
2272 ProcessChangeItem item = mActiveProcessChanges[j];
2273 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2274 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2275 + item.pid + " uid=" + item.uid + ": "
2276 + item.foregroundActivities);
2277 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2278 item.foregroundActivities);
2279 }
2280 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2281 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2282 + item.pid + " uid=" + item.uid + ": " + item.importance);
2283 observer.onImportanceChanged(item.pid, item.uid,
2284 item.importance);
2285 }
2286 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002287 } catch (RemoteException e) {
2288 }
2289 }
2290 }
2291 mProcessObservers.finishBroadcast();
2292 }
2293
2294 private void dispatchProcessDied(int pid, int uid) {
2295 int i = mProcessObservers.beginBroadcast();
2296 while (i > 0) {
2297 i--;
2298 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2299 if (observer != null) {
2300 try {
2301 observer.onProcessDied(pid, uid);
2302 } catch (RemoteException e) {
2303 }
2304 }
2305 }
2306 mProcessObservers.finishBroadcast();
2307 }
2308
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002309 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002310 final int N = mPendingActivityLaunches.size();
2311 if (N <= 0) {
2312 return;
2313 }
2314 for (int i=0; i<N; i++) {
2315 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002316 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002317 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002318 }
2319 mPendingActivityLaunches.clear();
2320 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002321
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002322 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002323 Intent intent, String resolvedType, IBinder resultTo,
2324 String resultWho, int requestCode, int startFlags,
2325 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002326 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002327 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002328 }
2329
2330 public final int startActivityAsUser(IApplicationThread caller,
2331 Intent intent, String resolvedType, IBinder resultTo,
2332 String resultWho, int requestCode, int startFlags,
2333 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002334 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002335 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07002336 // Requesting a different user, make sure that they have the permission
2337 if (checkComponentPermission(
2338 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2339 Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
2340 == PackageManager.PERMISSION_GRANTED) {
2341 // Translate to the current user id, if caller wasn't aware
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002342 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07002343 userId = mCurrentUserId;
2344 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002345 } else {
Amith Yamasani82644082012-08-03 13:09:11 -07002346 String msg = "Permission Denial: "
2347 + "Request to startActivity as user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002348 + " but is calling from user " + UserHandle.getCallingUserId()
Amith Yamasani82644082012-08-03 13:09:11 -07002349 + "; this requires "
2350 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
2351 Slog.w(TAG, msg);
2352 throw new SecurityException(msg);
2353 }
2354 } else {
2355 if (intent.getCategories() != null
2356 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2357 // Requesting home, set the identity to the current user
2358 // HACK!
2359 userId = mCurrentUserId;
2360 } else {
2361 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2362 // the current user's userId
2363 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2364 userId = 0;
2365 } else {
2366 userId = Binder.getOrigCallingUser();
2367 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002368 }
2369 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002370 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002371 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2372 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002373 }
2374
2375 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002376 Intent intent, String resolvedType, IBinder resultTo,
2377 String resultWho, int requestCode, int startFlags, String profileFile,
2378 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002379 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002380 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002381 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002382 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002383 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2384 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002385 return res;
2386 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002387
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002388 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002389 Intent intent, String resolvedType, IBinder resultTo,
2390 String resultWho, int requestCode, int startFlags, Configuration config,
2391 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002392 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002393 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002394 resultTo, resultWho, requestCode, startFlags,
2395 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002396 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002397 }
2398
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002400 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002401 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002402 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002403 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002404 // Refuse possible leaked file descriptors
2405 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2406 throw new IllegalArgumentException("File descriptors passed in Intent");
2407 }
2408
2409 IIntentSender sender = intent.getTarget();
2410 if (!(sender instanceof PendingIntentRecord)) {
2411 throw new IllegalArgumentException("Bad PendingIntent object");
2412 }
2413
2414 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002415
2416 synchronized (this) {
2417 // If this is coming from the currently resumed activity, it is
2418 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002419 if (mMainStack.mResumedActivity != null
2420 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002421 Binder.getCallingUid()) {
2422 mAppSwitchesAllowedTime = 0;
2423 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002424 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002425 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2426 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002427 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002428 }
2429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002431 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 // Refuse possible leaked file descriptors
2433 if (intent != null && intent.hasFileDescriptors() == true) {
2434 throw new IllegalArgumentException("File descriptors passed in Intent");
2435 }
2436
2437 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002438 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2439 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002440 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 return false;
2442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 if (r.app == null || r.app.thread == null) {
2444 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002445 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 return false;
2447 }
2448 intent = new Intent(intent);
2449 // The caller is not allowed to change the data.
2450 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2451 // And we are resetting to find the next component...
2452 intent.setComponent(null);
2453
2454 ActivityInfo aInfo = null;
2455 try {
2456 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002457 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002459 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002460 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461
2462 // Look for the original activity in the list...
2463 final int N = resolves != null ? resolves.size() : 0;
2464 for (int i=0; i<N; i++) {
2465 ResolveInfo rInfo = resolves.get(i);
2466 if (rInfo.activityInfo.packageName.equals(r.packageName)
2467 && rInfo.activityInfo.name.equals(r.info.name)) {
2468 // We found the current one... the next matching is
2469 // after it.
2470 i++;
2471 if (i<N) {
2472 aInfo = resolves.get(i).activityInfo;
2473 }
2474 break;
2475 }
2476 }
2477 } catch (RemoteException e) {
2478 }
2479
2480 if (aInfo == null) {
2481 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002482 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002483 return false;
2484 }
2485
2486 intent.setComponent(new ComponentName(
2487 aInfo.applicationInfo.packageName, aInfo.name));
2488 intent.setFlags(intent.getFlags()&~(
2489 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2490 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2491 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2492 Intent.FLAG_ACTIVITY_NEW_TASK));
2493
2494 // Okay now we need to start the new activity, replacing the
2495 // currently running activity. This is a little tricky because
2496 // we want to start the new one as if the current one is finished,
2497 // but not finish the current one first so that there is no flicker.
2498 // And thus...
2499 final boolean wasFinishing = r.finishing;
2500 r.finishing = true;
2501
2502 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002503 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 final String resultWho = r.resultWho;
2505 final int requestCode = r.requestCode;
2506 r.resultTo = null;
2507 if (resultTo != null) {
2508 resultTo.removeResultsLocked(r, resultWho, requestCode);
2509 }
2510
2511 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002512 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002513 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2514 resultWho, requestCode, -1, r.launchedFromUid, 0,
2515 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 Binder.restoreCallingIdentity(origId);
2517
2518 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002519 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 return false;
2521 }
2522 return true;
2523 }
2524 }
2525
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002526 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002529
2530 // This is so super not safe, that only the system (or okay root)
2531 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002532 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002533 final int callingUid = Binder.getCallingUid();
2534 if (callingUid != 0 && callingUid != Process.myUid()) {
2535 throw new SecurityException(
2536 "startActivityInPackage only available to the system");
2537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538
Amith Yamasani742a6712011-05-04 14:49:28 -07002539 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002540 resultTo, resultWho, requestCode, startFlags,
2541 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002542 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002543 }
2544
2545 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002546 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002547 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002548 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002550 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002551 }
2552
2553 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002554 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2555 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002556
2557 // This is so super not safe, that only the system (or okay root)
2558 // can do it.
2559 final int callingUid = Binder.getCallingUid();
2560 if (callingUid != 0 && callingUid != Process.myUid()) {
2561 throw new SecurityException(
2562 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002564 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002565 options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002566 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002569 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002571 // Quick case: check if the top-most recent task is the same.
2572 if (N > 0 && mRecentTasks.get(0) == task) {
2573 return;
2574 }
2575 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 for (int i=0; i<N; i++) {
2577 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002578 if (task.userId == tr.userId
2579 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2580 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 mRecentTasks.remove(i);
2582 i--;
2583 N--;
2584 if (task.intent == null) {
2585 // If the new recent task we are adding is not fully
2586 // specified, then replace it with the existing recent task.
2587 task = tr;
2588 }
2589 }
2590 }
2591 if (N >= MAX_RECENT_TASKS) {
2592 mRecentTasks.remove(N-1);
2593 }
2594 mRecentTasks.add(0, task);
2595 }
2596
2597 public void setRequestedOrientation(IBinder token,
2598 int requestedOrientation) {
2599 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002600 ActivityRecord r = mMainStack.isInStackLocked(token);
2601 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 return;
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002605 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002607 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002608 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 if (config != null) {
2610 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002611 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002612 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 }
2614 }
2615 Binder.restoreCallingIdentity(origId);
2616 }
2617 }
2618
2619 public int getRequestedOrientation(IBinder token) {
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 ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2624 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002625 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
2628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 /**
2630 * This is the internal entry point for handling Activity.finish().
2631 *
2632 * @param token The Binder token referencing the Activity we want to finish.
2633 * @param resultCode Result code, if any, from this Activity.
2634 * @param resultData Result data (Intent), if any, from this Activity.
2635 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002636 * @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 -08002637 */
2638 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2639 // Refuse possible leaked file descriptors
2640 if (resultData != null && resultData.hasFileDescriptors() == true) {
2641 throw new IllegalArgumentException("File descriptors passed in Intent");
2642 }
2643
2644 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002645 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002647 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 if (next != null) {
2649 // ask watcher if this is allowed
2650 boolean resumeOK = true;
2651 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002652 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002654 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002655 }
2656
2657 if (!resumeOK) {
2658 return false;
2659 }
2660 }
2661 }
2662 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 resultData, "app-request");
2665 Binder.restoreCallingIdentity(origId);
2666 return res;
2667 }
2668 }
2669
Dianne Hackborn860755f2010-06-03 18:47:52 -07002670 public final void finishHeavyWeightApp() {
2671 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2672 != PackageManager.PERMISSION_GRANTED) {
2673 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2674 + Binder.getCallingPid()
2675 + ", uid=" + Binder.getCallingUid()
2676 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2677 Slog.w(TAG, msg);
2678 throw new SecurityException(msg);
2679 }
2680
2681 synchronized(this) {
2682 if (mHeavyWeightProcess == null) {
2683 return;
2684 }
2685
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002686 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002687 mHeavyWeightProcess.activities);
2688 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002689 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002690 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002691 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002692 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002693 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002694 null, "finish-heavy");
2695 }
2696 }
2697 }
2698
2699 mHeavyWeightProcess = null;
2700 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2701 }
2702 }
2703
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002704 public void crashApplication(int uid, int initialPid, String packageName,
2705 String message) {
2706 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2707 != PackageManager.PERMISSION_GRANTED) {
2708 String msg = "Permission Denial: crashApplication() from pid="
2709 + Binder.getCallingPid()
2710 + ", uid=" + Binder.getCallingUid()
2711 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2712 Slog.w(TAG, msg);
2713 throw new SecurityException(msg);
2714 }
2715
2716 synchronized(this) {
2717 ProcessRecord proc = null;
2718
2719 // Figure out which process to kill. We don't trust that initialPid
2720 // still has any relation to current pids, so must scan through the
2721 // list.
2722 synchronized (mPidsSelfLocked) {
2723 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2724 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002725 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002726 continue;
2727 }
2728 if (p.pid == initialPid) {
2729 proc = p;
2730 break;
2731 }
2732 for (String str : p.pkgList) {
2733 if (str.equals(packageName)) {
2734 proc = p;
2735 }
2736 }
2737 }
2738 }
2739
2740 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002741 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002742 + " initialPid=" + initialPid
2743 + " packageName=" + packageName);
2744 return;
2745 }
2746
2747 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002748 if (proc.pid == Process.myPid()) {
2749 Log.w(TAG, "crashApplication: trying to crash self!");
2750 return;
2751 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002752 long ident = Binder.clearCallingIdentity();
2753 try {
2754 proc.thread.scheduleCrash(message);
2755 } catch (RemoteException e) {
2756 }
2757 Binder.restoreCallingIdentity(ident);
2758 }
2759 }
2760 }
2761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 public final void finishSubActivity(IBinder token, String resultWho,
2763 int requestCode) {
2764 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002766 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 Binder.restoreCallingIdentity(origId);
2768 }
2769 }
2770
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002771 public boolean finishActivityAffinity(IBinder token) {
2772 synchronized(this) {
2773 final long origId = Binder.clearCallingIdentity();
2774 boolean res = mMainStack.finishActivityAffinityLocked(token);
2775 Binder.restoreCallingIdentity(origId);
2776 return res;
2777 }
2778 }
2779
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002780 public boolean willActivityBeVisible(IBinder token) {
2781 synchronized(this) {
2782 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2784 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002785 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002786 return true;
2787 }
2788 if (r.fullscreen && !r.finishing) {
2789 return false;
2790 }
2791 }
2792 return true;
2793 }
2794 }
2795
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002796 public void overridePendingTransition(IBinder token, String packageName,
2797 int enterAnim, int exitAnim) {
2798 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002799 ActivityRecord self = mMainStack.isInStackLocked(token);
2800 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002801 return;
2802 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002803
2804 final long origId = Binder.clearCallingIdentity();
2805
2806 if (self.state == ActivityState.RESUMED
2807 || self.state == ActivityState.PAUSING) {
2808 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002809 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002810 }
2811
2812 Binder.restoreCallingIdentity(origId);
2813 }
2814 }
2815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 * Main function for removing an existing process from the activity manager
2818 * as a result of that process going away. Clears out all connections
2819 * to the process.
2820 */
2821 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002822 boolean restarting, boolean allowRestart) {
2823 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002825 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002828 if (mProfileProc == app) {
2829 clearProfilerLocked();
2830 }
2831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002833 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2834 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2835 mMainStack.mPausingActivity = null;
2836 }
2837 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2838 mMainStack.mLastPausedActivity = null;
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840
2841 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002842 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843
2844 boolean atTop = true;
2845 boolean hasVisibleActivities = false;
2846
2847 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002848 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002849 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 TAG, "Removing app " + app + " from history with " + i + " entries");
2851 while (i > 0) {
2852 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002853 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002854 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2856 if (r.app == app) {
2857 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002858 if (ActivityStack.DEBUG_ADD_REMOVE) {
2859 RuntimeException here = new RuntimeException("here");
2860 here.fillInStackTrace();
2861 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2862 + ": haveState=" + r.haveState
2863 + " stateNotNeeded=" + r.stateNotNeeded
2864 + " finishing=" + r.finishing
2865 + " state=" + r.state, here);
2866 }
2867 if (!r.finishing) {
2868 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002869 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2870 System.identityHashCode(r),
2871 r.task.taskId, r.shortComponentName,
2872 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002873 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002874 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875
2876 } else {
2877 // We have the current state for this activity, so
2878 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002879 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 TAG, "Keeping entry, setting app to null");
2881 if (r.visible) {
2882 hasVisibleActivities = true;
2883 }
2884 r.app = null;
2885 r.nowVisible = false;
2886 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002887 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2888 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 r.icicle = null;
2890 }
2891 }
2892
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002893 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 }
2895 atTop = false;
2896 }
2897
2898 app.activities.clear();
2899
2900 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002901 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 + " running instrumentation " + app.instrumentationClass);
2903 Bundle info = new Bundle();
2904 info.putString("shortMsg", "Process crashed.");
2905 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2906 }
2907
2908 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002909 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 // If there was nothing to resume, and we are not already
2911 // restarting this process, but there is a visible activity that
2912 // is hosted by the process... then make sure all visible
2913 // activities are running, taking care of restarting this
2914 // process.
2915 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002916 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 }
2918 }
2919 }
2920 }
2921
2922 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2923 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002925 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2926 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2928 return i;
2929 }
2930 }
2931 return -1;
2932 }
2933
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002934 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 IApplicationThread thread) {
2936 if (thread == null) {
2937 return null;
2938 }
2939
2940 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002941 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002944 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 IApplicationThread thread) {
2946
2947 mProcDeaths[0]++;
2948
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002949 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2950 synchronized (stats) {
2951 stats.noteProcessDiedLocked(app.info.uid, pid);
2952 }
2953
Magnus Edlund7bb25812010-02-24 15:45:06 +01002954 // Clean up already done if the process has been re-started.
2955 if (app.pid == pid && app.thread != null &&
2956 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002957 if (!app.killedBackground) {
2958 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2959 + ") has died.");
2960 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002961 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002962 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 TAG, "Dying app: " + app + ", pid: " + pid
2964 + ", thread: " + thread.asBinder());
2965 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002966 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967
2968 if (doLowMem) {
2969 // If there are no longer any background processes running,
2970 // and the app that died was not running instrumentation,
2971 // then tell everyone we are now low on memory.
2972 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002973 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2974 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002975 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 haveBg = true;
2977 break;
2978 }
2979 }
2980
2981 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002982 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002983 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002984 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2985 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002986 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002987 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2988 // The low memory report is overriding any current
2989 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002990 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002991 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002992 rec.lastRequestedGc = 0;
2993 } else {
2994 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002996 rec.reportLowMemory = true;
2997 rec.lastLowMemory = now;
2998 mProcessesToGc.remove(rec);
2999 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
3001 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003002 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003003 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 }
3005 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003006 } else if (app.pid != pid) {
3007 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003008 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003009 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003010 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003011 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003012 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 + thread.asBinder());
3014 }
3015 }
3016
Dan Egnor42471dd2010-01-07 17:25:22 -08003017 /**
3018 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003019 * @param clearTraces causes the dump file to be erased prior to the new
3020 * traces being written, if true; when false, the new traces will be
3021 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003022 * @param firstPids of dalvik VM processes to dump stack traces for first
3023 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003024 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003025 * @return file containing stack traces, or null if no dump file is configured
3026 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003027 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003028 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003029 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3030 if (tracesPath == null || tracesPath.length() == 0) {
3031 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003033
3034 File tracesFile = new File(tracesPath);
3035 try {
3036 File tracesDir = tracesFile.getParentFile();
3037 if (!tracesDir.exists()) tracesFile.mkdirs();
3038 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3039
Christopher Tate6ee412d2010-05-28 12:01:56 -07003040 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003041 tracesFile.createNewFile();
3042 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3043 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003044 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003045 return null;
3046 }
3047
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003048 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003049 return tracesFile;
3050 }
3051
3052 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003053 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003054 // Use a FileObserver to detect when traces finish writing.
3055 // The order of traces is considered important to maintain for legibility.
3056 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3057 public synchronized void onEvent(int event, String path) { notify(); }
3058 };
3059
3060 try {
3061 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003062
3063 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003064 if (firstPids != null) {
3065 try {
3066 int num = firstPids.size();
3067 for (int i = 0; i < num; i++) {
3068 synchronized (observer) {
3069 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3070 observer.wait(200); // Wait for write-close, give up after 200msec
3071 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003073 } catch (InterruptedException e) {
3074 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003076 }
3077
3078 // Next measure CPU usage.
3079 if (processStats != null) {
3080 processStats.init();
3081 System.gc();
3082 processStats.update();
3083 try {
3084 synchronized (processStats) {
3085 processStats.wait(500); // measure over 1/2 second.
3086 }
3087 } catch (InterruptedException e) {
3088 }
3089 processStats.update();
3090
3091 // We'll take the stack crawls of just the top apps using CPU.
3092 final int N = processStats.countWorkingStats();
3093 int numProcs = 0;
3094 for (int i=0; i<N && numProcs<5; i++) {
3095 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3096 if (lastPids.indexOfKey(stats.pid) >= 0) {
3097 numProcs++;
3098 try {
3099 synchronized (observer) {
3100 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3101 observer.wait(200); // Wait for write-close, give up after 200msec
3102 }
3103 } catch (InterruptedException e) {
3104 Log.wtf(TAG, e);
3105 }
3106
3107 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003108 }
3109 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003110
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 } finally {
3112 observer.stopWatching();
3113 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003114
3115 if (nativeProcs != null) {
3116 int[] pids = Process.getPidsForCommands(nativeProcs);
3117 if (pids != null) {
3118 for (int pid : pids) {
3119 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3120 }
3121 }
3122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 }
3124
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003125 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003126 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003127 return;
3128 }
3129 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3130 if (tracesPath == null || tracesPath.length() == 0) {
3131 return;
3132 }
3133
3134 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3135 StrictMode.allowThreadDiskWrites();
3136 try {
3137 final File tracesFile = new File(tracesPath);
3138 final File tracesDir = tracesFile.getParentFile();
3139 final File tracesTmp = new File(tracesDir, "__tmp__");
3140 try {
3141 if (!tracesDir.exists()) tracesFile.mkdirs();
3142 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3143
3144 if (tracesFile.exists()) {
3145 tracesTmp.delete();
3146 tracesFile.renameTo(tracesTmp);
3147 }
3148 StringBuilder sb = new StringBuilder();
3149 Time tobj = new Time();
3150 tobj.set(System.currentTimeMillis());
3151 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3152 sb.append(": ");
3153 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3154 sb.append(" since ");
3155 sb.append(msg);
3156 FileOutputStream fos = new FileOutputStream(tracesFile);
3157 fos.write(sb.toString().getBytes());
3158 if (app == null) {
3159 fos.write("\n*** No application process!".getBytes());
3160 }
3161 fos.close();
3162 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3163 } catch (IOException e) {
3164 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3165 return;
3166 }
3167
3168 if (app != null) {
3169 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3170 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003171 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003172 }
3173
3174 File lastTracesFile = null;
3175 File curTracesFile = null;
3176 for (int i=9; i>=0; i--) {
3177 String name = String.format("slow%02d.txt", i);
3178 curTracesFile = new File(tracesDir, name);
3179 if (curTracesFile.exists()) {
3180 if (lastTracesFile != null) {
3181 curTracesFile.renameTo(lastTracesFile);
3182 } else {
3183 curTracesFile.delete();
3184 }
3185 }
3186 lastTracesFile = curTracesFile;
3187 }
3188 tracesFile.renameTo(curTracesFile);
3189 if (tracesTmp.exists()) {
3190 tracesTmp.renameTo(tracesFile);
3191 }
3192 } finally {
3193 StrictMode.setThreadPolicy(oldPolicy);
3194 }
3195 }
3196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003197 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3198 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003199 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3200 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3201
Dianne Hackborn287952c2010-09-22 22:34:31 -07003202 if (mController != null) {
3203 try {
3204 // 0 == continue, -1 = kill process immediately
3205 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3206 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3207 } catch (RemoteException e) {
3208 mController = null;
3209 }
3210 }
3211
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003212 long anrTime = SystemClock.uptimeMillis();
3213 if (MONITOR_CPU_USAGE) {
3214 updateCpuStatsNow();
3215 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003216
3217 synchronized (this) {
3218 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3219 if (mShuttingDown) {
3220 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3221 return;
3222 } else if (app.notResponding) {
3223 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3224 return;
3225 } else if (app.crashing) {
3226 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3227 return;
3228 }
3229
3230 // In case we come through here for the same app before completing
3231 // this one, mark as anring now so we will bail out.
3232 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003233
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003234 // Log the ANR to the event log.
3235 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3236 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003237
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003238 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003239 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003240
3241 int parentPid = app.pid;
3242 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003243 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003244
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003245 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003246
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003247 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3248 ProcessRecord r = mLruProcesses.get(i);
3249 if (r != null && r.thread != null) {
3250 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003251 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3252 if (r.persistent) {
3253 firstPids.add(pid);
3254 } else {
3255 lastPids.put(pid, Boolean.TRUE);
3256 }
3257 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003259 }
3260 }
3261
Dan Egnor42471dd2010-01-07 17:25:22 -08003262 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003263 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003264 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003265 info.append("ANR in ").append(app.processName);
3266 if (activity != null && activity.shortComponentName != null) {
3267 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003268 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003269 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003271 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003273 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003274 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276
Dianne Hackborn287952c2010-09-22 22:34:31 -07003277 final ProcessStats processStats = new ProcessStats(true);
3278
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003279 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003280
Dan Egnor42471dd2010-01-07 17:25:22 -08003281 String cpuInfo = null;
3282 if (MONITOR_CPU_USAGE) {
3283 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003284 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003285 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003286 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003287 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003288 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
3290
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003291 info.append(processStats.printCurrentState(anrTime));
3292
Joe Onorato8a9b2202010-02-26 18:56:32 -08003293 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003294 if (tracesFile == null) {
3295 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3296 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3297 }
3298
Jeff Sharkeya353d262011-10-28 11:12:06 -07003299 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3300 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003301
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003302 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003304 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3305 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003307 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3308 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 }
3310 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003311 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
3313 }
3314
Dan Egnor42471dd2010-01-07 17:25:22 -08003315 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3316 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3317 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003318
3319 synchronized (this) {
3320 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003321 Slog.w(TAG, "Killing " + app + ": background ANR");
3322 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3323 app.processName, app.setAdj, "background ANR");
3324 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003325 return;
3326 }
3327
3328 // Set the app's notResponding state, and look up the errorReportReceiver
3329 makeAppNotRespondingLocked(app,
3330 activity != null ? activity.shortComponentName : null,
3331 annotation != null ? "ANR " + annotation : "ANR",
3332 info.toString());
3333
3334 // Bring up the infamous App Not Responding dialog
3335 Message msg = Message.obtain();
3336 HashMap map = new HashMap();
3337 msg.what = SHOW_NOT_RESPONDING_MSG;
3338 msg.obj = map;
3339 map.put("app", app);
3340 if (activity != null) {
3341 map.put("activity", activity);
3342 }
3343
3344 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
3347
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003348 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3349 if (!mLaunchWarningShown) {
3350 mLaunchWarningShown = true;
3351 mHandler.post(new Runnable() {
3352 @Override
3353 public void run() {
3354 synchronized (ActivityManagerService.this) {
3355 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3356 d.show();
3357 mHandler.postDelayed(new Runnable() {
3358 @Override
3359 public void run() {
3360 synchronized (ActivityManagerService.this) {
3361 d.dismiss();
3362 mLaunchWarningShown = false;
3363 }
3364 }
3365 }, 4000);
3366 }
3367 }
3368 });
3369 }
3370 }
3371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003373 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003374 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 int uid = Binder.getCallingUid();
3376 int pid = Binder.getCallingPid();
3377 long callingId = Binder.clearCallingIdentity();
3378 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003379 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 int pkgUid = -1;
3381 synchronized(this) {
3382 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003383 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 } catch (RemoteException e) {
3385 }
3386 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003387 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 return false;
3389 }
3390 if (uid == pkgUid || checkComponentPermission(
3391 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003392 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003394 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 } else {
3396 throw new SecurityException(pid+" does not have permission:"+
3397 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3398 "for process:"+packageName);
3399 }
3400 }
3401
3402 try {
3403 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003404 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3406 Uri.fromParts("package", packageName, null));
3407 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003408 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003409 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 } catch (RemoteException e) {
3411 }
3412 } finally {
3413 Binder.restoreCallingIdentity(callingId);
3414 }
3415 return true;
3416 }
3417
Dianne Hackborn03abb812010-01-04 18:43:19 -08003418 public void killBackgroundProcesses(final String packageName) {
3419 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3420 != PackageManager.PERMISSION_GRANTED &&
3421 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3422 != PackageManager.PERMISSION_GRANTED) {
3423 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 + Binder.getCallingPid()
3425 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003426 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003427 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 throw new SecurityException(msg);
3429 }
3430
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003431 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 long callingId = Binder.clearCallingIdentity();
3433 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003434 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 int pkgUid = -1;
3436 synchronized(this) {
3437 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003438 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003439 } catch (RemoteException e) {
3440 }
3441 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003442 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 return;
3444 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003445 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003446 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3447 }
3448 } finally {
3449 Binder.restoreCallingIdentity(callingId);
3450 }
3451 }
3452
3453 public void killAllBackgroundProcesses() {
3454 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3455 != PackageManager.PERMISSION_GRANTED) {
3456 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3457 + Binder.getCallingPid()
3458 + ", uid=" + Binder.getCallingUid()
3459 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3460 Slog.w(TAG, msg);
3461 throw new SecurityException(msg);
3462 }
3463
3464 long callingId = Binder.clearCallingIdentity();
3465 try {
3466 synchronized(this) {
3467 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3468 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3469 final int NA = apps.size();
3470 for (int ia=0; ia<NA; ia++) {
3471 ProcessRecord app = apps.valueAt(ia);
3472 if (app.persistent) {
3473 // we don't kill persistent processes
3474 continue;
3475 }
3476 if (app.removed) {
3477 procs.add(app);
3478 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3479 app.removed = true;
3480 procs.add(app);
3481 }
3482 }
3483 }
3484
3485 int N = procs.size();
3486 for (int i=0; i<N; i++) {
3487 removeProcessLocked(procs.get(i), false, true, "kill all background");
3488 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003489 }
3490 } finally {
3491 Binder.restoreCallingIdentity(callingId);
3492 }
3493 }
3494
3495 public void forceStopPackage(final String packageName) {
3496 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3497 != PackageManager.PERMISSION_GRANTED) {
3498 String msg = "Permission Denial: forceStopPackage() from pid="
3499 + Binder.getCallingPid()
3500 + ", uid=" + Binder.getCallingUid()
3501 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003502 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003503 throw new SecurityException(msg);
3504 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003505 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003506 long callingId = Binder.clearCallingIdentity();
3507 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003508 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003509 int pkgUid = -1;
3510 synchronized(this) {
3511 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003512 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003513 } catch (RemoteException e) {
3514 }
3515 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003516 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003517 return;
3518 }
3519 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003520 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003521 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003522 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003523 } catch (IllegalArgumentException e) {
3524 Slog.w(TAG, "Failed trying to unstop package "
3525 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 }
3528 } finally {
3529 Binder.restoreCallingIdentity(callingId);
3530 }
3531 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003532
3533 /*
3534 * The pkg name and uid have to be specified.
3535 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3536 */
3537 public void killApplicationWithUid(String pkg, int uid) {
3538 if (pkg == null) {
3539 return;
3540 }
3541 // Make sure the uid is valid.
3542 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003543 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003544 return;
3545 }
3546 int callerUid = Binder.getCallingUid();
3547 // Only the system server can kill an application
3548 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003549 // Post an aysnc message to kill the application
3550 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3551 msg.arg1 = uid;
3552 msg.arg2 = 0;
3553 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003554 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003555 } else {
3556 throw new SecurityException(callerUid + " cannot kill pkg: " +
3557 pkg);
3558 }
3559 }
3560
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003561 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003562 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003563
3564 final int uid = Binder.getCallingUid();
3565 final long origId = Binder.clearCallingIdentity();
3566 synchronized (this) {
3567 closeSystemDialogsLocked(uid, reason);
3568 }
3569 Binder.restoreCallingIdentity(origId);
3570 }
3571
3572 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003573 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003574 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003575 if (reason != null) {
3576 intent.putExtra("reason", reason);
3577 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003578 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003579
Dianne Hackborne302a162012-05-15 14:58:32 -07003580 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3581 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003582 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003583 r.stack.finishActivityLocked(r, i,
3584 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003585 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003586 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003587
3588 broadcastIntentLocked(null, null, intent, null,
3589 null, 0, null, null, null, false, false, -1,
3590 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003591 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003592
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003593 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003594 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003595 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003596 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3597 for (int i=pids.length-1; i>=0; i--) {
3598 infos[i] = new Debug.MemoryInfo();
3599 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003600 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003601 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003602 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003603
Dianne Hackbornb437e092011-08-05 17:50:29 -07003604 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003605 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003606 long[] pss = new long[pids.length];
3607 for (int i=pids.length-1; i>=0; i--) {
3608 pss[i] = Debug.getPss(pids[i]);
3609 }
3610 return pss;
3611 }
3612
Christopher Tate5e1ab332009-09-01 20:32:49 -07003613 public void killApplicationProcess(String processName, int uid) {
3614 if (processName == null) {
3615 return;
3616 }
3617
3618 int callerUid = Binder.getCallingUid();
3619 // Only the system server can kill an application
3620 if (callerUid == Process.SYSTEM_UID) {
3621 synchronized (this) {
3622 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003623 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003624 try {
3625 app.thread.scheduleSuicide();
3626 } catch (RemoteException e) {
3627 // If the other end already died, then our work here is done.
3628 }
3629 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003630 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003631 + processName + " / " + uid);
3632 }
3633 }
3634 } else {
3635 throw new SecurityException(callerUid + " cannot kill app process: " +
3636 processName);
3637 }
3638 }
3639
Dianne Hackborn03abb812010-01-04 18:43:19 -08003640 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003641 forceStopPackageLocked(packageName, uid, false, false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3643 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003644 if (!mProcessesReady) {
3645 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 intent.putExtra(Intent.EXTRA_UID, uid);
3648 broadcastIntentLocked(null, null, intent,
3649 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003650 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003651 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 }
3653
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003654 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003655 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003656 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003657 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658
Dianne Hackborn03abb812010-01-04 18:43:19 -08003659 // Remove all processes this package may have touched: all with the
3660 // same UID (except for the system or root user), and all whose name
3661 // matches the package name.
3662 final String procNamePrefix = packageName + ":";
3663 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3664 final int NA = apps.size();
3665 for (int ia=0; ia<NA; ia++) {
3666 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003667 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003668 // we don't kill persistent processes
3669 continue;
3670 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003671 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003672 if (doit) {
3673 procs.add(app);
3674 }
Amith Yamasani13593602012-03-22 16:16:17 -07003675 // If uid is specified and the uid and process name match
3676 // Or, the uid is not specified and the process name matches
3677 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003678 || ((app.processName.equals(packageName)
3679 || app.processName.startsWith(procNamePrefix))
3680 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003681 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003682 if (!doit) {
3683 return true;
3684 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003685 app.removed = true;
3686 procs.add(app);
3687 }
3688 }
3689 }
3690 }
3691
3692 int N = procs.size();
3693 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003694 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003695 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003696 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003697 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003698
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003699 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003700 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003701 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003702 int i;
3703 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 if (uid < 0) {
3706 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003707 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 } catch (RemoteException e) {
3709 }
3710 }
3711
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003713 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003714
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003715 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3716 while (badApps.hasNext()) {
3717 SparseArray<Long> ba = badApps.next();
3718 if (ba.get(uid) != null) {
3719 badApps.remove();
3720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 }
3722 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003723
3724 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003725 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003727 TaskRecord lastTask = null;
3728 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003729 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003730 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003731 if (r.userId == userId
3732 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003733 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003734 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003735 if (r.finishing) {
3736 // If this activity is just finishing, then it is not
3737 // interesting as far as something to stop.
3738 continue;
3739 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003740 return true;
3741 }
3742 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003743 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003744 if (samePackage) {
3745 if (r.app != null) {
3746 r.app.removed = true;
3747 }
3748 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003750 lastTask = r.task;
3751 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003752 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003753 i--;
3754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
3756 }
3757
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003758 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3759 if (!doit) {
3760 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003762 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003764
3765 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003766 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003767 if (provider.info.packageName.equals(name)
3768 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3769 if (!doit) {
3770 return true;
3771 }
3772 didSomething = true;
3773 providers.add(provider);
3774 }
3775 }
3776
3777 N = providers.size();
3778 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003779 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003780 }
3781
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003782 if (doit) {
3783 if (purgeCache) {
3784 AttributeCache ac = AttributeCache.instance();
3785 if (ac != null) {
3786 ac.removePackage(name);
3787 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003788 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003789 if (mBooted) {
3790 mMainStack.resumeTopActivityLocked(null);
3791 mMainStack.scheduleIdleLocked();
3792 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003793 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003794
3795 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 }
3797
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003798 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003799 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003800 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003801 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003802 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003803 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 + "/" + uid + ")");
3805
3806 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003807 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003808 if (mHeavyWeightProcess == app) {
3809 mHeavyWeightProcess = null;
3810 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 boolean needRestart = false;
3813 if (app.pid > 0 && app.pid != MY_PID) {
3814 int pid = app.pid;
3815 synchronized (mPidsSelfLocked) {
3816 mPidsSelfLocked.remove(pid);
3817 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3818 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003819 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003820 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003821 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003822 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003824 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003826 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 } else {
3828 needRestart = true;
3829 }
3830 }
3831 } else {
3832 mRemovedProcesses.add(app);
3833 }
3834
3835 return needRestart;
3836 }
3837
3838 private final void processStartTimedOutLocked(ProcessRecord app) {
3839 final int pid = app.pid;
3840 boolean gone = false;
3841 synchronized (mPidsSelfLocked) {
3842 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3843 if (knownApp != null && knownApp.thread == null) {
3844 mPidsSelfLocked.remove(pid);
3845 gone = true;
3846 }
3847 }
3848
3849 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003850 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003851 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003852 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003853 mProcessNames.remove(app.processName, app.uid);
3854 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003855 if (mHeavyWeightProcess == app) {
3856 mHeavyWeightProcess = null;
3857 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3858 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003859 // Take care of any launching providers waiting for this process.
3860 checkAppInLaunchingProvidersLocked(app, true);
3861 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003862 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003863 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3864 app.processName, app.setAdj, "start timeout");
3865 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003866 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003867 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003868 try {
3869 IBackupManager bm = IBackupManager.Stub.asInterface(
3870 ServiceManager.getService(Context.BACKUP_SERVICE));
3871 bm.agentDisconnected(app.info.packageName);
3872 } catch (RemoteException e) {
3873 // Can't happen; the backup manager is local
3874 }
3875 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003876 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003877 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003878 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003881 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 }
3883 }
3884
3885 private final boolean attachApplicationLocked(IApplicationThread thread,
3886 int pid) {
3887
3888 // Find the application record that is being attached... either via
3889 // the pid if we are running in multiple processes, or just pull the
3890 // next app record if we are emulating process with anonymous threads.
3891 ProcessRecord app;
3892 if (pid != MY_PID && pid >= 0) {
3893 synchronized (mPidsSelfLocked) {
3894 app = mPidsSelfLocked.get(pid);
3895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 } else {
3897 app = null;
3898 }
3899
3900 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003901 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003903 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003905 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 } else {
3907 try {
3908 thread.scheduleExit();
3909 } catch (Exception e) {
3910 // Ignore exceptions.
3911 }
3912 }
3913 return false;
3914 }
3915
3916 // If this application record is still attached to a previous
3917 // process, clean it up now.
3918 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003919 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921
3922 // Tell the process all about itself.
3923
Joe Onorato8a9b2202010-02-26 18:56:32 -08003924 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 TAG, "Binding process pid " + pid + " to record " + app);
3926
3927 String processName = app.processName;
3928 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003929 AppDeathRecipient adr = new AppDeathRecipient(
3930 app, pid, thread);
3931 thread.asBinder().linkToDeath(adr, 0);
3932 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 } catch (RemoteException e) {
3934 app.resetPackageList();
3935 startProcessLocked(app, "link fail", processName);
3936 return false;
3937 }
3938
Doug Zongker2bec3d42009-12-04 12:52:44 -08003939 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940
3941 app.thread = thread;
3942 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003943 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3944 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 app.forcingToForeground = null;
3946 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003947 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 app.debugging = false;
3949
3950 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3951
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003952 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003953 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003955 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003956 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003957 }
3958
Joe Onorato8a9b2202010-02-26 18:56:32 -08003959 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 TAG, "New app record " + app
3961 + " thread=" + thread.asBinder() + " pid=" + pid);
3962 try {
3963 int testMode = IApplicationThread.DEBUG_OFF;
3964 if (mDebugApp != null && mDebugApp.equals(processName)) {
3965 testMode = mWaitForDebugger
3966 ? IApplicationThread.DEBUG_WAIT
3967 : IApplicationThread.DEBUG_ON;
3968 app.debugging = true;
3969 if (mDebugTransient) {
3970 mDebugApp = mOrigDebugApp;
3971 mWaitForDebugger = mOrigWaitForDebugger;
3972 }
3973 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003974 String profileFile = app.instrumentationProfileFile;
3975 ParcelFileDescriptor profileFd = null;
3976 boolean profileAutoStop = false;
3977 if (mProfileApp != null && mProfileApp.equals(processName)) {
3978 mProfileProc = app;
3979 profileFile = mProfileFile;
3980 profileFd = mProfileFd;
3981 profileAutoStop = mAutoStopProfiler;
3982 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003983 boolean enableOpenGlTrace = false;
3984 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3985 enableOpenGlTrace = true;
3986 mOpenGlTraceApp = null;
3987 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003988
Christopher Tate181fafa2009-05-14 11:12:14 -07003989 // If the app is being launched for restore or full backup, set it up specially
3990 boolean isRestrictedBackupMode = false;
3991 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3992 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003993 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003994 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3995 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003996
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003997 ensurePackageDexOpt(app.instrumentationInfo != null
3998 ? app.instrumentationInfo.packageName
3999 : app.info.packageName);
4000 if (app.instrumentationClass != null) {
4001 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004002 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004003 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004004 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004005 ApplicationInfo appInfo = app.instrumentationInfo != null
4006 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004007 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004008 if (profileFd != null) {
4009 profileFd = profileFd.dup();
4010 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004011 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004012 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004013 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4014 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004015 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004016 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004017 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004018 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 } catch (Exception e) {
4020 // todo: Yikes! What should we do? For now we will try to
4021 // start another process, but that could easily get us in
4022 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004023 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024
4025 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004026 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 startProcessLocked(app, "bind fail", processName);
4028 return false;
4029 }
4030
4031 // Remove this record from the list of starting applications.
4032 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004033 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4034 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 mProcessesOnHold.remove(app);
4036
4037 boolean badApp = false;
4038 boolean didSomething = false;
4039
4040 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004041 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004042 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004043 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 && processName.equals(hr.processName)) {
4045 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004046 if (mHeadless) {
4047 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4048 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 didSomething = true;
4050 }
4051 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004052 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 + hr.intent.getComponent().flattenToShortString(), e);
4054 badApp = true;
4055 }
4056 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 }
4059 }
4060
4061 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004062 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004064 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 badApp = true;
4067 }
4068 }
4069
Christopher Tatef46723b2012-01-26 14:19:24 -08004070 // Check if a next-broadcast receiver is in this process...
4071 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004073 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004075 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004076 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 }
4078 }
4079
Christopher Tate181fafa2009-05-14 11:12:14 -07004080 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004081 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004082 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004083 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004084 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004085 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4086 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4087 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004088 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004089 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004090 e.printStackTrace();
4091 }
4092 }
4093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004094 if (badApp) {
4095 // todo: Also need to kill application to deal with all
4096 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004097 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 return false;
4099 }
4100
4101 if (!didSomething) {
4102 updateOomAdjLocked();
4103 }
4104
4105 return true;
4106 }
4107
4108 public final void attachApplication(IApplicationThread thread) {
4109 synchronized (this) {
4110 int callingPid = Binder.getCallingPid();
4111 final long origId = Binder.clearCallingIdentity();
4112 attachApplicationLocked(thread, callingPid);
4113 Binder.restoreCallingIdentity(origId);
4114 }
4115 }
4116
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004117 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004119 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4120 if (stopProfiling) {
4121 synchronized (this) {
4122 if (mProfileProc == r.app) {
4123 if (mProfileFd != null) {
4124 try {
4125 mProfileFd.close();
4126 } catch (IOException e) {
4127 }
4128 clearProfilerLocked();
4129 }
4130 }
4131 }
4132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 Binder.restoreCallingIdentity(origId);
4134 }
4135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004137 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004138 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004140
4141 synchronized (this) {
4142 updateEventDispatchingLocked();
4143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 }
4145
Dianne Hackborn661cd522011-08-22 00:26:20 -07004146 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004147 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004148 mWindowManager.showBootMessage(msg, always);
4149 }
4150
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004151 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004152 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004153 final long token = Binder.clearCallingIdentity();
4154 try {
4155 synchronized (this) {
4156 if (mLockScreenShown) {
4157 mLockScreenShown = false;
4158 comeOutOfSleepIfNeededLocked();
4159 }
4160 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004161 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004162 } finally {
4163 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004164 }
4165 }
4166
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004167 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004168 IntentFilter pkgFilter = new IntentFilter();
4169 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4170 pkgFilter.addDataScheme("package");
4171 mContext.registerReceiver(new BroadcastReceiver() {
4172 @Override
4173 public void onReceive(Context context, Intent intent) {
4174 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4175 if (pkgs != null) {
4176 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004177 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004178 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4179 setResultCode(Activity.RESULT_OK);
4180 return;
4181 }
4182 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004183 }
4184 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004185 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004186 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004187
4188 IntentFilter userFilter = new IntentFilter();
4189 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4190 mContext.registerReceiver(new BroadcastReceiver() {
4191 @Override
4192 public void onReceive(Context context, Intent intent) {
4193 onUserRemoved(intent);
4194 }
4195 }, userFilter);
4196
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004197 synchronized (this) {
4198 // Ensure that any processes we had put on hold are now started
4199 // up.
4200 final int NP = mProcessesOnHold.size();
4201 if (NP > 0) {
4202 ArrayList<ProcessRecord> procs =
4203 new ArrayList<ProcessRecord>(mProcessesOnHold);
4204 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004205 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4206 + procs.get(ip));
4207 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004208 }
4209 }
4210
4211 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004212 // Start looking for apps that are abusing wake locks.
4213 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004214 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004215 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004216 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004217 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani258848d2012-08-10 17:06:33 -07004218 List<UserInfo> users = getUserManager().getUsers();
4219 for (UserInfo user : users) {
4220 broadcastIntentLocked(null, null,
4221 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4222 null, null, 0, null, null,
4223 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
4224 false, false, MY_PID, Process.SYSTEM_UID, user.id);
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004225 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004226 }
4227 }
4228 }
4229
4230 final void ensureBootCompleted() {
4231 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004232 boolean enableScreen;
4233 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004234 booting = mBooting;
4235 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004236 enableScreen = !mBooted;
4237 mBooted = true;
4238 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004239
4240 if (booting) {
4241 finishBooting();
4242 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004243
4244 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004245 enableScreenAfterBoot();
4246 }
4247 }
4248
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004249 public final void activityPaused(IBinder token) {
4250 final long origId = Binder.clearCallingIdentity();
4251 mMainStack.activityPaused(token, false);
4252 Binder.restoreCallingIdentity(origId);
4253 }
4254
4255 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4256 CharSequence description) {
4257 if (localLOGV) Slog.v(
4258 TAG, "Activity stopped: token=" + token);
4259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 // Refuse possible leaked file descriptors
4261 if (icicle != null && icicle.hasFileDescriptors()) {
4262 throw new IllegalArgumentException("File descriptors passed in Bundle");
4263 }
4264
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004265 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266
4267 final long origId = Binder.clearCallingIdentity();
4268
4269 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004270 r = mMainStack.isInStackLocked(token);
4271 if (r != null) {
4272 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004273 }
4274 }
4275
4276 if (r != null) {
4277 sendPendingThumbnail(r, null, null, null, false);
4278 }
4279
4280 trimApplications();
4281
4282 Binder.restoreCallingIdentity(origId);
4283 }
4284
4285 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004286 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004287 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 }
4289
4290 public String getCallingPackage(IBinder token) {
4291 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004292 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004293 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 }
4295 }
4296
4297 public ComponentName getCallingActivity(IBinder token) {
4298 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004299 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 return r != null ? r.intent.getComponent() : null;
4301 }
4302 }
4303
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004304 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004305 ActivityRecord r = mMainStack.isInStackLocked(token);
4306 if (r == null) {
4307 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004309 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004310 }
4311
4312 public ComponentName getActivityClassForToken(IBinder token) {
4313 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004314 ActivityRecord r = mMainStack.isInStackLocked(token);
4315 if (r == null) {
4316 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004317 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004318 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 }
4320 }
4321
4322 public String getPackageForToken(IBinder token) {
4323 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004324 ActivityRecord r = mMainStack.isInStackLocked(token);
4325 if (r == null) {
4326 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004328 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004329 }
4330 }
4331
4332 public IIntentSender getIntentSender(int type,
4333 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004334 int requestCode, Intent[] intents, String[] resolvedTypes,
4335 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004336 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004338 if (intents != null) {
4339 if (intents.length < 1) {
4340 throw new IllegalArgumentException("Intents array length must be >= 1");
4341 }
4342 for (int i=0; i<intents.length; i++) {
4343 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004344 if (intent != null) {
4345 if (intent.hasFileDescriptors()) {
4346 throw new IllegalArgumentException("File descriptors passed in Intent");
4347 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004348 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004349 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4350 throw new IllegalArgumentException(
4351 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4352 }
4353 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004354 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004355 }
4356 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004357 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004358 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004359 }
4360 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004361 if (options != null) {
4362 if (options.hasFileDescriptors()) {
4363 throw new IllegalArgumentException("File descriptors passed in options");
4364 }
4365 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 synchronized(this) {
4368 int callingUid = Binder.getCallingUid();
4369 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004370 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004371 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004372 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4373 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 String msg = "Permission Denial: getIntentSender() from pid="
4375 + Binder.getCallingPid()
4376 + ", uid=" + Binder.getCallingUid()
4377 + ", (need uid=" + uid + ")"
4378 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004379 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380 throw new SecurityException(msg);
4381 }
4382 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004383
Amith Yamasani742a6712011-05-04 14:49:28 -07004384 if (DEBUG_MU)
4385 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4386 + Binder.getOrigCallingUid());
4387 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004388 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 } catch (RemoteException e) {
4391 throw new SecurityException(e);
4392 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 }
4394 }
4395
4396 IIntentSender getIntentSenderLocked(int type,
4397 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004398 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4399 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004400 if (DEBUG_MU)
4401 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004402 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004403 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004404 activity = mMainStack.isInStackLocked(token);
4405 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004406 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004408 if (activity.finishing) {
4409 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411 }
4412
4413 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4414 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4415 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4416 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4417 |PendingIntent.FLAG_UPDATE_CURRENT);
4418
4419 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4420 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004421 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004422 WeakReference<PendingIntentRecord> ref;
4423 ref = mIntentSenderRecords.get(key);
4424 PendingIntentRecord rec = ref != null ? ref.get() : null;
4425 if (rec != null) {
4426 if (!cancelCurrent) {
4427 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004428 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004429 rec.key.requestIntent.replaceExtras(intents != null ?
4430 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004431 }
4432 if (intents != null) {
4433 intents[intents.length-1] = rec.key.requestIntent;
4434 rec.key.allIntents = intents;
4435 rec.key.allResolvedTypes = resolvedTypes;
4436 } else {
4437 rec.key.allIntents = null;
4438 rec.key.allResolvedTypes = null;
4439 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 return rec;
4442 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004443 rec.canceled = true;
4444 mIntentSenderRecords.remove(key);
4445 }
4446 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 return rec;
4448 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004449 rec = new PendingIntentRecord(this, key, callingUid);
4450 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004451 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004452 if (activity.pendingResults == null) {
4453 activity.pendingResults
4454 = new HashSet<WeakReference<PendingIntentRecord>>();
4455 }
4456 activity.pendingResults.add(rec.ref);
4457 }
4458 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 }
4460
4461 public void cancelIntentSender(IIntentSender sender) {
4462 if (!(sender instanceof PendingIntentRecord)) {
4463 return;
4464 }
4465 synchronized(this) {
4466 PendingIntentRecord rec = (PendingIntentRecord)sender;
4467 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004468 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004469 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4470 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 String msg = "Permission Denial: cancelIntentSender() from pid="
4472 + Binder.getCallingPid()
4473 + ", uid=" + Binder.getCallingUid()
4474 + " is not allowed to cancel packges "
4475 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004476 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 throw new SecurityException(msg);
4478 }
4479 } catch (RemoteException e) {
4480 throw new SecurityException(e);
4481 }
4482 cancelIntentSenderLocked(rec, true);
4483 }
4484 }
4485
4486 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4487 rec.canceled = true;
4488 mIntentSenderRecords.remove(rec.key);
4489 if (cleanActivity && rec.key.activity != null) {
4490 rec.key.activity.pendingResults.remove(rec.ref);
4491 }
4492 }
4493
4494 public String getPackageForIntentSender(IIntentSender pendingResult) {
4495 if (!(pendingResult instanceof PendingIntentRecord)) {
4496 return null;
4497 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004498 try {
4499 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4500 return res.key.packageName;
4501 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 }
4503 return null;
4504 }
4505
Christopher Tatec4a07d12012-04-06 14:19:13 -07004506 public int getUidForIntentSender(IIntentSender sender) {
4507 if (sender instanceof PendingIntentRecord) {
4508 try {
4509 PendingIntentRecord res = (PendingIntentRecord)sender;
4510 return res.uid;
4511 } catch (ClassCastException e) {
4512 }
4513 }
4514 return -1;
4515 }
4516
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004517 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4518 if (!(pendingResult instanceof PendingIntentRecord)) {
4519 return false;
4520 }
4521 try {
4522 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4523 if (res.key.allIntents == null) {
4524 return false;
4525 }
4526 for (int i=0; i<res.key.allIntents.length; i++) {
4527 Intent intent = res.key.allIntents[i];
4528 if (intent.getPackage() != null && intent.getComponent() != null) {
4529 return false;
4530 }
4531 }
4532 return true;
4533 } catch (ClassCastException e) {
4534 }
4535 return false;
4536 }
4537
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004538 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4539 if (!(pendingResult instanceof PendingIntentRecord)) {
4540 return false;
4541 }
4542 try {
4543 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4544 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4545 return true;
4546 }
4547 return false;
4548 } catch (ClassCastException e) {
4549 }
4550 return false;
4551 }
4552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 public void setProcessLimit(int max) {
4554 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4555 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004556 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004557 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004558 mProcessLimitOverride = max;
4559 }
4560 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
4562
4563 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004564 synchronized (this) {
4565 return mProcessLimitOverride;
4566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004567 }
4568
4569 void foregroundTokenDied(ForegroundToken token) {
4570 synchronized (ActivityManagerService.this) {
4571 synchronized (mPidsSelfLocked) {
4572 ForegroundToken cur
4573 = mForegroundProcesses.get(token.pid);
4574 if (cur != token) {
4575 return;
4576 }
4577 mForegroundProcesses.remove(token.pid);
4578 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4579 if (pr == null) {
4580 return;
4581 }
4582 pr.forcingToForeground = null;
4583 pr.foregroundServices = false;
4584 }
4585 updateOomAdjLocked();
4586 }
4587 }
4588
4589 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4590 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4591 "setProcessForeground()");
4592 synchronized(this) {
4593 boolean changed = false;
4594
4595 synchronized (mPidsSelfLocked) {
4596 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004597 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004598 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 return;
4600 }
4601 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4602 if (oldToken != null) {
4603 oldToken.token.unlinkToDeath(oldToken, 0);
4604 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004605 if (pr != null) {
4606 pr.forcingToForeground = null;
4607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004608 changed = true;
4609 }
4610 if (isForeground && token != null) {
4611 ForegroundToken newToken = new ForegroundToken() {
4612 public void binderDied() {
4613 foregroundTokenDied(this);
4614 }
4615 };
4616 newToken.pid = pid;
4617 newToken.token = token;
4618 try {
4619 token.linkToDeath(newToken, 0);
4620 mForegroundProcesses.put(pid, newToken);
4621 pr.forcingToForeground = token;
4622 changed = true;
4623 } catch (RemoteException e) {
4624 // If the process died while doing this, we will later
4625 // do the cleanup with the process death link.
4626 }
4627 }
4628 }
4629
4630 if (changed) {
4631 updateOomAdjLocked();
4632 }
4633 }
4634 }
4635
4636 // =========================================================
4637 // PERMISSIONS
4638 // =========================================================
4639
4640 static class PermissionController extends IPermissionController.Stub {
4641 ActivityManagerService mActivityManagerService;
4642 PermissionController(ActivityManagerService activityManagerService) {
4643 mActivityManagerService = activityManagerService;
4644 }
4645
4646 public boolean checkPermission(String permission, int pid, int uid) {
4647 return mActivityManagerService.checkPermission(permission, pid,
4648 uid) == PackageManager.PERMISSION_GRANTED;
4649 }
4650 }
4651
4652 /**
4653 * This can be called with or without the global lock held.
4654 */
4655 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004656 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 // We might be performing an operation on behalf of an indirect binder
4658 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4659 // client identity accordingly before proceeding.
4660 Identity tlsIdentity = sCallerIdentity.get();
4661 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004662 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004663 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4664 uid = tlsIdentity.uid;
4665 pid = tlsIdentity.pid;
4666 }
4667
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004668 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 return PackageManager.PERMISSION_GRANTED;
4670 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004671
4672 return ActivityManager.checkComponentPermission(permission, uid,
4673 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004674 }
4675
4676 /**
4677 * As the only public entry point for permissions checking, this method
4678 * can enforce the semantic that requesting a check on a null global
4679 * permission is automatically denied. (Internally a null permission
4680 * string is used when calling {@link #checkComponentPermission} in cases
4681 * when only uid-based security is needed.)
4682 *
4683 * This can be called with or without the global lock held.
4684 */
4685 public int checkPermission(String permission, int pid, int uid) {
4686 if (permission == null) {
4687 return PackageManager.PERMISSION_DENIED;
4688 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004689 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004690 }
4691
4692 /**
4693 * Binder IPC calls go through the public entry point.
4694 * This can be called with or without the global lock held.
4695 */
4696 int checkCallingPermission(String permission) {
4697 return checkPermission(permission,
4698 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004699 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004700 }
4701
4702 /**
4703 * This can be called with or without the global lock held.
4704 */
4705 void enforceCallingPermission(String permission, String func) {
4706 if (checkCallingPermission(permission)
4707 == PackageManager.PERMISSION_GRANTED) {
4708 return;
4709 }
4710
4711 String msg = "Permission Denial: " + func + " from pid="
4712 + Binder.getCallingPid()
4713 + ", uid=" + Binder.getCallingUid()
4714 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004715 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 throw new SecurityException(msg);
4717 }
4718
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004719 /**
4720 * Determine if UID is holding permissions required to access {@link Uri} in
4721 * the given {@link ProviderInfo}. Final permission checking is always done
4722 * in {@link ContentProvider}.
4723 */
4724 private final boolean checkHoldingPermissionsLocked(
4725 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004726 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4727 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004728
4729 if (pi.applicationInfo.uid == uid) {
4730 return true;
4731 } else if (!pi.exported) {
4732 return false;
4733 }
4734
4735 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4736 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004738 // check if target holds top-level <provider> permissions
4739 if (!readMet && pi.readPermission != null
4740 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4741 readMet = true;
4742 }
4743 if (!writeMet && pi.writePermission != null
4744 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4745 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004746 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004747
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004748 // track if unprotected read/write is allowed; any denied
4749 // <path-permission> below removes this ability
4750 boolean allowDefaultRead = pi.readPermission == null;
4751 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004752
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004753 // check if target holds any <path-permission> that match uri
4754 final PathPermission[] pps = pi.pathPermissions;
4755 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004756 final String path = uri.getPath();
4757 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004758 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004759 i--;
4760 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004761 if (pp.match(path)) {
4762 if (!readMet) {
4763 final String pprperm = pp.getReadPermission();
4764 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4765 + pprperm + " for " + pp.getPath()
4766 + ": match=" + pp.match(path)
4767 + " check=" + pm.checkUidPermission(pprperm, uid));
4768 if (pprperm != null) {
4769 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4770 readMet = true;
4771 } else {
4772 allowDefaultRead = false;
4773 }
4774 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004775 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004776 if (!writeMet) {
4777 final String ppwperm = pp.getWritePermission();
4778 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4779 + ppwperm + " for " + pp.getPath()
4780 + ": match=" + pp.match(path)
4781 + " check=" + pm.checkUidPermission(ppwperm, uid));
4782 if (ppwperm != null) {
4783 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4784 writeMet = true;
4785 } else {
4786 allowDefaultWrite = false;
4787 }
4788 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004789 }
4790 }
4791 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004792 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004793
4794 // grant unprotected <provider> read/write, if not blocked by
4795 // <path-permission> above
4796 if (allowDefaultRead) readMet = true;
4797 if (allowDefaultWrite) writeMet = true;
4798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 } catch (RemoteException e) {
4800 return false;
4801 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004802
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004803 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004804 }
4805
4806 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4807 int modeFlags) {
4808 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004809 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 return true;
4811 }
4812 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4813 if (perms == null) return false;
4814 UriPermission perm = perms.get(uri);
4815 if (perm == null) return false;
4816 return (modeFlags&perm.modeFlags) == modeFlags;
4817 }
4818
4819 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004820 enforceNotIsolatedCaller("checkUriPermission");
4821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 // Another redirected-binder-call permissions check as in
4823 // {@link checkComponentPermission}.
4824 Identity tlsIdentity = sCallerIdentity.get();
4825 if (tlsIdentity != null) {
4826 uid = tlsIdentity.uid;
4827 pid = tlsIdentity.pid;
4828 }
4829
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004830 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004831 // Our own process gets to do everything.
4832 if (pid == MY_PID) {
4833 return PackageManager.PERMISSION_GRANTED;
4834 }
4835 synchronized(this) {
4836 return checkUriPermissionLocked(uri, uid, modeFlags)
4837 ? PackageManager.PERMISSION_GRANTED
4838 : PackageManager.PERMISSION_DENIED;
4839 }
4840 }
4841
Dianne Hackborn39792d22010-08-19 18:01:52 -07004842 /**
4843 * Check if the targetPkg can be granted permission to access uri by
4844 * the callingUid using the given modeFlags. Throws a security exception
4845 * if callingUid is not allowed to do this. Returns the uid of the target
4846 * if the URI permission grant should be performed; returns -1 if it is not
4847 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004848 * If you already know the uid of the target, you can supply it in
4849 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004850 */
4851 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004852 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004853 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4854 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4855 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004856 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 }
4858
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004859 if (targetPkg != null) {
4860 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4861 "Checking grant " + targetPkg + " permission to " + uri);
4862 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004863
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004864 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865
4866 // If this is not a content: uri, we can't do anything with it.
4867 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004868 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004869 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004870 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 }
4872
4873 String name = uri.getAuthority();
4874 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004875 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004876 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 if (cpr != null) {
4878 pi = cpr.info;
4879 } else {
4880 try {
4881 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004882 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 } catch (RemoteException ex) {
4884 }
4885 }
4886 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004887 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004888 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004889 }
4890
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004891 int targetUid = lastTargetUid;
4892 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004893 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004894 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004895 if (targetUid < 0) {
4896 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4897 "Can't grant URI permission no uid for: " + targetPkg);
4898 return -1;
4899 }
4900 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004901 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004903 }
4904
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004905 if (targetUid >= 0) {
4906 // First... does the target actually need this permission?
4907 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4908 // No need to grant the target this permission.
4909 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4910 "Target " + targetPkg + " already has full permission to " + uri);
4911 return -1;
4912 }
4913 } else {
4914 // First... there is no target package, so can anyone access it?
4915 boolean allowed = pi.exported;
4916 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4917 if (pi.readPermission != null) {
4918 allowed = false;
4919 }
4920 }
4921 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4922 if (pi.writePermission != null) {
4923 allowed = false;
4924 }
4925 }
4926 if (allowed) {
4927 return -1;
4928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004929 }
4930
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004931 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 if (!pi.grantUriPermissions) {
4933 throw new SecurityException("Provider " + pi.packageName
4934 + "/" + pi.name
4935 + " does not allow granting of Uri permissions (uri "
4936 + uri + ")");
4937 }
4938 if (pi.uriPermissionPatterns != null) {
4939 final int N = pi.uriPermissionPatterns.length;
4940 boolean allowed = false;
4941 for (int i=0; i<N; i++) {
4942 if (pi.uriPermissionPatterns[i] != null
4943 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4944 allowed = true;
4945 break;
4946 }
4947 }
4948 if (!allowed) {
4949 throw new SecurityException("Provider " + pi.packageName
4950 + "/" + pi.name
4951 + " does not allow granting of permission to path of Uri "
4952 + uri);
4953 }
4954 }
4955
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004956 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004958 if (callingUid != Process.myUid()) {
4959 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4960 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4961 throw new SecurityException("Uid " + callingUid
4962 + " does not have permission to uri " + uri);
4963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
4965 }
4966
Dianne Hackborn39792d22010-08-19 18:01:52 -07004967 return targetUid;
4968 }
4969
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004970 public int checkGrantUriPermission(int callingUid, String targetPkg,
4971 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004972 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004973 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004974 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004975 }
4976 }
4977
Dianne Hackborn39792d22010-08-19 18:01:52 -07004978 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4979 Uri uri, int modeFlags, UriPermissionOwner owner) {
4980 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4981 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4982 if (modeFlags == 0) {
4983 return;
4984 }
4985
4986 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004987 // to the uri, and the target doesn't. Let's now give this to
4988 // the target.
4989
Joe Onorato8a9b2202010-02-26 18:56:32 -08004990 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004991 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 HashMap<Uri, UriPermission> targetUris
4994 = mGrantedUriPermissions.get(targetUid);
4995 if (targetUris == null) {
4996 targetUris = new HashMap<Uri, UriPermission>();
4997 mGrantedUriPermissions.put(targetUid, targetUris);
4998 }
4999
5000 UriPermission perm = targetUris.get(uri);
5001 if (perm == null) {
5002 perm = new UriPermission(targetUid, uri);
5003 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005004 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005007 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005009 } else {
5010 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5011 perm.readOwners.add(owner);
5012 owner.addReadPermission(perm);
5013 }
5014 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5015 perm.writeOwners.add(owner);
5016 owner.addWritePermission(perm);
5017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 }
5019 }
5020
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005021 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5022 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005023 if (targetPkg == null) {
5024 throw new NullPointerException("targetPkg");
5025 }
5026
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005027 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005028 if (targetUid < 0) {
5029 return;
5030 }
5031
5032 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5033 }
5034
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005035 static class NeededUriGrants extends ArrayList<Uri> {
5036 final String targetPkg;
5037 final int targetUid;
5038 final int flags;
5039
5040 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5041 targetPkg = _targetPkg;
5042 targetUid = _targetUid;
5043 flags = _flags;
5044 }
5045 }
5046
Dianne Hackborn39792d22010-08-19 18:01:52 -07005047 /**
5048 * Like checkGrantUriPermissionLocked, but takes an Intent.
5049 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005050 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5051 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005052 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005053 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5054 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005055 + " from " + intent + "; flags=0x"
5056 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5057
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005058 if (targetPkg == null) {
5059 throw new NullPointerException("targetPkg");
5060 }
5061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005062 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 }
5065 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005066 ClipData clip = intent.getClipData();
5067 if (data == null && clip == null) {
5068 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005069 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005070 if (data != null) {
5071 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5072 mode, needed != null ? needed.targetUid : -1);
5073 if (target > 0) {
5074 if (needed == null) {
5075 needed = new NeededUriGrants(targetPkg, target, mode);
5076 }
5077 needed.add(data);
5078 }
5079 }
5080 if (clip != null) {
5081 for (int i=0; i<clip.getItemCount(); i++) {
5082 Uri uri = clip.getItemAt(i).getUri();
5083 if (uri != null) {
5084 int target = -1;
5085 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5086 mode, needed != null ? needed.targetUid : -1);
5087 if (target > 0) {
5088 if (needed == null) {
5089 needed = new NeededUriGrants(targetPkg, target, mode);
5090 }
5091 needed.add(uri);
5092 }
5093 } else {
5094 Intent clipIntent = clip.getItemAt(i).getIntent();
5095 if (clipIntent != null) {
5096 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5097 callingUid, targetPkg, clipIntent, mode, needed);
5098 if (newNeeded != null) {
5099 needed = newNeeded;
5100 }
5101 }
5102 }
5103 }
5104 }
5105
5106 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005107 }
5108
5109 /**
5110 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5111 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005112 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5113 UriPermissionOwner owner) {
5114 if (needed != null) {
5115 for (int i=0; i<needed.size(); i++) {
5116 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5117 needed.get(i), needed.flags, owner);
5118 }
5119 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005120 }
5121
5122 void grantUriPermissionFromIntentLocked(int callingUid,
5123 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005124 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005125 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005126 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005127 return;
5128 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005129
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005130 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005131 }
5132
5133 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5134 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005135 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 synchronized(this) {
5137 final ProcessRecord r = getRecordForAppLocked(caller);
5138 if (r == null) {
5139 throw new SecurityException("Unable to find app for caller "
5140 + caller
5141 + " when granting permission to uri " + uri);
5142 }
5143 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005144 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005145 }
5146 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005147 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 }
5149
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005150 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005151 null);
5152 }
5153 }
5154
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005155 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5157 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5158 HashMap<Uri, UriPermission> perms
5159 = mGrantedUriPermissions.get(perm.uid);
5160 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005161 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005162 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 perms.remove(perm.uri);
5164 if (perms.size() == 0) {
5165 mGrantedUriPermissions.remove(perm.uid);
5166 }
5167 }
5168 }
5169 }
5170
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5172 int modeFlags) {
5173 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5174 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5175 if (modeFlags == 0) {
5176 return;
5177 }
5178
Joe Onorato8a9b2202010-02-26 18:56:32 -08005179 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005180 "Revoking all granted permissions to " + uri);
5181
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005182 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005183
5184 final String authority = uri.getAuthority();
5185 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005186 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005187 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 if (cpr != null) {
5189 pi = cpr.info;
5190 } else {
5191 try {
5192 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005193 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005194 } catch (RemoteException ex) {
5195 }
5196 }
5197 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005198 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005199 return;
5200 }
5201
5202 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005203 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 // Right now, if you are not the original owner of the permission,
5205 // you are not allowed to revoke it.
5206 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5207 throw new SecurityException("Uid " + callingUid
5208 + " does not have permission to uri " + uri);
5209 //}
5210 }
5211
5212 // Go through all of the permissions and remove any that match.
5213 final List<String> SEGMENTS = uri.getPathSegments();
5214 if (SEGMENTS != null) {
5215 final int NS = SEGMENTS.size();
5216 int N = mGrantedUriPermissions.size();
5217 for (int i=0; i<N; i++) {
5218 HashMap<Uri, UriPermission> perms
5219 = mGrantedUriPermissions.valueAt(i);
5220 Iterator<UriPermission> it = perms.values().iterator();
5221 toploop:
5222 while (it.hasNext()) {
5223 UriPermission perm = it.next();
5224 Uri targetUri = perm.uri;
5225 if (!authority.equals(targetUri.getAuthority())) {
5226 continue;
5227 }
5228 List<String> targetSegments = targetUri.getPathSegments();
5229 if (targetSegments == null) {
5230 continue;
5231 }
5232 if (targetSegments.size() < NS) {
5233 continue;
5234 }
5235 for (int j=0; j<NS; j++) {
5236 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5237 continue toploop;
5238 }
5239 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005240 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005241 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005242 perm.clearModes(modeFlags);
5243 if (perm.modeFlags == 0) {
5244 it.remove();
5245 }
5246 }
5247 if (perms.size() == 0) {
5248 mGrantedUriPermissions.remove(
5249 mGrantedUriPermissions.keyAt(i));
5250 N--;
5251 i--;
5252 }
5253 }
5254 }
5255 }
5256
5257 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5258 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005259 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 synchronized(this) {
5261 final ProcessRecord r = getRecordForAppLocked(caller);
5262 if (r == null) {
5263 throw new SecurityException("Unable to find app for caller "
5264 + caller
5265 + " when revoking permission to uri " + uri);
5266 }
5267 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005268 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 return;
5270 }
5271
5272 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5273 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5274 if (modeFlags == 0) {
5275 return;
5276 }
5277
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005278 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005279
5280 final String authority = uri.getAuthority();
5281 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005282 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005283 if (cpr != null) {
5284 pi = cpr.info;
5285 } else {
5286 try {
5287 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005288 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 } catch (RemoteException ex) {
5290 }
5291 }
5292 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005293 Slog.w(TAG, "No content provider found for permission revoke: "
5294 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005295 return;
5296 }
5297
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005298 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 }
5300 }
5301
Dianne Hackborn7e269642010-08-25 19:50:20 -07005302 @Override
5303 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005304 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005305 synchronized(this) {
5306 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5307 return owner.getExternalTokenLocked();
5308 }
5309 }
5310
5311 @Override
5312 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5313 Uri uri, int modeFlags) {
5314 synchronized(this) {
5315 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5316 if (owner == null) {
5317 throw new IllegalArgumentException("Unknown owner: " + token);
5318 }
5319 if (fromUid != Binder.getCallingUid()) {
5320 if (Binder.getCallingUid() != Process.myUid()) {
5321 // Only system code can grant URI permissions on behalf
5322 // of other users.
5323 throw new SecurityException("nice try");
5324 }
5325 }
5326 if (targetPkg == null) {
5327 throw new IllegalArgumentException("null target");
5328 }
5329 if (uri == null) {
5330 throw new IllegalArgumentException("null uri");
5331 }
5332
5333 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5334 }
5335 }
5336
5337 @Override
5338 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5339 synchronized(this) {
5340 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5341 if (owner == null) {
5342 throw new IllegalArgumentException("Unknown owner: " + token);
5343 }
5344
5345 if (uri == null) {
5346 owner.removeUriPermissionsLocked(mode);
5347 } else {
5348 owner.removeUriPermissionLocked(uri, mode);
5349 }
5350 }
5351 }
5352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5354 synchronized (this) {
5355 ProcessRecord app =
5356 who != null ? getRecordForAppLocked(who) : null;
5357 if (app == null) return;
5358
5359 Message msg = Message.obtain();
5360 msg.what = WAIT_FOR_DEBUGGER_MSG;
5361 msg.obj = app;
5362 msg.arg1 = waiting ? 1 : 0;
5363 mHandler.sendMessage(msg);
5364 }
5365 }
5366
5367 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005368 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5369 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005370 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005371 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005372 outInfo.threshold = homeAppMem;
5373 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5374 outInfo.hiddenAppThreshold = hiddenAppMem;
5375 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005376 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005377 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5378 ProcessList.VISIBLE_APP_ADJ);
5379 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5380 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381 }
5382
5383 // =========================================================
5384 // TASK MANAGEMENT
5385 // =========================================================
5386
5387 public List getTasks(int maxNum, int flags,
5388 IThumbnailReceiver receiver) {
5389 ArrayList list = new ArrayList();
5390
5391 PendingThumbnailsRecord pending = null;
5392 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005393 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394
5395 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005396 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5398 + ", receiver=" + receiver);
5399
5400 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5401 != PackageManager.PERMISSION_GRANTED) {
5402 if (receiver != null) {
5403 // If the caller wants to wait for pending thumbnails,
5404 // it ain't gonna get them.
5405 try {
5406 receiver.finished();
5407 } catch (RemoteException ex) {
5408 }
5409 }
5410 String msg = "Permission Denial: getTasks() from pid="
5411 + Binder.getCallingPid()
5412 + ", uid=" + Binder.getCallingUid()
5413 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005414 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 throw new SecurityException(msg);
5416 }
5417
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005418 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005419 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005420 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005421 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 TaskRecord curTask = null;
5423 int numActivities = 0;
5424 int numRunning = 0;
5425 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005426 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005428 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429
5430 // Initialize state for next task if needed.
5431 if (top == null ||
5432 (top.state == ActivityState.INITIALIZING
5433 && top.task == r.task)) {
5434 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 curTask = r.task;
5436 numActivities = numRunning = 0;
5437 }
5438
5439 // Add 'r' into the current task.
5440 numActivities++;
5441 if (r.app != null && r.app.thread != null) {
5442 numRunning++;
5443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444
Joe Onorato8a9b2202010-02-26 18:56:32 -08005445 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005446 TAG, r.intent.getComponent().flattenToShortString()
5447 + ": task=" + r.task);
5448
5449 // If the next one is a different task, generate a new
5450 // TaskInfo entry for what we have.
5451 if (next == null || next.task != curTask) {
5452 ActivityManager.RunningTaskInfo ci
5453 = new ActivityManager.RunningTaskInfo();
5454 ci.id = curTask.taskId;
5455 ci.baseActivity = r.intent.getComponent();
5456 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005457 if (top.thumbHolder != null) {
5458 ci.description = top.thumbHolder.lastDescription;
5459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 ci.numActivities = numActivities;
5461 ci.numRunning = numRunning;
5462 //System.out.println(
5463 // "#" + maxNum + ": " + " descr=" + ci.description);
5464 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005465 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 TAG, "State=" + top.state + "Idle=" + top.idle
5467 + " app=" + top.app
5468 + " thr=" + (top.app != null ? top.app.thread : null));
5469 if (top.state == ActivityState.RESUMED
5470 || top.state == ActivityState.PAUSING) {
5471 if (top.idle && top.app != null
5472 && top.app.thread != null) {
5473 topRecord = top;
5474 topThumbnail = top.app.thread;
5475 } else {
5476 top.thumbnailNeeded = true;
5477 }
5478 }
5479 if (pending == null) {
5480 pending = new PendingThumbnailsRecord(receiver);
5481 }
5482 pending.pendingRecords.add(top);
5483 }
5484 list.add(ci);
5485 maxNum--;
5486 top = null;
5487 }
5488 }
5489
5490 if (pending != null) {
5491 mPendingThumbnails.add(pending);
5492 }
5493 }
5494
Joe Onorato8a9b2202010-02-26 18:56:32 -08005495 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496
5497 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005498 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005500 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005502 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005503 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 }
5505 }
5506
5507 if (pending == null && receiver != null) {
5508 // In this case all thumbnails were available and the client
5509 // is being asked to be told when the remaining ones come in...
5510 // which is unusually, since the top-most currently running
5511 // activity should never have a canned thumbnail! Oh well.
5512 try {
5513 receiver.finished();
5514 } catch (RemoteException ex) {
5515 }
5516 }
5517
5518 return list;
5519 }
5520
5521 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005522 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005523 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005524 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005525 // Check if the caller is holding permissions for cross-user requests.
5526 if (checkComponentPermission(
5527 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5528 Binder.getCallingPid(), callingUid, -1, true)
5529 != PackageManager.PERMISSION_GRANTED) {
5530 String msg = "Permission Denial: "
5531 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005532 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005533 + "; this requires "
5534 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5535 Slog.w(TAG, msg);
5536 throw new SecurityException(msg);
5537 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005538 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005539 userId = mCurrentUserId;
5540 }
5541 }
5542 }
5543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 synchronized (this) {
5545 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5546 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005547 final boolean detailed = checkCallingPermission(
5548 android.Manifest.permission.GET_DETAILED_TASKS)
5549 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005551 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 final int N = mRecentTasks.size();
5554 ArrayList<ActivityManager.RecentTaskInfo> res
5555 = new ArrayList<ActivityManager.RecentTaskInfo>(
5556 maxNum < N ? maxNum : N);
5557 for (int i=0; i<N && maxNum > 0; i++) {
5558 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005559 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005560 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005561 // Return the entry if desired by the caller. We always return
5562 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005563 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005564 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5565 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005566
Dianne Hackborn905577f2011-09-07 18:31:28 -07005567 if (i == 0
5568 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 || (tr.intent == null)
5570 || ((tr.intent.getFlags()
5571 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5572 ActivityManager.RecentTaskInfo rti
5573 = new ActivityManager.RecentTaskInfo();
5574 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005575 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005576 rti.baseIntent = new Intent(
5577 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005578 if (!detailed) {
5579 rti.baseIntent.replaceExtras((Bundle)null);
5580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005582 rti.description = tr.lastDescription;
5583
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005584 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5585 // Check whether this activity is currently available.
5586 try {
5587 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005588 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005589 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005590 continue;
5591 }
5592 } else if (rti.baseIntent != null) {
5593 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005594 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005595 continue;
5596 }
5597 }
5598 } catch (RemoteException e) {
5599 // Will never happen.
5600 }
5601 }
5602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 res.add(rti);
5604 maxNum--;
5605 }
5606 }
5607 return res;
5608 }
5609 }
5610
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005611 private TaskRecord taskForIdLocked(int id) {
5612 final int N = mRecentTasks.size();
5613 for (int i=0; i<N; i++) {
5614 TaskRecord tr = mRecentTasks.get(i);
5615 if (tr.taskId == id) {
5616 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005617 }
5618 }
5619 return null;
5620 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005621
5622 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5623 synchronized (this) {
5624 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5625 "getTaskThumbnails()");
5626 TaskRecord tr = taskForIdLocked(id);
5627 if (tr != null) {
5628 return mMainStack.getTaskThumbnailsLocked(tr);
5629 }
5630 }
5631 return null;
5632 }
5633
5634 public boolean removeSubTask(int taskId, int subTaskIndex) {
5635 synchronized (this) {
5636 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5637 "removeSubTask()");
5638 long ident = Binder.clearCallingIdentity();
5639 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005640 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5641 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005642 } finally {
5643 Binder.restoreCallingIdentity(ident);
5644 }
5645 }
5646 }
5647
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005648 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5649 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005650 Intent baseIntent = new Intent(
5651 tr.intent != null ? tr.intent : tr.affinityIntent);
5652 ComponentName component = baseIntent.getComponent();
5653 if (component == null) {
5654 Slog.w(TAG, "Now component for base intent of task: " + tr);
5655 return;
5656 }
5657
5658 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005659 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005660
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005661 if (killProcesses) {
5662 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005663 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005664 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005665 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5666 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5667 for (int i=0; i<uids.size(); i++) {
5668 ProcessRecord proc = uids.valueAt(i);
5669 if (proc.userId != tr.userId) {
5670 continue;
5671 }
5672 if (!proc.pkgList.contains(pkg)) {
5673 continue;
5674 }
5675 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005676 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005677 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005678
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005679 // Kill the running processes.
5680 for (int i=0; i<procs.size(); i++) {
5681 ProcessRecord pr = procs.get(i);
5682 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5683 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5684 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5685 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005686 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005687 Process.killProcessQuiet(pr.pid);
5688 } else {
5689 pr.waitingToKill = "remove task";
5690 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005691 }
5692 }
5693 }
5694
5695 public boolean removeTask(int taskId, int flags) {
5696 synchronized (this) {
5697 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5698 "removeTask()");
5699 long ident = Binder.clearCallingIdentity();
5700 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005701 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5702 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 if (r != null) {
5704 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005705 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005706 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005707 } else {
5708 TaskRecord tr = null;
5709 int i=0;
5710 while (i < mRecentTasks.size()) {
5711 TaskRecord t = mRecentTasks.get(i);
5712 if (t.taskId == taskId) {
5713 tr = t;
5714 break;
5715 }
5716 i++;
5717 }
5718 if (tr != null) {
5719 if (tr.numActivities <= 0) {
5720 // Caller is just removing a recent task that is
5721 // not actively running. That is easy!
5722 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005723 cleanUpRemovedTaskLocked(tr, flags);
5724 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005725 } else {
5726 Slog.w(TAG, "removeTask: task " + taskId
5727 + " does not have activities to remove, "
5728 + " but numActivities=" + tr.numActivities
5729 + ": " + tr);
5730 }
5731 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005732 }
5733 } finally {
5734 Binder.restoreCallingIdentity(ident);
5735 }
5736 }
5737 return false;
5738 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5741 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005742 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 TaskRecord jt = startTask;
5744
5745 // First look backwards
5746 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005747 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 if (r.task != jt) {
5749 jt = r.task;
5750 if (affinity.equals(jt.affinity)) {
5751 return j;
5752 }
5753 }
5754 }
5755
5756 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005757 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 jt = startTask;
5759 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005760 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005761 if (r.task != jt) {
5762 if (affinity.equals(jt.affinity)) {
5763 return j;
5764 }
5765 jt = r.task;
5766 }
5767 }
5768
5769 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005770 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 return N-1;
5772 }
5773
5774 return -1;
5775 }
5776
5777 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005778 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005780 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005781 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5782 "moveTaskToFront()");
5783
5784 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005785 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5786 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005787 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005788 return;
5789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 final long origId = Binder.clearCallingIdentity();
5791 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005792 TaskRecord tr = taskForIdLocked(task);
5793 if (tr != null) {
5794 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5795 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005796 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005797 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5798 // Caller wants the home activity moved with it. To accomplish this,
5799 // we'll just move the home task to the top first.
5800 mMainStack.moveHomeToFrontLocked();
5801 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005802 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005803 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005805 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5806 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005808 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5809 mMainStack.mUserLeaving = true;
5810 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005811 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5812 // Caller wants the home activity moved with it. To accomplish this,
5813 // we'll just move the home task to the top first.
5814 mMainStack.moveHomeToFrontLocked();
5815 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005816 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 return;
5818 }
5819 }
5820 } finally {
5821 Binder.restoreCallingIdentity(origId);
5822 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005823 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 }
5825 }
5826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005827 public void moveTaskToBack(int task) {
5828 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5829 "moveTaskToBack()");
5830
5831 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005832 if (mMainStack.mResumedActivity != null
5833 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005834 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5835 Binder.getCallingUid(), "Task to back")) {
5836 return;
5837 }
5838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005840 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 Binder.restoreCallingIdentity(origId);
5842 }
5843 }
5844
5845 /**
5846 * Moves an activity, and all of the other activities within the same task, to the bottom
5847 * of the history stack. The activity's order within the task is unchanged.
5848 *
5849 * @param token A reference to the activity we wish to move
5850 * @param nonRoot If false then this only works if the activity is the root
5851 * of a task; if true it will work for any activity in a task.
5852 * @return Returns true if the move completed, false if not.
5853 */
5854 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005855 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 synchronized(this) {
5857 final long origId = Binder.clearCallingIdentity();
5858 int taskId = getTaskForActivityLocked(token, !nonRoot);
5859 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005860 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 }
5862 Binder.restoreCallingIdentity(origId);
5863 }
5864 return false;
5865 }
5866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 public void moveTaskBackwards(int task) {
5868 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5869 "moveTaskBackwards()");
5870
5871 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005872 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5873 Binder.getCallingUid(), "Task backwards")) {
5874 return;
5875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 final long origId = Binder.clearCallingIdentity();
5877 moveTaskBackwardsLocked(task);
5878 Binder.restoreCallingIdentity(origId);
5879 }
5880 }
5881
5882 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005883 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 }
5885
5886 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5887 synchronized(this) {
5888 return getTaskForActivityLocked(token, onlyRoot);
5889 }
5890 }
5891
5892 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005893 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 TaskRecord lastTask = null;
5895 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005896 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005897 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 if (!onlyRoot || lastTask != r.task) {
5899 return r.task.taskId;
5900 }
5901 return -1;
5902 }
5903 lastTask = r.task;
5904 }
5905
5906 return -1;
5907 }
5908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005909 // =========================================================
5910 // THUMBNAILS
5911 // =========================================================
5912
5913 public void reportThumbnail(IBinder token,
5914 Bitmap thumbnail, CharSequence description) {
5915 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5916 final long origId = Binder.clearCallingIdentity();
5917 sendPendingThumbnail(null, token, thumbnail, description, true);
5918 Binder.restoreCallingIdentity(origId);
5919 }
5920
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005921 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 Bitmap thumbnail, CharSequence description, boolean always) {
5923 TaskRecord task = null;
5924 ArrayList receivers = null;
5925
5926 //System.out.println("Send pending thumbnail: " + r);
5927
5928 synchronized(this) {
5929 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005930 r = mMainStack.isInStackLocked(token);
5931 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 return;
5933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005935 if (thumbnail == null && r.thumbHolder != null) {
5936 thumbnail = r.thumbHolder.lastThumbnail;
5937 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 }
5939 if (thumbnail == null && !always) {
5940 // If there is no thumbnail, and this entry is not actually
5941 // going away, then abort for now and pick up the next
5942 // thumbnail we get.
5943 return;
5944 }
5945 task = r.task;
5946
5947 int N = mPendingThumbnails.size();
5948 int i=0;
5949 while (i<N) {
5950 PendingThumbnailsRecord pr =
5951 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5952 //System.out.println("Looking in " + pr.pendingRecords);
5953 if (pr.pendingRecords.remove(r)) {
5954 if (receivers == null) {
5955 receivers = new ArrayList();
5956 }
5957 receivers.add(pr);
5958 if (pr.pendingRecords.size() == 0) {
5959 pr.finished = true;
5960 mPendingThumbnails.remove(i);
5961 N--;
5962 continue;
5963 }
5964 }
5965 i++;
5966 }
5967 }
5968
5969 if (receivers != null) {
5970 final int N = receivers.size();
5971 for (int i=0; i<N; i++) {
5972 try {
5973 PendingThumbnailsRecord pr =
5974 (PendingThumbnailsRecord)receivers.get(i);
5975 pr.receiver.newThumbnail(
5976 task != null ? task.taskId : -1, thumbnail, description);
5977 if (pr.finished) {
5978 pr.receiver.finished();
5979 }
5980 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005981 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 }
5983 }
5984 }
5985 }
5986
5987 // =========================================================
5988 // CONTENT PROVIDERS
5989 // =========================================================
5990
Jeff Brown10e89712011-07-08 18:52:57 -07005991 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5992 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005994 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005995 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005996 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 } catch (RemoteException ex) {
5998 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005999 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006000 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6001 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006003 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 for (int i=0; i<N; i++) {
6005 ProviderInfo cpi =
6006 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006007 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6008 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006009 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006010 // This is a singleton provider, but a user besides the
6011 // default user is asking to initialize a process it runs
6012 // in... well, no, it doesn't actually run in this process,
6013 // it runs in the process of the default user. Get rid of it.
6014 providers.remove(i);
6015 N--;
6016 continue;
6017 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006018
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006019 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006020 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006021 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006022 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006023 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006024 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006025 if (DEBUG_MU)
6026 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006027 app.pubProviders.put(cpi.name, cpr);
6028 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006029 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 }
6031 }
6032 return providers;
6033 }
6034
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006035 /**
6036 * Check if {@link ProcessRecord} has a possible chance at accessing the
6037 * given {@link ProviderInfo}. Final permission checking is always done
6038 * in {@link ContentProvider}.
6039 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006041 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006043 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006045 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006046 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 return null;
6048 }
6049 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006050 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 == PackageManager.PERMISSION_GRANTED) {
6052 return null;
6053 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006054
6055 PathPermission[] pps = cpi.pathPermissions;
6056 if (pps != null) {
6057 int i = pps.length;
6058 while (i > 0) {
6059 i--;
6060 PathPermission pp = pps[i];
6061 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006062 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006063 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006064 return null;
6065 }
6066 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006067 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006068 == PackageManager.PERMISSION_GRANTED) {
6069 return null;
6070 }
6071 }
6072 }
6073
Dianne Hackbornb424b632010-08-18 15:59:05 -07006074 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6075 if (perms != null) {
6076 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6077 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6078 return null;
6079 }
6080 }
6081 }
6082
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006083 String msg;
6084 if (!cpi.exported) {
6085 msg = "Permission Denial: opening provider " + cpi.name
6086 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6087 + ", uid=" + callingUid + ") that is not exported from uid "
6088 + cpi.applicationInfo.uid;
6089 } else {
6090 msg = "Permission Denial: opening provider " + cpi.name
6091 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6092 + ", uid=" + callingUid + ") requires "
6093 + cpi.readPermission + " or " + cpi.writePermission;
6094 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006095 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006096 return msg;
6097 }
6098
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006099 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6100 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006101 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006102 for (int i=0; i<r.conProviders.size(); i++) {
6103 ContentProviderConnection conn = r.conProviders.get(i);
6104 if (conn.provider == cpr) {
6105 if (DEBUG_PROVIDER) Slog.v(TAG,
6106 "Adding provider requested by "
6107 + r.processName + " from process "
6108 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6109 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6110 if (stable) {
6111 conn.stableCount++;
6112 conn.numStableIncs++;
6113 } else {
6114 conn.unstableCount++;
6115 conn.numUnstableIncs++;
6116 }
6117 return conn;
6118 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006120 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6121 if (stable) {
6122 conn.stableCount = 1;
6123 conn.numStableIncs = 1;
6124 } else {
6125 conn.unstableCount = 1;
6126 conn.numUnstableIncs = 1;
6127 }
6128 cpr.connections.add(conn);
6129 r.conProviders.add(conn);
6130 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006131 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006132 cpr.addExternalProcessHandleLocked(externalProcessToken);
6133 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006134 }
6135
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006136 boolean decProviderCountLocked(ContentProviderConnection conn,
6137 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6138 if (conn != null) {
6139 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006140 if (DEBUG_PROVIDER) Slog.v(TAG,
6141 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006142 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006144 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6145 if (stable) {
6146 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006147 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006148 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006149 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006150 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6151 cpr.connections.remove(conn);
6152 conn.client.conProviders.remove(conn);
6153 return true;
6154 }
6155 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006156 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006157 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006158 return false;
6159 }
6160
Amith Yamasani742a6712011-05-04 14:49:28 -07006161 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006162 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006164 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 ProviderInfo cpi = null;
6166
6167 synchronized(this) {
6168 ProcessRecord r = null;
6169 if (caller != null) {
6170 r = getRecordForAppLocked(caller);
6171 if (r == null) {
6172 throw new SecurityException(
6173 "Unable to find app for caller " + caller
6174 + " (pid=" + Binder.getCallingPid()
6175 + ") when getting content provider " + name);
6176 }
6177 }
6178
6179 // First check if this content provider has been published...
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006180 int userId = UserHandle.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006181 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006182 boolean providerRunning = cpr != null;
6183 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006185 String msg;
6186 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6187 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 }
6189
6190 if (r != null && cpr.canRunHere(r)) {
6191 // This provider has been published or is in the process
6192 // of being published... but it is also allowed to run
6193 // in the caller's process, so don't make a connection
6194 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006195 ContentProviderHolder holder = cpr.newHolder(null);
6196 // don't give caller the provider object, it needs
6197 // to make its own.
6198 holder.provider = null;
6199 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 }
6201
6202 final long origId = Binder.clearCallingIdentity();
6203
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006204 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006206 conn = incProviderCountLocked(r, cpr, token, stable);
6207 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006208 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006209 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006210 // make sure to count it as being accessed and thus
6211 // back up on the LRU list. This is good because
6212 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006213 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006214 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006215 }
6216
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006217 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006218 if (false) {
6219 if (cpr.name.flattenToShortString().equals(
6220 "com.android.providers.calendar/.CalendarProvider2")) {
6221 Slog.v(TAG, "****************** KILLING "
6222 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006223 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006224 }
6225 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006226 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006227 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6228 // NOTE: there is still a race here where a signal could be
6229 // pending on the process even though we managed to update its
6230 // adj level. Not sure what to do about this, but at least
6231 // the race is now smaller.
6232 if (!success) {
6233 // Uh oh... it looks like the provider's process
6234 // has been killed on us. We need to wait for a new
6235 // process to be started, and make sure its death
6236 // doesn't kill our process.
6237 Slog.i(TAG,
6238 "Existing provider " + cpr.name.flattenToShortString()
6239 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006240 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006241 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006242 if (!lastRef) {
6243 // This wasn't the last ref our process had on
6244 // the provider... we have now been killed, bail.
6245 return null;
6246 }
6247 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006248 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 }
6251
6252 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006255 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006258 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006259 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006260 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 } catch (RemoteException ex) {
6262 }
6263 if (cpi == null) {
6264 return null;
6265 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006266 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6267 cpi.name, cpi.flags);
6268 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006269 userId = 0;
6270 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006271 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006272
Dianne Hackbornb424b632010-08-18 15:59:05 -07006273 String msg;
6274 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6275 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
6277
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006278 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006279 && !cpi.processName.equals("system")) {
6280 // If this content provider does not run in the system
6281 // process, and the system is not yet ready to run other
6282 // processes, then fail fast instead of hanging.
6283 throw new IllegalArgumentException(
6284 "Attempt to launch content provider before system ready");
6285 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006286
6287 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006288 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 final boolean firstClass = cpr == null;
6290 if (firstClass) {
6291 try {
6292 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006293 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 getApplicationInfo(
6295 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006296 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006298 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 + cpi.name);
6300 return null;
6301 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006302 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006303 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 } catch (RemoteException ex) {
6305 // pm is in same process, this will never happen.
6306 }
6307 }
6308
6309 if (r != null && cpr.canRunHere(r)) {
6310 // If this is a multiprocess provider, then just return its
6311 // info and allow the caller to instantiate it. Only do
6312 // this if the provider is the same user as the caller's
6313 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006314 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 }
6316
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006317 if (DEBUG_PROVIDER) {
6318 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006319 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006320 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 }
6322
6323 // This is single process, and our app is now connecting to it.
6324 // See if we are already in the process of launching this
6325 // provider.
6326 final int N = mLaunchingProviders.size();
6327 int i;
6328 for (i=0; i<N; i++) {
6329 if (mLaunchingProviders.get(i) == cpr) {
6330 break;
6331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
6333
6334 // If the provider is not already being launched, then get it
6335 // started.
6336 if (i >= N) {
6337 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006338
6339 try {
6340 // Content provider is now in use, its package can't be stopped.
6341 try {
6342 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006343 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006344 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006345 } catch (IllegalArgumentException e) {
6346 Slog.w(TAG, "Failed trying to unstop package "
6347 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006348 }
6349
6350 ProcessRecord proc = startProcessLocked(cpi.processName,
6351 cpr.appInfo, false, 0, "content provider",
6352 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006353 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006354 if (proc == null) {
6355 Slog.w(TAG, "Unable to launch app "
6356 + cpi.applicationInfo.packageName + "/"
6357 + cpi.applicationInfo.uid + " for provider "
6358 + name + ": process is bad");
6359 return null;
6360 }
6361 cpr.launchingApp = proc;
6362 mLaunchingProviders.add(cpr);
6363 } finally {
6364 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
6367
6368 // Make sure the provider is published (the same provider class
6369 // may be published under multiple names).
6370 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006371 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006373
Amith Yamasani742a6712011-05-04 14:49:28 -07006374 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006375 conn = incProviderCountLocked(r, cpr, token, stable);
6376 if (conn != null) {
6377 conn.waiting = true;
6378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 }
6380 }
6381
6382 // Wait for the provider to be published...
6383 synchronized (cpr) {
6384 while (cpr.provider == null) {
6385 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006386 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 + cpi.applicationInfo.packageName + "/"
6388 + cpi.applicationInfo.uid + " for provider "
6389 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006390 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 cpi.applicationInfo.packageName,
6392 cpi.applicationInfo.uid, name);
6393 return null;
6394 }
6395 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006396 if (DEBUG_MU) {
6397 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6398 + cpr.launchingApp);
6399 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006400 if (conn != null) {
6401 conn.waiting = true;
6402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 cpr.wait();
6404 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006405 } finally {
6406 if (conn != null) {
6407 conn.waiting = false;
6408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 }
6410 }
6411 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006412 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 }
6414
6415 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006416 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006417 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 if (caller == null) {
6419 String msg = "null IApplicationThread when getting content provider "
6420 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006421 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 throw new SecurityException(msg);
6423 }
6424
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006425 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 }
6427
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006428 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6429 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6430 "Do not have permission in call getContentProviderExternal()");
6431 return getContentProviderExternalUnchecked(name, token);
6432 }
6433
6434 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006435 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 }
6437
6438 /**
6439 * Drop a content provider from a ProcessRecord's bookkeeping
6440 * @param cpr
6441 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006442 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006443 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006445 ContentProviderConnection conn;
6446 try {
6447 conn = (ContentProviderConnection)connection;
6448 } catch (ClassCastException e) {
6449 String msg ="removeContentProvider: " + connection
6450 + " not a ContentProviderConnection";
6451 Slog.w(TAG, msg);
6452 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006454 if (conn == null) {
6455 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006457 if (decProviderCountLocked(conn, null, null, stable)) {
6458 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 }
6461 }
6462
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006463 public void removeContentProviderExternal(String name, IBinder token) {
6464 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6465 "Do not have permission in call removeContentProviderExternal()");
6466 removeContentProviderExternalUnchecked(name, token);
6467 }
6468
6469 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006471 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6472 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 if(cpr == null) {
6474 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006475 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 return;
6477 }
6478
6479 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006480 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006481 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6482 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006483 if (localCpr.hasExternalProcessHandles()) {
6484 if (localCpr.removeExternalProcessHandleLocked(token)) {
6485 updateOomAdjLocked();
6486 } else {
6487 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6488 + " with no external reference for token: "
6489 + token + ".");
6490 }
6491 } else {
6492 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6493 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496 }
6497
6498 public final void publishContentProviders(IApplicationThread caller,
6499 List<ContentProviderHolder> providers) {
6500 if (providers == null) {
6501 return;
6502 }
6503
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006504 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006505 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006507 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006508 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 if (r == null) {
6510 throw new SecurityException(
6511 "Unable to find app for caller " + caller
6512 + " (pid=" + Binder.getCallingPid()
6513 + ") when publishing content providers");
6514 }
6515
6516 final long origId = Binder.clearCallingIdentity();
6517
6518 final int N = providers.size();
6519 for (int i=0; i<N; i++) {
6520 ContentProviderHolder src = providers.get(i);
6521 if (src == null || src.info == null || src.provider == null) {
6522 continue;
6523 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006524 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006525 if (DEBUG_MU)
6526 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006528 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006529 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 String names[] = dst.info.authority.split(";");
6531 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006532 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
6534
6535 int NL = mLaunchingProviders.size();
6536 int j;
6537 for (j=0; j<NL; j++) {
6538 if (mLaunchingProviders.get(j) == dst) {
6539 mLaunchingProviders.remove(j);
6540 j--;
6541 NL--;
6542 }
6543 }
6544 synchronized (dst) {
6545 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006546 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 dst.notifyAll();
6548 }
6549 updateOomAdjLocked(r);
6550 }
6551 }
6552
6553 Binder.restoreCallingIdentity(origId);
6554 }
6555 }
6556
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006557 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6558 ContentProviderConnection conn;
6559 try {
6560 conn = (ContentProviderConnection)connection;
6561 } catch (ClassCastException e) {
6562 String msg ="refContentProvider: " + connection
6563 + " not a ContentProviderConnection";
6564 Slog.w(TAG, msg);
6565 throw new IllegalArgumentException(msg);
6566 }
6567 if (conn == null) {
6568 throw new NullPointerException("connection is null");
6569 }
6570
6571 synchronized (this) {
6572 if (stable > 0) {
6573 conn.numStableIncs += stable;
6574 }
6575 stable = conn.stableCount + stable;
6576 if (stable < 0) {
6577 throw new IllegalStateException("stableCount < 0: " + stable);
6578 }
6579
6580 if (unstable > 0) {
6581 conn.numUnstableIncs += unstable;
6582 }
6583 unstable = conn.unstableCount + unstable;
6584 if (unstable < 0) {
6585 throw new IllegalStateException("unstableCount < 0: " + unstable);
6586 }
6587
6588 if ((stable+unstable) <= 0) {
6589 throw new IllegalStateException("ref counts can't go to zero here: stable="
6590 + stable + " unstable=" + unstable);
6591 }
6592 conn.stableCount = stable;
6593 conn.unstableCount = unstable;
6594 return !conn.dead;
6595 }
6596 }
6597
6598 public void unstableProviderDied(IBinder connection) {
6599 ContentProviderConnection conn;
6600 try {
6601 conn = (ContentProviderConnection)connection;
6602 } catch (ClassCastException e) {
6603 String msg ="refContentProvider: " + connection
6604 + " not a ContentProviderConnection";
6605 Slog.w(TAG, msg);
6606 throw new IllegalArgumentException(msg);
6607 }
6608 if (conn == null) {
6609 throw new NullPointerException("connection is null");
6610 }
6611
6612 // Safely retrieve the content provider associated with the connection.
6613 IContentProvider provider;
6614 synchronized (this) {
6615 provider = conn.provider.provider;
6616 }
6617
6618 if (provider == null) {
6619 // Um, yeah, we're way ahead of you.
6620 return;
6621 }
6622
6623 // Make sure the caller is being honest with us.
6624 if (provider.asBinder().pingBinder()) {
6625 // Er, no, still looks good to us.
6626 synchronized (this) {
6627 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6628 + " says " + conn + " died, but we don't agree");
6629 return;
6630 }
6631 }
6632
6633 // Well look at that! It's dead!
6634 synchronized (this) {
6635 if (conn.provider.provider != provider) {
6636 // But something changed... good enough.
6637 return;
6638 }
6639
6640 ProcessRecord proc = conn.provider.proc;
6641 if (proc == null || proc.thread == null) {
6642 // Seems like the process is already cleaned up.
6643 return;
6644 }
6645
6646 // As far as we're concerned, this is just like receiving a
6647 // death notification... just a bit prematurely.
6648 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6649 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006650 final long ident = Binder.clearCallingIdentity();
6651 try {
6652 appDiedLocked(proc, proc.pid, proc.thread);
6653 } finally {
6654 Binder.restoreCallingIdentity(ident);
6655 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006656 }
6657 }
6658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006660 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006661 synchronized (mSelf) {
6662 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6663 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006664 if (providers != null) {
6665 for (int i=providers.size()-1; i>=0; i--) {
6666 ProviderInfo pi = (ProviderInfo)providers.get(i);
6667 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6668 Slog.w(TAG, "Not installing system proc provider " + pi.name
6669 + ": not system .apk");
6670 providers.remove(i);
6671 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006672 }
6673 }
6674 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006675 if (providers != null) {
6676 mSystemThread.installSystemProviders(providers);
6677 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006678
6679 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006680
6681 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 }
6683
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006684 /**
6685 * Allows app to retrieve the MIME type of a URI without having permission
6686 * to access its content provider.
6687 *
6688 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6689 *
6690 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6691 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6692 */
6693 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006694 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006695 final String name = uri.getAuthority();
6696 final long ident = Binder.clearCallingIdentity();
6697 ContentProviderHolder holder = null;
6698
6699 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006700 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006701 if (holder != null) {
6702 return holder.provider.getType(uri);
6703 }
6704 } catch (RemoteException e) {
6705 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6706 return null;
6707 } finally {
6708 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006709 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006710 }
6711 Binder.restoreCallingIdentity(ident);
6712 }
6713
6714 return null;
6715 }
6716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 // =========================================================
6718 // GLOBAL MANAGEMENT
6719 // =========================================================
6720
6721 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006722 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 String proc = customProcess != null ? customProcess : info.processName;
6724 BatteryStatsImpl.Uid.Proc ps = null;
6725 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006726 int uid = info.uid;
6727 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006728 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006729 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6730 uid = 0;
6731 while (true) {
6732 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6733 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6734 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6735 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006736 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006737 mNextIsolatedProcessUid++;
6738 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6739 // No process for this uid, use it.
6740 break;
6741 }
6742 stepsLeft--;
6743 if (stepsLeft <= 0) {
6744 return null;
6745 }
6746 }
6747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006748 synchronized (stats) {
6749 ps = stats.getProcessStatsLocked(info.uid, proc);
6750 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006751 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 }
6753
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006754 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6755 ProcessRecord app;
6756 if (!isolated) {
6757 app = getProcessRecordLocked(info.processName, info.uid);
6758 } else {
6759 app = null;
6760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761
6762 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006763 app = newProcessRecordLocked(null, info, null, isolated);
6764 mProcessNames.put(info.processName, app.uid, app);
6765 if (isolated) {
6766 mIsolatedProcesses.put(app.uid, app);
6767 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006768 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 }
6770
Dianne Hackborne7f97212011-02-24 14:40:20 -08006771 // This package really, really can not be stopped.
6772 try {
6773 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006774 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006775 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006776 } catch (IllegalArgumentException e) {
6777 Slog.w(TAG, "Failed trying to unstop package "
6778 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006779 }
6780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006781 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6782 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6783 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006784 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 }
6786 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6787 mPersistentStartingProcesses.add(app);
6788 startProcessLocked(app, "added application", app.processName);
6789 }
6790
6791 return app;
6792 }
6793
6794 public void unhandledBack() {
6795 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6796 "unhandledBack()");
6797
6798 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006799 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006800 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 TAG, "Performing unhandledBack(): stack size = " + count);
6802 if (count > 1) {
6803 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006804 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6806 Binder.restoreCallingIdentity(origId);
6807 }
6808 }
6809 }
6810
6811 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006812 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006814 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006815 ParcelFileDescriptor pfd = null;
6816 if (cph != null) {
6817 // We record the binder invoker's uid in thread-local storage before
6818 // going to the content provider to open the file. Later, in the code
6819 // that handles all permissions checks, we look for this uid and use
6820 // that rather than the Activity Manager's own uid. The effect is that
6821 // we do the check against the caller's permissions even though it looks
6822 // to the content provider like the Activity Manager itself is making
6823 // the request.
6824 sCallerIdentity.set(new Identity(
6825 Binder.getCallingPid(), Binder.getCallingUid()));
6826 try {
6827 pfd = cph.provider.openFile(uri, "r");
6828 } catch (FileNotFoundException e) {
6829 // do nothing; pfd will be returned null
6830 } finally {
6831 // Ensure that whatever happens, we clean up the identity state
6832 sCallerIdentity.remove();
6833 }
6834
6835 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006836 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006838 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 }
6840 return pfd;
6841 }
6842
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006843 // Actually is sleeping or shutting down or whatever else in the future
6844 // is an inactive state.
6845 public boolean isSleeping() {
6846 return mSleeping || mShuttingDown;
6847 }
6848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006850 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6851 != PackageManager.PERMISSION_GRANTED) {
6852 throw new SecurityException("Requires permission "
6853 + android.Manifest.permission.DEVICE_POWER);
6854 }
6855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006857 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006858 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006860 if (!mSleeping) {
6861 mSleeping = true;
6862 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006863
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006864 // Initialize the wake times of all processes.
6865 checkExcessivePowerUsageLocked(false);
6866 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6867 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6868 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 }
6871 }
6872
Dianne Hackborn55280a92009-05-07 15:53:46 -07006873 public boolean shutdown(int timeout) {
6874 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6875 != PackageManager.PERMISSION_GRANTED) {
6876 throw new SecurityException("Requires permission "
6877 + android.Manifest.permission.SHUTDOWN);
6878 }
6879
6880 boolean timedout = false;
6881
6882 synchronized(this) {
6883 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006884 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006885
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006886 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006887 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006888 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006889 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006890 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006891 long delay = endTime - System.currentTimeMillis();
6892 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006893 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006894 timedout = true;
6895 break;
6896 }
6897 try {
6898 this.wait();
6899 } catch (InterruptedException e) {
6900 }
6901 }
6902 }
6903 }
6904
6905 mUsageStatsService.shutdown();
6906 mBatteryStatsService.shutdown();
6907
6908 return timedout;
6909 }
6910
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006911 public final void activitySlept(IBinder token) {
6912 if (localLOGV) Slog.v(
6913 TAG, "Activity slept: token=" + token);
6914
6915 ActivityRecord r = null;
6916
6917 final long origId = Binder.clearCallingIdentity();
6918
6919 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006920 r = mMainStack.isInStackLocked(token);
6921 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006922 mMainStack.activitySleptLocked(r);
6923 }
6924 }
6925
6926 Binder.restoreCallingIdentity(origId);
6927 }
6928
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006929 private void comeOutOfSleepIfNeededLocked() {
6930 if (!mWentToSleep && !mLockScreenShown) {
6931 if (mSleeping) {
6932 mSleeping = false;
6933 mMainStack.awakeFromSleepingLocked();
6934 mMainStack.resumeTopActivityLocked(null);
6935 }
6936 }
6937 }
6938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006940 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6941 != PackageManager.PERMISSION_GRANTED) {
6942 throw new SecurityException("Requires permission "
6943 + android.Manifest.permission.DEVICE_POWER);
6944 }
6945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006947 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006948 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006949 comeOutOfSleepIfNeededLocked();
6950 }
6951 }
6952
Jeff Brownc042ee22012-05-08 13:03:42 -07006953 private void updateEventDispatchingLocked() {
6954 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6955 }
6956
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006957 public void setLockScreenShown(boolean shown) {
6958 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6959 != PackageManager.PERMISSION_GRANTED) {
6960 throw new SecurityException("Requires permission "
6961 + android.Manifest.permission.DEVICE_POWER);
6962 }
6963
6964 synchronized(this) {
6965 mLockScreenShown = shown;
6966 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 }
6968 }
6969
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006970 public void stopAppSwitches() {
6971 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6972 != PackageManager.PERMISSION_GRANTED) {
6973 throw new SecurityException("Requires permission "
6974 + android.Manifest.permission.STOP_APP_SWITCHES);
6975 }
6976
6977 synchronized(this) {
6978 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6979 + APP_SWITCH_DELAY_TIME;
6980 mDidAppSwitch = false;
6981 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6982 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6983 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6984 }
6985 }
6986
6987 public void resumeAppSwitches() {
6988 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6989 != PackageManager.PERMISSION_GRANTED) {
6990 throw new SecurityException("Requires permission "
6991 + android.Manifest.permission.STOP_APP_SWITCHES);
6992 }
6993
6994 synchronized(this) {
6995 // Note that we don't execute any pending app switches... we will
6996 // let those wait until either the timeout, or the next start
6997 // activity request.
6998 mAppSwitchesAllowedTime = 0;
6999 }
7000 }
7001
7002 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7003 String name) {
7004 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7005 return true;
7006 }
7007
7008 final int perm = checkComponentPermission(
7009 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007010 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007011 if (perm == PackageManager.PERMISSION_GRANTED) {
7012 return true;
7013 }
7014
Joe Onorato8a9b2202010-02-26 18:56:32 -08007015 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007016 return false;
7017 }
7018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007019 public void setDebugApp(String packageName, boolean waitForDebugger,
7020 boolean persistent) {
7021 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7022 "setDebugApp()");
7023
7024 // Note that this is not really thread safe if there are multiple
7025 // callers into it at the same time, but that's not a situation we
7026 // care about.
7027 if (persistent) {
7028 final ContentResolver resolver = mContext.getContentResolver();
7029 Settings.System.putString(
7030 resolver, Settings.System.DEBUG_APP,
7031 packageName);
7032 Settings.System.putInt(
7033 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7034 waitForDebugger ? 1 : 0);
7035 }
7036
7037 synchronized (this) {
7038 if (!persistent) {
7039 mOrigDebugApp = mDebugApp;
7040 mOrigWaitForDebugger = mWaitForDebugger;
7041 }
7042 mDebugApp = packageName;
7043 mWaitForDebugger = waitForDebugger;
7044 mDebugTransient = !persistent;
7045 if (packageName != null) {
7046 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007047 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 Binder.restoreCallingIdentity(origId);
7049 }
7050 }
7051 }
7052
Siva Velusamy92a8b222012-03-09 16:24:04 -08007053 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7054 synchronized (this) {
7055 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7056 if (!isDebuggable) {
7057 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7058 throw new SecurityException("Process not debuggable: " + app.packageName);
7059 }
7060 }
7061
7062 mOpenGlTraceApp = processName;
7063 }
7064 }
7065
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007066 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7067 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7068 synchronized (this) {
7069 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7070 if (!isDebuggable) {
7071 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7072 throw new SecurityException("Process not debuggable: " + app.packageName);
7073 }
7074 }
7075 mProfileApp = processName;
7076 mProfileFile = profileFile;
7077 if (mProfileFd != null) {
7078 try {
7079 mProfileFd.close();
7080 } catch (IOException e) {
7081 }
7082 mProfileFd = null;
7083 }
7084 mProfileFd = profileFd;
7085 mProfileType = 0;
7086 mAutoStopProfiler = autoStopProfiler;
7087 }
7088 }
7089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007090 public void setAlwaysFinish(boolean enabled) {
7091 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7092 "setAlwaysFinish()");
7093
7094 Settings.System.putInt(
7095 mContext.getContentResolver(),
7096 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7097
7098 synchronized (this) {
7099 mAlwaysFinishActivities = enabled;
7100 }
7101 }
7102
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007103 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007105 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007107 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 }
7109 }
7110
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007111 public boolean isUserAMonkey() {
7112 // For now the fact that there is a controller implies
7113 // we have a monkey.
7114 synchronized (this) {
7115 return mController != null;
7116 }
7117 }
7118
Jeff Sharkeya4620792011-05-20 15:29:23 -07007119 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007120 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7121 "registerProcessObserver()");
7122 synchronized (this) {
7123 mProcessObservers.register(observer);
7124 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007125 }
7126
7127 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007128 synchronized (this) {
7129 mProcessObservers.unregister(observer);
7130 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007131 }
7132
Daniel Sandler69a48172010-06-23 16:29:36 -04007133 public void setImmersive(IBinder token, boolean immersive) {
7134 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007135 ActivityRecord r = mMainStack.isInStackLocked(token);
7136 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007137 throw new IllegalArgumentException();
7138 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007139 r.immersive = immersive;
7140 }
7141 }
7142
7143 public boolean isImmersive(IBinder token) {
7144 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007145 ActivityRecord r = mMainStack.isInStackLocked(token);
7146 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007147 throw new IllegalArgumentException();
7148 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007149 return r.immersive;
7150 }
7151 }
7152
7153 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007154 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007155 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007156 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007157 return (r != null) ? r.immersive : false;
7158 }
7159 }
7160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 public final void enterSafeMode() {
7162 synchronized(this) {
7163 // It only makes sense to do this before the system is ready
7164 // and started launching other packages.
7165 if (!mSystemReady) {
7166 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007167 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 } catch (RemoteException e) {
7169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 }
7171 }
7172 }
7173
Jeff Brownb09abc12011-01-13 21:08:27 -08007174 public final void showSafeModeOverlay() {
7175 View v = LayoutInflater.from(mContext).inflate(
7176 com.android.internal.R.layout.safe_mode, null);
7177 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7178 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7179 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7180 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007181 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007182 lp.format = v.getBackground().getOpacity();
7183 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7184 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7185 ((WindowManager)mContext.getSystemService(
7186 Context.WINDOW_SERVICE)).addView(v, lp);
7187 }
7188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 public void noteWakeupAlarm(IIntentSender sender) {
7190 if (!(sender instanceof PendingIntentRecord)) {
7191 return;
7192 }
7193 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7194 synchronized (stats) {
7195 if (mBatteryStatsService.isOnBattery()) {
7196 mBatteryStatsService.enforceCallingPermission();
7197 PendingIntentRecord rec = (PendingIntentRecord)sender;
7198 int MY_UID = Binder.getCallingUid();
7199 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7200 BatteryStatsImpl.Uid.Pkg pkg =
7201 stats.getPackageStatsLocked(uid, rec.key.packageName);
7202 pkg.incWakeupsLocked();
7203 }
7204 }
7205 }
7206
Dianne Hackborn64825172011-03-02 21:32:58 -08007207 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007209 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007211 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007212 // XXX Note: don't acquire main activity lock here, because the window
7213 // manager calls in with its locks held.
7214
7215 boolean killed = false;
7216 synchronized (mPidsSelfLocked) {
7217 int[] types = new int[pids.length];
7218 int worstType = 0;
7219 for (int i=0; i<pids.length; i++) {
7220 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7221 if (proc != null) {
7222 int type = proc.setAdj;
7223 types[i] = type;
7224 if (type > worstType) {
7225 worstType = type;
7226 }
7227 }
7228 }
7229
Dianne Hackborn64825172011-03-02 21:32:58 -08007230 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007232 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7233 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007234 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007235 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007236
7237 // If this is not a secure call, don't let it kill processes that
7238 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007239 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7240 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007241 }
7242
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007243 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 for (int i=0; i<pids.length; i++) {
7245 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7246 if (proc == null) {
7247 continue;
7248 }
7249 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007250 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007251 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007252 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7253 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007255 proc.killedBackground = true;
7256 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 }
7258 }
7259 }
7260 return killed;
7261 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007262
7263 @Override
7264 public boolean killProcessesBelowForeground(String reason) {
7265 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7266 throw new SecurityException("killProcessesBelowForeground() only available to system");
7267 }
7268
7269 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7270 }
7271
7272 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7273 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7274 throw new SecurityException("killProcessesBelowAdj() only available to system");
7275 }
7276
7277 boolean killed = false;
7278 synchronized (mPidsSelfLocked) {
7279 final int size = mPidsSelfLocked.size();
7280 for (int i = 0; i < size; i++) {
7281 final int pid = mPidsSelfLocked.keyAt(i);
7282 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7283 if (proc == null) continue;
7284
7285 final int adj = proc.setAdj;
7286 if (adj > belowAdj && !proc.killedBackground) {
7287 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7288 EventLog.writeEvent(
7289 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7290 killed = true;
7291 proc.killedBackground = true;
7292 Process.killProcessQuiet(pid);
7293 }
7294 }
7295 }
7296 return killed;
7297 }
7298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 public final void startRunning(String pkg, String cls, String action,
7300 String data) {
7301 synchronized(this) {
7302 if (mStartRunning) {
7303 return;
7304 }
7305 mStartRunning = true;
7306 mTopComponent = pkg != null && cls != null
7307 ? new ComponentName(pkg, cls) : null;
7308 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7309 mTopData = data;
7310 if (!mSystemReady) {
7311 return;
7312 }
7313 }
7314
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007315 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 }
7317
7318 private void retrieveSettings() {
7319 final ContentResolver resolver = mContext.getContentResolver();
7320 String debugApp = Settings.System.getString(
7321 resolver, Settings.System.DEBUG_APP);
7322 boolean waitForDebugger = Settings.System.getInt(
7323 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7324 boolean alwaysFinishActivities = Settings.System.getInt(
7325 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7326
7327 Configuration configuration = new Configuration();
7328 Settings.System.getConfiguration(resolver, configuration);
7329
7330 synchronized (this) {
7331 mDebugApp = mOrigDebugApp = debugApp;
7332 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7333 mAlwaysFinishActivities = alwaysFinishActivities;
7334 // This happens before any activities are started, so we can
7335 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007336 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007337 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 }
7339 }
7340
7341 public boolean testIsSystemReady() {
7342 // no need to synchronize(this) just to read & return the value
7343 return mSystemReady;
7344 }
7345
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007346 private static File getCalledPreBootReceiversFile() {
7347 File dataDir = Environment.getDataDirectory();
7348 File systemDir = new File(dataDir, "system");
7349 File fname = new File(systemDir, "called_pre_boots.dat");
7350 return fname;
7351 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007352
7353 static final int LAST_DONE_VERSION = 10000;
7354
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007355 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7356 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7357 File file = getCalledPreBootReceiversFile();
7358 FileInputStream fis = null;
7359 try {
7360 fis = new FileInputStream(file);
7361 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007362 int fvers = dis.readInt();
7363 if (fvers == LAST_DONE_VERSION) {
7364 String vers = dis.readUTF();
7365 String codename = dis.readUTF();
7366 String build = dis.readUTF();
7367 if (android.os.Build.VERSION.RELEASE.equals(vers)
7368 && android.os.Build.VERSION.CODENAME.equals(codename)
7369 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7370 int num = dis.readInt();
7371 while (num > 0) {
7372 num--;
7373 String pkg = dis.readUTF();
7374 String cls = dis.readUTF();
7375 lastDoneReceivers.add(new ComponentName(pkg, cls));
7376 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007377 }
7378 }
7379 } catch (FileNotFoundException e) {
7380 } catch (IOException e) {
7381 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7382 } finally {
7383 if (fis != null) {
7384 try {
7385 fis.close();
7386 } catch (IOException e) {
7387 }
7388 }
7389 }
7390 return lastDoneReceivers;
7391 }
7392
7393 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7394 File file = getCalledPreBootReceiversFile();
7395 FileOutputStream fos = null;
7396 DataOutputStream dos = null;
7397 try {
7398 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7399 fos = new FileOutputStream(file);
7400 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007401 dos.writeInt(LAST_DONE_VERSION);
7402 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007403 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007404 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007405 dos.writeInt(list.size());
7406 for (int i=0; i<list.size(); i++) {
7407 dos.writeUTF(list.get(i).getPackageName());
7408 dos.writeUTF(list.get(i).getClassName());
7409 }
7410 } catch (IOException e) {
7411 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7412 file.delete();
7413 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007414 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007415 if (dos != null) {
7416 try {
7417 dos.close();
7418 } catch (IOException e) {
7419 // TODO Auto-generated catch block
7420 e.printStackTrace();
7421 }
7422 }
7423 }
7424 }
7425
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007426 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007427 synchronized(this) {
7428 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007429 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007430 return;
7431 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007432
7433 // Check to see if there are any update receivers to run.
7434 if (!mDidUpdate) {
7435 if (mWaitingUpdate) {
7436 return;
7437 }
7438 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7439 List<ResolveInfo> ris = null;
7440 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007441 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007442 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007443 } catch (RemoteException e) {
7444 }
7445 if (ris != null) {
7446 for (int i=ris.size()-1; i>=0; i--) {
7447 if ((ris.get(i).activityInfo.applicationInfo.flags
7448 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7449 ris.remove(i);
7450 }
7451 }
7452 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007453
7454 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7455
7456 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007457 for (int i=0; i<ris.size(); i++) {
7458 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007459 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7460 if (lastDoneReceivers.contains(comp)) {
7461 ris.remove(i);
7462 i--;
7463 }
7464 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007465
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007466 for (int i=0; i<ris.size(); i++) {
7467 ActivityInfo ai = ris.get(i).activityInfo;
7468 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7469 doneReceivers.add(comp);
7470 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007471 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007472 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007473 finisher = new IIntentReceiver.Stub() {
7474 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007475 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007476 boolean sticky) {
7477 // The raw IIntentReceiver interface is called
7478 // with the AM lock held, so redispatch to
7479 // execute our code without the lock.
7480 mHandler.post(new Runnable() {
7481 public void run() {
7482 synchronized (ActivityManagerService.this) {
7483 mDidUpdate = true;
7484 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007485 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007486 showBootMessage(mContext.getText(
7487 R.string.android_upgrading_complete),
7488 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007489 systemReady(goingCallback);
7490 }
7491 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007492 }
7493 };
7494 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007495 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007496 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007497 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007498 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007499 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007500 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007501 mWaitingUpdate = true;
7502 }
7503 }
7504 }
7505 if (mWaitingUpdate) {
7506 return;
7507 }
7508 mDidUpdate = true;
7509 }
7510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 mSystemReady = true;
7512 if (!mStartRunning) {
7513 return;
7514 }
7515 }
7516
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007517 ArrayList<ProcessRecord> procsToKill = null;
7518 synchronized(mPidsSelfLocked) {
7519 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7520 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7521 if (!isAllowedWhileBooting(proc.info)){
7522 if (procsToKill == null) {
7523 procsToKill = new ArrayList<ProcessRecord>();
7524 }
7525 procsToKill.add(proc);
7526 }
7527 }
7528 }
7529
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007530 synchronized(this) {
7531 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007532 for (int i=procsToKill.size()-1; i>=0; i--) {
7533 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007534 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007535 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007536 }
7537 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007538
7539 // Now that we have cleaned up any update processes, we
7540 // are ready to start launching real processes and know that
7541 // we won't trample on them any more.
7542 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007543 }
7544
Joe Onorato8a9b2202010-02-26 18:56:32 -08007545 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007546 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 SystemClock.uptimeMillis());
7548
7549 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007550 // Make sure we have no pre-ready processes sitting around.
7551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7553 ResolveInfo ri = mContext.getPackageManager()
7554 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007555 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 CharSequence errorMsg = null;
7557 if (ri != null) {
7558 ActivityInfo ai = ri.activityInfo;
7559 ApplicationInfo app = ai.applicationInfo;
7560 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7561 mTopAction = Intent.ACTION_FACTORY_TEST;
7562 mTopData = null;
7563 mTopComponent = new ComponentName(app.packageName,
7564 ai.name);
7565 } else {
7566 errorMsg = mContext.getResources().getText(
7567 com.android.internal.R.string.factorytest_not_system);
7568 }
7569 } else {
7570 errorMsg = mContext.getResources().getText(
7571 com.android.internal.R.string.factorytest_no_action);
7572 }
7573 if (errorMsg != null) {
7574 mTopAction = null;
7575 mTopData = null;
7576 mTopComponent = null;
7577 Message msg = Message.obtain();
7578 msg.what = SHOW_FACTORY_ERROR_MSG;
7579 msg.getData().putCharSequence("msg", errorMsg);
7580 mHandler.sendMessage(msg);
7581 }
7582 }
7583 }
7584
7585 retrieveSettings();
7586
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007587 if (goingCallback != null) goingCallback.run();
7588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 synchronized (this) {
7590 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7591 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007592 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007593 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 if (apps != null) {
7595 int N = apps.size();
7596 int i;
7597 for (i=0; i<N; i++) {
7598 ApplicationInfo info
7599 = (ApplicationInfo)apps.get(i);
7600 if (info != null &&
7601 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007602 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 }
7604 }
7605 }
7606 } catch (RemoteException ex) {
7607 // pm is in same process, this will never happen.
7608 }
7609 }
7610
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007611 // Start up initial activity.
7612 mBooting = true;
7613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007615 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 Message msg = Message.obtain();
7617 msg.what = SHOW_UID_ERROR_MSG;
7618 mHandler.sendMessage(msg);
7619 }
7620 } catch (RemoteException e) {
7621 }
7622
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007623 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 }
7625 }
7626
Dan Egnorb7f03672009-12-09 16:22:32 -08007627 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007628 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007630 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007631 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 startAppProblemLocked(app);
7633 app.stopFreezingAllLocked();
7634 return handleAppCrashLocked(app);
7635 }
7636
Dan Egnorb7f03672009-12-09 16:22:32 -08007637 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007638 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007639 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007640 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007641 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7642 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 startAppProblemLocked(app);
7644 app.stopFreezingAllLocked();
7645 }
7646
7647 /**
7648 * Generate a process error record, suitable for attachment to a ProcessRecord.
7649 *
7650 * @param app The ProcessRecord in which the error occurred.
7651 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7652 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007653 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 * @param shortMsg Short message describing the crash.
7655 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007656 * @param stackTrace Full crash stack trace, may be null.
7657 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 * @return Returns a fully-formed AppErrorStateInfo record.
7659 */
7660 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007661 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 report.condition = condition;
7665 report.processName = app.processName;
7666 report.pid = app.pid;
7667 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007668 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 report.shortMsg = shortMsg;
7670 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007671 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672
7673 return report;
7674 }
7675
Dan Egnor42471dd2010-01-07 17:25:22 -08007676 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 synchronized (this) {
7678 app.crashing = false;
7679 app.crashingReport = null;
7680 app.notResponding = false;
7681 app.notRespondingReport = null;
7682 if (app.anrDialog == fromDialog) {
7683 app.anrDialog = null;
7684 }
7685 if (app.waitDialog == fromDialog) {
7686 app.waitDialog = null;
7687 }
7688 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007689 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007690 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007691 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7692 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007693 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007695 }
7696 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007697
Dan Egnorb7f03672009-12-09 16:22:32 -08007698 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007699 if (mHeadless) {
7700 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7701 return false;
7702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 long now = SystemClock.uptimeMillis();
7704
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007705 Long crashTime;
7706 if (!app.isolated) {
7707 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7708 } else {
7709 crashTime = null;
7710 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007711 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007713 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007715 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007716 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007717 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7718 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007720 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007722 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 }
7724 }
7725 if (!app.persistent) {
7726 // We don't want to start this process again until the user
7727 // explicitly does so... but for persistent process, we really
7728 // need to keep it running. If a persistent process is actually
7729 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007730 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007732 if (!app.isolated) {
7733 // XXX We don't have a way to mark isolated processes
7734 // as bad, since they don't have a peristent identity.
7735 mBadProcesses.put(app.info.processName, app.uid, now);
7736 mProcessCrashTimes.remove(app.info.processName, app.uid);
7737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007740 // Don't let services in this process be restarted and potentially
7741 // annoy the user repeatedly. Unless it is persistent, since those
7742 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007743 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007744 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 return false;
7746 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007747 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007748 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007749 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007750 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007751 // If the top running activity is from this crashing
7752 // process, then terminate it to avoid getting in a loop.
7753 Slog.w(TAG, " Force finishing activity "
7754 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007755 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007756 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007757 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007758 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007759 // stopped, to avoid a situation where one will get
7760 // re-start our crashing activity once it gets resumed again.
7761 index--;
7762 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007763 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007764 if (r.state == ActivityState.RESUMED
7765 || r.state == ActivityState.PAUSING
7766 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007767 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007768 Slog.w(TAG, " Force finishing activity "
7769 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007770 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007771 Activity.RESULT_CANCELED, null, "crashed");
7772 }
7773 }
7774 }
7775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 }
7777
7778 // Bump up the crash count of any services currently running in the proc.
7779 if (app.services.size() != 0) {
7780 // Any services running in the application need to be placed
7781 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007782 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007784 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 sr.crashCount++;
7786 }
7787 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007788
7789 // If the crashing process is what we consider to be the "home process" and it has been
7790 // replaced by a third-party app, clear the package preferred activities from packages
7791 // with a home activity running in the process to prevent a repeatedly crashing app
7792 // from blocking the user to manually clear the list.
7793 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7794 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7795 Iterator it = mHomeProcess.activities.iterator();
7796 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007797 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007798 if (r.isHomeActivity) {
7799 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7800 try {
7801 ActivityThread.getPackageManager()
7802 .clearPackagePreferredActivities(r.packageName);
7803 } catch (RemoteException c) {
7804 // pm is in same process, this will never happen.
7805 }
7806 }
7807 }
7808 }
7809
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007810 if (!app.isolated) {
7811 // XXX Can't keep track of crash times for isolated processes,
7812 // because they don't have a perisistent identity.
7813 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7814 }
7815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 return true;
7817 }
7818
7819 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007820 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7821 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 skipCurrentReceiverLocked(app);
7823 }
7824
7825 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007826 for (BroadcastQueue queue : mBroadcastQueues) {
7827 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 }
7829 }
7830
Dan Egnor60d87622009-12-16 16:32:58 -08007831 /**
7832 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7833 * The application process will exit immediately after this call returns.
7834 * @param app object of the crashing app, null for the system server
7835 * @param crashInfo describing the exception
7836 */
7837 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007838 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007839 final String processName = app == null ? "system_server"
7840 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007841
7842 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007843 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007844 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007845 crashInfo.exceptionClassName,
7846 crashInfo.exceptionMessage,
7847 crashInfo.throwFileName,
7848 crashInfo.throwLineNumber);
7849
Jeff Sharkeya353d262011-10-28 11:12:06 -07007850 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007851
7852 crashApplication(r, crashInfo);
7853 }
7854
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007855 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007856 IBinder app,
7857 int violationMask,
7858 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007859 ProcessRecord r = findAppProcess(app, "StrictMode");
7860 if (r == null) {
7861 return;
7862 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007863
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007864 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007865 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007866 boolean logIt = true;
7867 synchronized (mAlreadyLoggedViolatedStacks) {
7868 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7869 logIt = false;
7870 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007871 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007872 // the relative pain numbers, without logging all
7873 // the stack traces repeatedly. We'd want to do
7874 // likewise in the client code, which also does
7875 // dup suppression, before the Binder call.
7876 } else {
7877 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7878 mAlreadyLoggedViolatedStacks.clear();
7879 }
7880 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7881 }
7882 }
7883 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007884 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007885 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007886 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007887
7888 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7889 AppErrorResult result = new AppErrorResult();
7890 synchronized (this) {
7891 final long origId = Binder.clearCallingIdentity();
7892
7893 Message msg = Message.obtain();
7894 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7895 HashMap<String, Object> data = new HashMap<String, Object>();
7896 data.put("result", result);
7897 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007898 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007899 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007900 msg.obj = data;
7901 mHandler.sendMessage(msg);
7902
7903 Binder.restoreCallingIdentity(origId);
7904 }
7905 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007906 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007907 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007908 }
7909
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007910 // Depending on the policy in effect, there could be a bunch of
7911 // these in quick succession so we try to batch these together to
7912 // minimize disk writes, number of dropbox entries, and maximize
7913 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007914 private void logStrictModeViolationToDropBox(
7915 ProcessRecord process,
7916 StrictMode.ViolationInfo info) {
7917 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007918 return;
7919 }
7920 final boolean isSystemApp = process == null ||
7921 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7922 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007923 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007924 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7925 final DropBoxManager dbox = (DropBoxManager)
7926 mContext.getSystemService(Context.DROPBOX_SERVICE);
7927
7928 // Exit early if the dropbox isn't configured to accept this report type.
7929 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7930
7931 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007932 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007933 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7934 synchronized (sb) {
7935 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007936 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007937 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7938 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007939 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7940 if (info.violationNumThisLoop != 0) {
7941 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7942 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007943 if (info.numAnimationsRunning != 0) {
7944 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7945 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007946 if (info.broadcastIntentAction != null) {
7947 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7948 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007949 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007950 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007951 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007952 if (info.numInstances != -1) {
7953 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7954 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007955 if (info.tags != null) {
7956 for (String tag : info.tags) {
7957 sb.append("Span-Tag: ").append(tag).append("\n");
7958 }
7959 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007960 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007961 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7962 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007963 }
7964 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007965
7966 // Only buffer up to ~64k. Various logging bits truncate
7967 // things at 128k.
7968 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007969 }
7970
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007971 // Flush immediately if the buffer's grown too large, or this
7972 // is a non-system app. Non-system apps are isolated with a
7973 // different tag & policy and not batched.
7974 //
7975 // Batching is useful during internal testing with
7976 // StrictMode settings turned up high. Without batching,
7977 // thousands of separate files could be created on boot.
7978 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007979 new Thread("Error dump: " + dropboxTag) {
7980 @Override
7981 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007982 String report;
7983 synchronized (sb) {
7984 report = sb.toString();
7985 sb.delete(0, sb.length());
7986 sb.trimToSize();
7987 }
7988 if (report.length() != 0) {
7989 dbox.addText(dropboxTag, report);
7990 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007991 }
7992 }.start();
7993 return;
7994 }
7995
7996 // System app batching:
7997 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007998 // An existing dropbox-writing thread is outstanding, so
7999 // we don't need to start it up. The existing thread will
8000 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008001 return;
8002 }
8003
8004 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8005 // (After this point, we shouldn't access AMS internal data structures.)
8006 new Thread("Error dump: " + dropboxTag) {
8007 @Override
8008 public void run() {
8009 // 5 second sleep to let stacks arrive and be batched together
8010 try {
8011 Thread.sleep(5000); // 5 seconds
8012 } catch (InterruptedException e) {}
8013
8014 String errorReport;
8015 synchronized (mStrictModeBuffer) {
8016 errorReport = mStrictModeBuffer.toString();
8017 if (errorReport.length() == 0) {
8018 return;
8019 }
8020 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8021 mStrictModeBuffer.trimToSize();
8022 }
8023 dbox.addText(dropboxTag, errorReport);
8024 }
8025 }.start();
8026 }
8027
Dan Egnor60d87622009-12-16 16:32:58 -08008028 /**
8029 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8030 * @param app object of the crashing app, null for the system server
8031 * @param tag reported by the caller
8032 * @param crashInfo describing the context of the error
8033 * @return true if the process should exit immediately (WTF is fatal)
8034 */
8035 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008036 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008037 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008038 final String processName = app == null ? "system_server"
8039 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008040
8041 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008042 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008043 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008044 tag, crashInfo.exceptionMessage);
8045
Jeff Sharkeya353d262011-10-28 11:12:06 -07008046 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008047
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008048 if (r != null && r.pid != Process.myPid() &&
8049 Settings.Secure.getInt(mContext.getContentResolver(),
8050 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008051 crashApplication(r, crashInfo);
8052 return true;
8053 } else {
8054 return false;
8055 }
8056 }
8057
8058 /**
8059 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8060 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8061 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008062 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008063 if (app == null) {
8064 return null;
8065 }
8066
8067 synchronized (this) {
8068 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8069 final int NA = apps.size();
8070 for (int ia=0; ia<NA; ia++) {
8071 ProcessRecord p = apps.valueAt(ia);
8072 if (p.thread != null && p.thread.asBinder() == app) {
8073 return p;
8074 }
8075 }
8076 }
8077
Dianne Hackborncb44d962011-03-10 17:02:27 -08008078 Slog.w(TAG, "Can't find mystery application for " + reason
8079 + " from pid=" + Binder.getCallingPid()
8080 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008081 return null;
8082 }
8083 }
8084
8085 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008086 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8087 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008088 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008089 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8090 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008091 // Watchdog thread ends up invoking this function (with
8092 // a null ProcessRecord) to add the stack file to dropbox.
8093 // Do not acquire a lock on this (am) in such cases, as it
8094 // could cause a potential deadlock, if and when watchdog
8095 // is invoked due to unavailability of lock on am and it
8096 // would prevent watchdog from killing system_server.
8097 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008098 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008099 return;
8100 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008101 // Note: ProcessRecord 'process' is guarded by the service
8102 // instance. (notably process.pkgList, which could otherwise change
8103 // concurrently during execution of this method)
8104 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008105 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008106 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008107 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008108 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8109 for (String pkg : process.pkgList) {
8110 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008111 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008112 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008113 if (pi != null) {
8114 sb.append(" v").append(pi.versionCode);
8115 if (pi.versionName != null) {
8116 sb.append(" (").append(pi.versionName).append(")");
8117 }
8118 }
8119 } catch (RemoteException e) {
8120 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008121 }
Dan Egnora455d192010-03-12 08:52:28 -08008122 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008123 }
Dan Egnora455d192010-03-12 08:52:28 -08008124 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008125 }
8126
8127 private static String processClass(ProcessRecord process) {
8128 if (process == null || process.pid == MY_PID) {
8129 return "system_server";
8130 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8131 return "system_app";
8132 } else {
8133 return "data_app";
8134 }
8135 }
8136
8137 /**
8138 * Write a description of an error (crash, WTF, ANR) to the drop box.
8139 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8140 * @param process which caused the error, null means the system server
8141 * @param activity which triggered the error, null if unknown
8142 * @param parent activity related to the error, null if unknown
8143 * @param subject line related to the error, null if absent
8144 * @param report in long form describing the error, null if absent
8145 * @param logFile to include in the report, null if none
8146 * @param crashInfo giving an application stack trace, null if absent
8147 */
8148 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008149 ProcessRecord process, String processName, ActivityRecord activity,
8150 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008151 final String report, final File logFile,
8152 final ApplicationErrorReport.CrashInfo crashInfo) {
8153 // NOTE -- this must never acquire the ActivityManagerService lock,
8154 // otherwise the watchdog may be prevented from resetting the system.
8155
8156 final String dropboxTag = processClass(process) + "_" + eventType;
8157 final DropBoxManager dbox = (DropBoxManager)
8158 mContext.getSystemService(Context.DROPBOX_SERVICE);
8159
8160 // Exit early if the dropbox isn't configured to accept this report type.
8161 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8162
8163 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008164 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008165 if (activity != null) {
8166 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8167 }
8168 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8169 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8170 }
8171 if (parent != null && parent != activity) {
8172 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8173 }
8174 if (subject != null) {
8175 sb.append("Subject: ").append(subject).append("\n");
8176 }
8177 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008178 if (Debug.isDebuggerConnected()) {
8179 sb.append("Debugger: Connected\n");
8180 }
Dan Egnora455d192010-03-12 08:52:28 -08008181 sb.append("\n");
8182
8183 // Do the rest in a worker thread to avoid blocking the caller on I/O
8184 // (After this point, we shouldn't access AMS internal data structures.)
8185 Thread worker = new Thread("Error dump: " + dropboxTag) {
8186 @Override
8187 public void run() {
8188 if (report != null) {
8189 sb.append(report);
8190 }
8191 if (logFile != null) {
8192 try {
8193 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8194 } catch (IOException e) {
8195 Slog.e(TAG, "Error reading " + logFile, e);
8196 }
8197 }
8198 if (crashInfo != null && crashInfo.stackTrace != null) {
8199 sb.append(crashInfo.stackTrace);
8200 }
8201
8202 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8203 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8204 if (lines > 0) {
8205 sb.append("\n");
8206
8207 // Merge several logcat streams, and take the last N lines
8208 InputStreamReader input = null;
8209 try {
8210 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8211 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8212 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8213
8214 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8215 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8216 input = new InputStreamReader(logcat.getInputStream());
8217
8218 int num;
8219 char[] buf = new char[8192];
8220 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8221 } catch (IOException e) {
8222 Slog.e(TAG, "Error running logcat", e);
8223 } finally {
8224 if (input != null) try { input.close(); } catch (IOException e) {}
8225 }
8226 }
8227
8228 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008229 }
Dan Egnora455d192010-03-12 08:52:28 -08008230 };
8231
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008232 if (process == null) {
8233 // If process is null, we are being called from some internal code
8234 // and may be about to die -- run this synchronously.
8235 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008236 } else {
8237 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008238 }
8239 }
8240
8241 /**
8242 * Bring up the "unexpected error" dialog box for a crashing app.
8243 * Deal with edge cases (intercepts from instrumented applications,
8244 * ActivityController, error intent receivers, that sort of thing).
8245 * @param r the application crashing
8246 * @param crashInfo describing the failure
8247 */
8248 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008249 long timeMillis = System.currentTimeMillis();
8250 String shortMsg = crashInfo.exceptionClassName;
8251 String longMsg = crashInfo.exceptionMessage;
8252 String stackTrace = crashInfo.stackTrace;
8253 if (shortMsg != null && longMsg != null) {
8254 longMsg = shortMsg + ": " + longMsg;
8255 } else if (shortMsg != null) {
8256 longMsg = shortMsg;
8257 }
8258
Dan Egnor60d87622009-12-16 16:32:58 -08008259 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008261 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008262 try {
8263 String name = r != null ? r.processName : null;
8264 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008265 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008266 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008267 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 + " at watcher's request");
8269 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008270 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 }
8272 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008273 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 }
8275 }
8276
8277 final long origId = Binder.clearCallingIdentity();
8278
8279 // If this process is running instrumentation, finish it.
8280 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008281 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008283 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8284 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008285 Bundle info = new Bundle();
8286 info.putString("shortMsg", shortMsg);
8287 info.putString("longMsg", longMsg);
8288 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8289 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008290 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 }
8292
Dan Egnor60d87622009-12-16 16:32:58 -08008293 // If we can't identify the process or it's already exceeded its crash quota,
8294 // quit right away without showing a crash dialog.
8295 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008297 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 }
8299
8300 Message msg = Message.obtain();
8301 msg.what = SHOW_ERROR_MSG;
8302 HashMap data = new HashMap();
8303 data.put("result", result);
8304 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 msg.obj = data;
8306 mHandler.sendMessage(msg);
8307
8308 Binder.restoreCallingIdentity(origId);
8309 }
8310
8311 int res = result.get();
8312
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008313 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008315 if (r != null && !r.isolated) {
8316 // XXX Can't keep track of crash time for isolated processes,
8317 // since they don't have a persistent identity.
8318 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008319 SystemClock.uptimeMillis());
8320 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008321 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008322 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008323 }
8324 }
8325
8326 if (appErrorIntent != null) {
8327 try {
8328 mContext.startActivity(appErrorIntent);
8329 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008330 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008334
8335 Intent createAppErrorIntentLocked(ProcessRecord r,
8336 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8337 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008338 if (report == null) {
8339 return null;
8340 }
8341 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8342 result.setComponent(r.errorReportReceiver);
8343 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8344 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8345 return result;
8346 }
8347
Dan Egnorb7f03672009-12-09 16:22:32 -08008348 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8349 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008350 if (r.errorReportReceiver == null) {
8351 return null;
8352 }
8353
8354 if (!r.crashing && !r.notResponding) {
8355 return null;
8356 }
8357
Dan Egnorb7f03672009-12-09 16:22:32 -08008358 ApplicationErrorReport report = new ApplicationErrorReport();
8359 report.packageName = r.info.packageName;
8360 report.installerPackageName = r.errorReportReceiver.getPackageName();
8361 report.processName = r.processName;
8362 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008363 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008364
Dan Egnorb7f03672009-12-09 16:22:32 -08008365 if (r.crashing) {
8366 report.type = ApplicationErrorReport.TYPE_CRASH;
8367 report.crashInfo = crashInfo;
8368 } else if (r.notResponding) {
8369 report.type = ApplicationErrorReport.TYPE_ANR;
8370 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008371
Dan Egnorb7f03672009-12-09 16:22:32 -08008372 report.anrInfo.activity = r.notRespondingReport.tag;
8373 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8374 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008375 }
8376
Dan Egnorb7f03672009-12-09 16:22:32 -08008377 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008378 }
8379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008380 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008381 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 // assume our apps are happy - lazy create the list
8383 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8384
8385 synchronized (this) {
8386
8387 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008388 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8389 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8391 // This one's in trouble, so we'll generate a report for it
8392 // crashes are higher priority (in case there's a crash *and* an anr)
8393 ActivityManager.ProcessErrorStateInfo report = null;
8394 if (app.crashing) {
8395 report = app.crashingReport;
8396 } else if (app.notResponding) {
8397 report = app.notRespondingReport;
8398 }
8399
8400 if (report != null) {
8401 if (errList == null) {
8402 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8403 }
8404 errList.add(report);
8405 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008406 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 " crashing = " + app.crashing +
8408 " notResponding = " + app.notResponding);
8409 }
8410 }
8411 }
8412 }
8413
8414 return errList;
8415 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008416
8417 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008418 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008419 if (currApp != null) {
8420 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8421 }
8422 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008423 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8424 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008425 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8426 if (currApp != null) {
8427 currApp.lru = 0;
8428 }
8429 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008430 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008431 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8432 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8433 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8434 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8435 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8436 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8437 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8438 } else {
8439 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8440 }
8441 }
8442
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008443 private void fillInProcMemInfo(ProcessRecord app,
8444 ActivityManager.RunningAppProcessInfo outInfo) {
8445 outInfo.pid = app.pid;
8446 outInfo.uid = app.info.uid;
8447 if (mHeavyWeightProcess == app) {
8448 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8449 }
8450 if (app.persistent) {
8451 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8452 }
8453 outInfo.lastTrimLevel = app.trimMemoryLevel;
8454 int adj = app.curAdj;
8455 outInfo.importance = oomAdjToImportance(adj, outInfo);
8456 outInfo.importanceReasonCode = app.adjTypeCode;
8457 }
8458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008460 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008461 // Lazy instantiation of list
8462 List<ActivityManager.RunningAppProcessInfo> runList = null;
8463 synchronized (this) {
8464 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008465 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8466 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008467 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8468 // Generate process state info for running application
8469 ActivityManager.RunningAppProcessInfo currApp =
8470 new ActivityManager.RunningAppProcessInfo(app.processName,
8471 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008472 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008473 if (app.adjSource instanceof ProcessRecord) {
8474 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008475 currApp.importanceReasonImportance = oomAdjToImportance(
8476 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008477 } else if (app.adjSource instanceof ActivityRecord) {
8478 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008479 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8480 }
8481 if (app.adjTarget instanceof ComponentName) {
8482 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8483 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008484 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 // + " lru=" + currApp.lru);
8486 if (runList == null) {
8487 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8488 }
8489 runList.add(currApp);
8490 }
8491 }
8492 }
8493 return runList;
8494 }
8495
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008496 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008497 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008498 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8499 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8500 if (runningApps != null && runningApps.size() > 0) {
8501 Set<String> extList = new HashSet<String>();
8502 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8503 if (app.pkgList != null) {
8504 for (String pkg : app.pkgList) {
8505 extList.add(pkg);
8506 }
8507 }
8508 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008509 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008510 for (String pkg : extList) {
8511 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008512 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008513 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8514 retList.add(info);
8515 }
8516 } catch (RemoteException e) {
8517 }
8518 }
8519 }
8520 return retList;
8521 }
8522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008524 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8525 enforceNotIsolatedCaller("getMyMemoryState");
8526 synchronized (this) {
8527 ProcessRecord proc;
8528 synchronized (mPidsSelfLocked) {
8529 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8530 }
8531 fillInProcMemInfo(proc, outInfo);
8532 }
8533 }
8534
8535 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 if (checkCallingPermission(android.Manifest.permission.DUMP)
8538 != PackageManager.PERMISSION_GRANTED) {
8539 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8540 + Binder.getCallingPid()
8541 + ", uid=" + Binder.getCallingUid()
8542 + " without permission "
8543 + android.Manifest.permission.DUMP);
8544 return;
8545 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008546
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008547 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008548 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008549 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008550
8551 int opti = 0;
8552 while (opti < args.length) {
8553 String opt = args[opti];
8554 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8555 break;
8556 }
8557 opti++;
8558 if ("-a".equals(opt)) {
8559 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008560 } else if ("-c".equals(opt)) {
8561 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 } else if ("-h".equals(opt)) {
8563 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008564 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008565 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008566 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008567 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8568 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8569 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008570 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008571 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008572 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008573 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008574 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008575 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008576 pw.println(" all: dump all activities");
8577 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008578 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008579 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8580 pw.println(" a partial substring in a component name, a");
8581 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008582 pw.println(" -a: include all available server state.");
8583 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008584 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 } else {
8586 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008589
8590 long origId = Binder.clearCallingIdentity();
8591 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008592 // Is the caller requesting to dump a particular piece of data?
8593 if (opti < args.length) {
8594 String cmd = args[opti];
8595 opti++;
8596 if ("activities".equals(cmd) || "a".equals(cmd)) {
8597 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008598 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008600 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008601 String[] newArgs;
8602 String name;
8603 if (opti >= args.length) {
8604 name = null;
8605 newArgs = EMPTY_STRING_ARRAY;
8606 } else {
8607 name = args[opti];
8608 opti++;
8609 newArgs = new String[args.length - opti];
8610 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8611 args.length - opti);
8612 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008613 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008614 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008615 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008616 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008617 String[] newArgs;
8618 String name;
8619 if (opti >= args.length) {
8620 name = null;
8621 newArgs = EMPTY_STRING_ARRAY;
8622 } else {
8623 name = args[opti];
8624 opti++;
8625 newArgs = new String[args.length - opti];
8626 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8627 args.length - opti);
8628 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008629 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008630 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008631 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008632 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008633 String[] newArgs;
8634 String name;
8635 if (opti >= args.length) {
8636 name = null;
8637 newArgs = EMPTY_STRING_ARRAY;
8638 } else {
8639 name = args[opti];
8640 opti++;
8641 newArgs = new String[args.length - opti];
8642 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8643 args.length - opti);
8644 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008646 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008648 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8649 synchronized (this) {
8650 dumpOomLocked(fd, pw, args, opti, true);
8651 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008652 } else if ("provider".equals(cmd)) {
8653 String[] newArgs;
8654 String name;
8655 if (opti >= args.length) {
8656 name = null;
8657 newArgs = EMPTY_STRING_ARRAY;
8658 } else {
8659 name = args[opti];
8660 opti++;
8661 newArgs = new String[args.length - opti];
8662 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8663 }
8664 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8665 pw.println("No providers match: " + name);
8666 pw.println("Use -h for help.");
8667 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8669 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008670 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008671 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008672 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008673 String[] newArgs;
8674 String name;
8675 if (opti >= args.length) {
8676 name = null;
8677 newArgs = EMPTY_STRING_ARRAY;
8678 } else {
8679 name = args[opti];
8680 opti++;
8681 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008682 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8683 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008684 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008685 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008686 pw.println("No services match: " + name);
8687 pw.println("Use -h for help.");
8688 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008689 } else if ("package".equals(cmd)) {
8690 String[] newArgs;
8691 if (opti >= args.length) {
8692 pw.println("package: no package name specified");
8693 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008694 } else {
8695 dumpPackage = args[opti];
8696 opti++;
8697 newArgs = new String[args.length - opti];
8698 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8699 args.length - opti);
8700 args = newArgs;
8701 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008702 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008703 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008704 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8705 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008706 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008708 } else {
8709 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008710 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8711 pw.println("Bad activity command, or no activities match: " + cmd);
8712 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008713 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008714 }
8715 if (!more) {
8716 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008717 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008720
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008721 // No piece of data specified, dump everything.
8722 synchronized (this) {
8723 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008724 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008725 if (needSep) {
8726 pw.println(" ");
8727 }
8728 if (dumpAll) {
8729 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008731 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008732 if (needSep) {
8733 pw.println(" ");
8734 }
8735 if (dumpAll) {
8736 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008738 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 if (needSep) {
8740 pw.println(" ");
8741 }
8742 if (dumpAll) {
8743 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008744 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008745 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008746 if (needSep) {
8747 pw.println(" ");
8748 }
8749 if (dumpAll) {
8750 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753 if (needSep) {
8754 pw.println(" ");
8755 }
8756 if (dumpAll) {
8757 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008758 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008759 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008760 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008761 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008763
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008764 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008765 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008766 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8767 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008768 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8769 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008770 pw.println(" ");
8771 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008772 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8773 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008774 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008776 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008778 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008780 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008782 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008783 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008785 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008786 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8787 pw.println(" ");
8788 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008789 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008790 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008791 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008792 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008793 pw.println(" ");
8794 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008795 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008796 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008799 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008800 if (mMainStack.mPausingActivity != null) {
8801 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008802 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008803 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008804 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008805 if (dumpAll) {
8806 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8807 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008808 pw.println(" mDismissKeyguardOnNextActivity: "
8809 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008812 if (mRecentTasks.size() > 0) {
8813 pw.println();
8814 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008815
8816 final int N = mRecentTasks.size();
8817 for (int i=0; i<N; i++) {
8818 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008819 if (dumpPackage != null) {
8820 if (tr.realActivity == null ||
8821 !dumpPackage.equals(tr.realActivity)) {
8822 continue;
8823 }
8824 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8826 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008827 if (dumpAll) {
8828 mRecentTasks.get(i).dump(pw, " ");
8829 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 }
8831 }
8832
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008833 if (dumpAll) {
8834 pw.println(" ");
8835 pw.println(" mCurTask: " + mCurTask);
8836 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008837
8838 return true;
8839 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008840
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008842 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008843 boolean needSep = false;
8844 int numPers = 0;
8845
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008846 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8847
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8850 final int NA = procs.size();
8851 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008852 ProcessRecord r = procs.valueAt(ia);
8853 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8854 continue;
8855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 if (!needSep) {
8857 pw.println(" All known processes:");
8858 needSep = true;
8859 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008860 pw.print(r.persistent ? " *PERS*" : " *APP*");
8861 pw.print(" UID "); pw.print(procs.keyAt(ia));
8862 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 r.dump(pw, " ");
8864 if (r.persistent) {
8865 numPers++;
8866 }
8867 }
8868 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008869 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008870
8871 if (mIsolatedProcesses.size() > 0) {
8872 if (needSep) pw.println(" ");
8873 needSep = true;
8874 pw.println(" Isolated process list (sorted by uid):");
8875 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8876 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8877 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8878 continue;
8879 }
8880 pw.println(String.format("%sIsolated #%2d: %s",
8881 " ", i, r.toString()));
8882 }
8883 }
8884
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008885 if (mLruProcesses.size() > 0) {
8886 if (needSep) pw.println(" ");
8887 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008888 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008889 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008890 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 needSep = true;
8892 }
8893
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008894 if (dumpAll) {
8895 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 boolean printed = false;
8897 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8898 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8899 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8900 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008901 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008902 if (!printed) {
8903 if (needSep) pw.println(" ");
8904 needSep = true;
8905 pw.println(" PID mappings:");
8906 printed = true;
8907 }
8908 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8909 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 }
8911 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008912 }
8913
8914 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008915 synchronized (mPidsSelfLocked) {
8916 boolean printed = false;
8917 for (int i=0; i<mForegroundProcesses.size(); i++) {
8918 ProcessRecord r = mPidsSelfLocked.get(
8919 mForegroundProcesses.valueAt(i).pid);
8920 if (dumpPackage != null && (r == null
8921 || !dumpPackage.equals(r.info.packageName))) {
8922 continue;
8923 }
8924 if (!printed) {
8925 if (needSep) pw.println(" ");
8926 needSep = true;
8927 pw.println(" Foreground Processes:");
8928 printed = true;
8929 }
8930 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8931 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008934 }
8935
8936 if (mPersistentStartingProcesses.size() > 0) {
8937 if (needSep) pw.println(" ");
8938 needSep = true;
8939 pw.println(" Persisent processes that are starting:");
8940 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008941 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008944 if (mRemovedProcesses.size() > 0) {
8945 if (needSep) pw.println(" ");
8946 needSep = true;
8947 pw.println(" Processes that are being removed:");
8948 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008950 }
8951
8952 if (mProcessesOnHold.size() > 0) {
8953 if (needSep) pw.println(" ");
8954 needSep = true;
8955 pw.println(" Processes that are on old until the system is ready:");
8956 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008957 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008960 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961
8962 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008963 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008964 long now = SystemClock.uptimeMillis();
8965 for (Map.Entry<String, SparseArray<Long>> procs
8966 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008967 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008968 SparseArray<Long> uids = procs.getValue();
8969 final int N = uids.size();
8970 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008971 int puid = uids.keyAt(i);
8972 ProcessRecord r = mProcessNames.get(pname, puid);
8973 if (dumpPackage != null && (r == null
8974 || !dumpPackage.equals(r.info.packageName))) {
8975 continue;
8976 }
8977 if (!printed) {
8978 if (needSep) pw.println(" ");
8979 needSep = true;
8980 pw.println(" Time since processes crashed:");
8981 printed = true;
8982 }
8983 pw.print(" Process "); pw.print(pname);
8984 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008986 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8987 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008988 }
8989 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008991
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 for (Map.Entry<String, SparseArray<Long>> procs
8995 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008996 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 SparseArray<Long> uids = procs.getValue();
8998 final int N = uids.size();
8999 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009000 int puid = uids.keyAt(i);
9001 ProcessRecord r = mProcessNames.get(pname, puid);
9002 if (dumpPackage != null && (r == null
9003 || !dumpPackage.equals(r.info.packageName))) {
9004 continue;
9005 }
9006 if (!printed) {
9007 if (needSep) pw.println(" ");
9008 needSep = true;
9009 pw.println(" Bad processes:");
9010 }
9011 pw.print(" Bad process "); pw.print(pname);
9012 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 pw.print(": crashed at time ");
9014 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 }
9016 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009018
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009019 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009021 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009022 if (dumpAll) {
9023 StringBuilder sb = new StringBuilder(128);
9024 sb.append(" mPreviousProcessVisibleTime: ");
9025 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9026 pw.println(sb);
9027 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009028 if (mHeavyWeightProcess != null) {
9029 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9030 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009032 if (dumpAll) {
9033 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009034 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009036 for (Map.Entry<String, Integer> entry
9037 : mCompatModePackages.getPackages().entrySet()) {
9038 String pkg = entry.getKey();
9039 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009040 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9041 continue;
9042 }
9043 if (!printed) {
9044 pw.println(" mScreenCompatPackages:");
9045 printed = true;
9046 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009047 pw.print(" "); pw.print(pkg); pw.print(": ");
9048 pw.print(mode); pw.println();
9049 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009050 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009051 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009052 if (mSleeping || mWentToSleep || mLockScreenShown) {
9053 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9054 + " mLockScreenShown " + mLockScreenShown);
9055 }
9056 if (mShuttingDown) {
9057 pw.println(" mShuttingDown=" + mShuttingDown);
9058 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9060 || mOrigWaitForDebugger) {
9061 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9062 + " mDebugTransient=" + mDebugTransient
9063 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9064 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009065 if (mOpenGlTraceApp != null) {
9066 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9067 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009068 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9069 || mProfileFd != null) {
9070 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9071 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9072 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9073 + mAutoStopProfiler);
9074 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009075 if (mAlwaysFinishActivities || mController != null) {
9076 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9077 + " mController=" + mController);
9078 }
9079 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009080 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009082 + " mProcessesReady=" + mProcessesReady
9083 + " mSystemReady=" + mSystemReady);
9084 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 + " mBooted=" + mBooted
9086 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009087 pw.print(" mLastPowerCheckRealtime=");
9088 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9089 pw.println("");
9090 pw.print(" mLastPowerCheckUptime=");
9091 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9092 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009093 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9094 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009095 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009096 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9097 + " mNumHiddenProcs=" + mNumHiddenProcs
9098 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009099 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101
9102 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 }
9104
Dianne Hackborn287952c2010-09-22 22:34:31 -07009105 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009106 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009107 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009108 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009109 long now = SystemClock.uptimeMillis();
9110 for (int i=0; i<mProcessesToGc.size(); i++) {
9111 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009112 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9113 continue;
9114 }
9115 if (!printed) {
9116 if (needSep) pw.println(" ");
9117 needSep = true;
9118 pw.println(" Processes that are waiting to GC:");
9119 printed = true;
9120 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009121 pw.print(" Process "); pw.println(proc);
9122 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9123 pw.print(", last gced=");
9124 pw.print(now-proc.lastRequestedGc);
9125 pw.print(" ms ago, last lowMem=");
9126 pw.print(now-proc.lastLowMemory);
9127 pw.println(" ms ago");
9128
9129 }
9130 }
9131 return needSep;
9132 }
9133
9134 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9135 int opti, boolean dumpAll) {
9136 boolean needSep = false;
9137
9138 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009139 if (needSep) pw.println(" ");
9140 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009141 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009142 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009143 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009144 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9145 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9146 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9147 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9148 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009149 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009150 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009151 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009152 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009153 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009154 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009155
9156 if (needSep) pw.println(" ");
9157 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009158 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009159 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009160 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009161 needSep = true;
9162 }
9163
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009164 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009165
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009166 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009167 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009168 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009169 if (mHeavyWeightProcess != null) {
9170 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9171 }
9172
9173 return true;
9174 }
9175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009176 /**
9177 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009178 * - no provider specified: dump all the providers
9179 * - a flattened component name that matched an existing provider was specified as the
9180 * first arg: dump that one provider
9181 * - the first arg isn't the flattened component name of an existing provider:
9182 * dump all providers whose component contains the first arg as a substring
9183 */
9184 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9185 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009186 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009187 }
9188
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009189 static class ItemMatcher {
9190 ArrayList<ComponentName> components;
9191 ArrayList<String> strings;
9192 ArrayList<Integer> objects;
9193 boolean all;
9194
9195 ItemMatcher() {
9196 all = true;
9197 }
9198
9199 void build(String name) {
9200 ComponentName componentName = ComponentName.unflattenFromString(name);
9201 if (componentName != null) {
9202 if (components == null) {
9203 components = new ArrayList<ComponentName>();
9204 }
9205 components.add(componentName);
9206 all = false;
9207 } else {
9208 int objectId = 0;
9209 // Not a '/' separated full component name; maybe an object ID?
9210 try {
9211 objectId = Integer.parseInt(name, 16);
9212 if (objects == null) {
9213 objects = new ArrayList<Integer>();
9214 }
9215 objects.add(objectId);
9216 all = false;
9217 } catch (RuntimeException e) {
9218 // Not an integer; just do string match.
9219 if (strings == null) {
9220 strings = new ArrayList<String>();
9221 }
9222 strings.add(name);
9223 all = false;
9224 }
9225 }
9226 }
9227
9228 int build(String[] args, int opti) {
9229 for (; opti<args.length; opti++) {
9230 String name = args[opti];
9231 if ("--".equals(name)) {
9232 return opti+1;
9233 }
9234 build(name);
9235 }
9236 return opti;
9237 }
9238
9239 boolean match(Object object, ComponentName comp) {
9240 if (all) {
9241 return true;
9242 }
9243 if (components != null) {
9244 for (int i=0; i<components.size(); i++) {
9245 if (components.get(i).equals(comp)) {
9246 return true;
9247 }
9248 }
9249 }
9250 if (objects != null) {
9251 for (int i=0; i<objects.size(); i++) {
9252 if (System.identityHashCode(object) == objects.get(i)) {
9253 return true;
9254 }
9255 }
9256 }
9257 if (strings != null) {
9258 String flat = comp.flattenToString();
9259 for (int i=0; i<strings.size(); i++) {
9260 if (flat.contains(strings.get(i))) {
9261 return true;
9262 }
9263 }
9264 }
9265 return false;
9266 }
9267 }
9268
Dianne Hackborn625ac272010-09-17 18:29:22 -07009269 /**
9270 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009271 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009272 * - the cmd arg isn't the flattened component name of an existing activity:
9273 * dump all activity whose component contains the cmd as a substring
9274 * - A hex number of the ActivityRecord object instance.
9275 */
9276 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9277 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009278 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279
9280 if ("all".equals(name)) {
9281 synchronized (this) {
9282 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009283 activities.add(r1);
9284 }
9285 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009286 } else if ("top".equals(name)) {
9287 synchronized (this) {
9288 final int N = mMainStack.mHistory.size();
9289 if (N > 0) {
9290 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9291 }
9292 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009293 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009294 ItemMatcher matcher = new ItemMatcher();
9295 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009296
9297 synchronized (this) {
9298 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009299 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009300 activities.add(r1);
9301 }
9302 }
9303 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009304 }
9305
9306 if (activities.size() <= 0) {
9307 return false;
9308 }
9309
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009310 String[] newArgs = new String[args.length - opti];
9311 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9312
Dianne Hackborn30d71892010-12-11 10:37:55 -08009313 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009314 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009315 for (int i=activities.size()-1; i>=0; i--) {
9316 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009317 if (needSep) {
9318 pw.println();
9319 }
9320 needSep = true;
9321 synchronized (this) {
9322 if (lastTask != r.task) {
9323 lastTask = r.task;
9324 pw.print("TASK "); pw.print(lastTask.affinity);
9325 pw.print(" id="); pw.println(lastTask.taskId);
9326 if (dumpAll) {
9327 lastTask.dump(pw, " ");
9328 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009329 }
9330 }
9331 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009332 }
9333 return true;
9334 }
9335
9336 /**
9337 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9338 * there is a thread associated with the activity.
9339 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009340 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009341 final ActivityRecord r, String[] args, boolean dumpAll) {
9342 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009343 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009344 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9345 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9346 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009347 if (r.app != null) pw.println(r.app.pid);
9348 else pw.println("(not running)");
9349 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009350 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009351 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009352 }
9353 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009354 // flush anything that is already in the PrintWriter since the thread is going
9355 // to write to the file descriptor directly
9356 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009357 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009358 TransferPipe tp = new TransferPipe();
9359 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009360 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9361 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009362 tp.go(fd);
9363 } finally {
9364 tp.kill();
9365 }
9366 } catch (IOException e) {
9367 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009368 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009369 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009370 }
9371 }
9372 }
9373
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009374 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009375 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009376 boolean needSep = false;
9377
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009378 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009379 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009381 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382 Iterator it = mRegisteredReceivers.values().iterator();
9383 while (it.hasNext()) {
9384 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009385 if (dumpPackage != null && (r.app == null ||
9386 !dumpPackage.equals(r.app.info.packageName))) {
9387 continue;
9388 }
9389 if (!printed) {
9390 pw.println(" Registered Receivers:");
9391 needSep = true;
9392 printed = true;
9393 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009394 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009395 r.dump(pw, " ");
9396 }
9397 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009398
9399 if (mReceiverResolver.dump(pw, needSep ?
9400 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9401 " ", dumpPackage, false)) {
9402 needSep = true;
9403 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009404 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009405
9406 for (BroadcastQueue q : mBroadcastQueues) {
9407 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009409
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009410 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009411
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009412 if (mStickyBroadcasts != null && dumpPackage == null) {
9413 if (needSep) {
9414 pw.println();
9415 }
9416 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009417 pw.println(" Sticky broadcasts:");
9418 StringBuilder sb = new StringBuilder(128);
9419 for (Map.Entry<String, ArrayList<Intent>> ent
9420 : mStickyBroadcasts.entrySet()) {
9421 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009422 if (dumpAll) {
9423 pw.println(":");
9424 ArrayList<Intent> intents = ent.getValue();
9425 final int N = intents.size();
9426 for (int i=0; i<N; i++) {
9427 sb.setLength(0);
9428 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009429 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009430 pw.println(sb.toString());
9431 Bundle bundle = intents.get(i).getExtras();
9432 if (bundle != null) {
9433 pw.print(" ");
9434 pw.println(bundle.toString());
9435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009436 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009437 } else {
9438 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009439 }
9440 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009441 needSep = true;
9442 }
9443
9444 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009445 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009446 for (BroadcastQueue queue : mBroadcastQueues) {
9447 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9448 + queue.mBroadcastsScheduled);
9449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009450 pw.println(" mHandler:");
9451 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009452 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009454
9455 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 }
9457
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009458 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009459 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009460 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009462 ItemMatcher matcher = new ItemMatcher();
9463 matcher.build(args, opti);
9464
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009465 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009466
9467 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009468
9469 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009470 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009471 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009472 ContentProviderRecord r = mLaunchingProviders.get(i);
9473 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9474 continue;
9475 }
9476 if (!printed) {
9477 if (needSep) pw.println(" ");
9478 needSep = true;
9479 pw.println(" Launching content providers:");
9480 printed = true;
9481 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009482 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009483 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009485 }
9486
9487 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 if (needSep) pw.println();
9489 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009490 pw.println("Granted Uri Permissions:");
9491 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9492 int uid = mGrantedUriPermissions.keyAt(i);
9493 HashMap<Uri, UriPermission> perms
9494 = mGrantedUriPermissions.valueAt(i);
9495 pw.print(" * UID "); pw.print(uid);
9496 pw.println(" holds:");
9497 for (UriPermission perm : perms.values()) {
9498 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009499 if (dumpAll) {
9500 perm.dump(pw, " ");
9501 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009502 }
9503 }
9504 needSep = true;
9505 }
9506
9507 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009508 }
9509
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009510 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009511 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009512 boolean needSep = false;
9513
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 if (mIntentSenderRecords.size() > 0) {
9515 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 Iterator<WeakReference<PendingIntentRecord>> it
9517 = mIntentSenderRecords.values().iterator();
9518 while (it.hasNext()) {
9519 WeakReference<PendingIntentRecord> ref = it.next();
9520 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009521 if (dumpPackage != null && (rec == null
9522 || !dumpPackage.equals(rec.key.packageName))) {
9523 continue;
9524 }
9525 if (!printed) {
9526 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9527 printed = true;
9528 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 needSep = true;
9530 if (rec != null) {
9531 pw.print(" * "); pw.println(rec);
9532 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009533 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009535 } else {
9536 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009537 }
9538 }
9539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009540
9541 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 }
9543
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009544 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 String prefix, String label, boolean complete, boolean brief, boolean client,
9546 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009547 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009548 boolean needNL = false;
9549 final String innerPrefix = prefix + " ";
9550 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009552 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009553 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9554 continue;
9555 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009556 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009557 if (needNL) {
9558 pw.println(" ");
9559 needNL = false;
9560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 if (lastTask != r.task) {
9562 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009563 pw.print(prefix);
9564 pw.print(full ? "* " : " ");
9565 pw.println(lastTask);
9566 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009567 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009568 } else if (complete) {
9569 // Complete + brief == give a summary. Isn't that obvious?!?
9570 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009571 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009572 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009576 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9577 pw.print(" #"); pw.print(i); pw.print(": ");
9578 pw.println(r);
9579 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009580 r.dump(pw, innerPrefix);
9581 } else if (complete) {
9582 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009583 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 if (r.app != null) {
9585 pw.print(innerPrefix); pw.println(r.app);
9586 }
9587 }
9588 if (client && r.app != null && r.app.thread != null) {
9589 // flush anything that is already in the PrintWriter since the thread is going
9590 // to write to the file descriptor directly
9591 pw.flush();
9592 try {
9593 TransferPipe tp = new TransferPipe();
9594 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009595 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9596 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009597 // Short timeout, since blocking here can
9598 // deadlock with the application.
9599 tp.go(fd, 2000);
9600 } finally {
9601 tp.kill();
9602 }
9603 } catch (IOException e) {
9604 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9605 } catch (RemoteException e) {
9606 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9607 }
9608 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009610 }
9611 }
9612
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009613 private static String buildOomTag(String prefix, String space, int val, int base) {
9614 if (val == base) {
9615 if (space == null) return prefix;
9616 return prefix + " ";
9617 }
9618 return prefix + "+" + Integer.toString(val-base);
9619 }
9620
9621 private static final int dumpProcessList(PrintWriter pw,
9622 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 String prefix, String normalLabel, String persistentLabel,
9624 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009625 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009626 final int N = list.size()-1;
9627 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009628 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009629 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9630 continue;
9631 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009632 pw.println(String.format("%s%s #%2d: %s",
9633 prefix, (r.persistent ? persistentLabel : normalLabel),
9634 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009635 if (r.persistent) {
9636 numPers++;
9637 }
9638 }
9639 return numPers;
9640 }
9641
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009642 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009643 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009644 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009645 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009646
Dianne Hackborn905577f2011-09-07 18:31:28 -07009647 ArrayList<Pair<ProcessRecord, Integer>> list
9648 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9649 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009650 ProcessRecord r = origList.get(i);
9651 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9652 continue;
9653 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009654 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9655 }
9656
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009657 if (list.size() <= 0) {
9658 return false;
9659 }
9660
Dianne Hackborn905577f2011-09-07 18:31:28 -07009661 Comparator<Pair<ProcessRecord, Integer>> comparator
9662 = new Comparator<Pair<ProcessRecord, Integer>>() {
9663 @Override
9664 public int compare(Pair<ProcessRecord, Integer> object1,
9665 Pair<ProcessRecord, Integer> object2) {
9666 if (object1.first.setAdj != object2.first.setAdj) {
9667 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9668 }
9669 if (object1.second.intValue() != object2.second.intValue()) {
9670 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9671 }
9672 return 0;
9673 }
9674 };
9675
9676 Collections.sort(list, comparator);
9677
Dianne Hackborn287952c2010-09-22 22:34:31 -07009678 final long curRealtime = SystemClock.elapsedRealtime();
9679 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9680 final long curUptime = SystemClock.uptimeMillis();
9681 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9682
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009683 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009684 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009685 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009686 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009687 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009688 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9689 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009690 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9691 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009692 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9693 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009694 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9695 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009696 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009697 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009698 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9699 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9700 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9701 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9702 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9703 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9704 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9705 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009706 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9707 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009708 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9709 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009710 } else {
9711 oomAdj = Integer.toString(r.setAdj);
9712 }
9713 String schedGroup;
9714 switch (r.setSchedGroup) {
9715 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9716 schedGroup = "B";
9717 break;
9718 case Process.THREAD_GROUP_DEFAULT:
9719 schedGroup = "F";
9720 break;
9721 default:
9722 schedGroup = Integer.toString(r.setSchedGroup);
9723 break;
9724 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009725 String foreground;
9726 if (r.foregroundActivities) {
9727 foreground = "A";
9728 } else if (r.foregroundServices) {
9729 foreground = "S";
9730 } else {
9731 foreground = " ";
9732 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009733 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009734 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009735 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9736 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009737 if (r.adjSource != null || r.adjTarget != null) {
9738 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009740 if (r.adjTarget instanceof ComponentName) {
9741 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9742 } else if (r.adjTarget != null) {
9743 pw.print(r.adjTarget.toString());
9744 } else {
9745 pw.print("{null}");
9746 }
9747 pw.print("<=");
9748 if (r.adjSource instanceof ProcessRecord) {
9749 pw.print("Proc{");
9750 pw.print(((ProcessRecord)r.adjSource).toShortString());
9751 pw.println("}");
9752 } else if (r.adjSource != null) {
9753 pw.println(r.adjSource.toString());
9754 } else {
9755 pw.println("{null}");
9756 }
9757 }
9758 if (inclDetails) {
9759 pw.print(prefix);
9760 pw.print(" ");
9761 pw.print("oom: max="); pw.print(r.maxAdj);
9762 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009763 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009764 pw.print(" curRaw="); pw.print(r.curRawAdj);
9765 pw.print(" setRaw="); pw.print(r.setRawAdj);
9766 pw.print(" cur="); pw.print(r.curAdj);
9767 pw.print(" set="); pw.println(r.setAdj);
9768 pw.print(prefix);
9769 pw.print(" ");
9770 pw.print("keeping="); pw.print(r.keeping);
9771 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009772 pw.print(" empty="); pw.print(r.empty);
9773 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009774
9775 if (!r.keeping) {
9776 if (r.lastWakeTime != 0) {
9777 long wtime;
9778 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9779 synchronized (stats) {
9780 wtime = stats.getProcessWakeTime(r.info.uid,
9781 r.pid, curRealtime);
9782 }
9783 long timeUsed = wtime - r.lastWakeTime;
9784 pw.print(prefix);
9785 pw.print(" ");
9786 pw.print("keep awake over ");
9787 TimeUtils.formatDuration(realtimeSince, pw);
9788 pw.print(" used ");
9789 TimeUtils.formatDuration(timeUsed, pw);
9790 pw.print(" (");
9791 pw.print((timeUsed*100)/realtimeSince);
9792 pw.println("%)");
9793 }
9794 if (r.lastCpuTime != 0) {
9795 long timeUsed = r.curCpuTime - r.lastCpuTime;
9796 pw.print(prefix);
9797 pw.print(" ");
9798 pw.print("run cpu over ");
9799 TimeUtils.formatDuration(uptimeSince, pw);
9800 pw.print(" used ");
9801 TimeUtils.formatDuration(timeUsed, pw);
9802 pw.print(" (");
9803 pw.print((timeUsed*100)/uptimeSince);
9804 pw.println("%)");
9805 }
9806 }
9807 }
9808 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009809 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009810 }
9811
Dianne Hackbornb437e092011-08-05 17:50:29 -07009812 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009813 ArrayList<ProcessRecord> procs;
9814 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009815 if (args != null && args.length > start
9816 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009817 procs = new ArrayList<ProcessRecord>();
9818 int pid = -1;
9819 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009820 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009821 } catch (NumberFormatException e) {
9822
9823 }
9824 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9825 ProcessRecord proc = mLruProcesses.get(i);
9826 if (proc.pid == pid) {
9827 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009828 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009829 procs.add(proc);
9830 }
9831 }
9832 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009833 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009834 return null;
9835 }
9836 } else {
9837 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9838 }
9839 }
9840 return procs;
9841 }
9842
9843 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9844 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009845 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009846 if (procs == null) {
9847 return;
9848 }
9849
9850 long uptime = SystemClock.uptimeMillis();
9851 long realtime = SystemClock.elapsedRealtime();
9852 pw.println("Applications Graphics Acceleration Info:");
9853 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9854
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009855 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9856 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009857 if (r.thread != null) {
9858 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9859 pw.flush();
9860 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009861 TransferPipe tp = new TransferPipe();
9862 try {
9863 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9864 tp.go(fd);
9865 } finally {
9866 tp.kill();
9867 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009868 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009869 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009870 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009871 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009872 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009873 pw.flush();
9874 }
9875 }
9876 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009877 }
9878
Jeff Brown6754ba22011-12-14 20:20:01 -08009879 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9880 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9881 if (procs == null) {
9882 return;
9883 }
9884
9885 pw.println("Applications Database Info:");
9886
9887 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9888 ProcessRecord r = procs.get(i);
9889 if (r.thread != null) {
9890 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9891 pw.flush();
9892 try {
9893 TransferPipe tp = new TransferPipe();
9894 try {
9895 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9896 tp.go(fd);
9897 } finally {
9898 tp.kill();
9899 }
9900 } catch (IOException e) {
9901 pw.println("Failure while dumping the app: " + r);
9902 pw.flush();
9903 } catch (RemoteException e) {
9904 pw.println("Got a RemoteException while dumping the app " + r);
9905 pw.flush();
9906 }
9907 }
9908 }
9909 }
9910
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009911 final static class MemItem {
9912 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009913 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009914 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009915 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009916 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009917
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009918 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009919 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009920 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009921 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009922 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009923 }
9924 }
9925
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009926 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009927 boolean sort) {
9928 if (sort) {
9929 Collections.sort(items, new Comparator<MemItem>() {
9930 @Override
9931 public int compare(MemItem lhs, MemItem rhs) {
9932 if (lhs.pss < rhs.pss) {
9933 return 1;
9934 } else if (lhs.pss > rhs.pss) {
9935 return -1;
9936 }
9937 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009938 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009939 });
9940 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009941
9942 for (int i=0; i<items.size(); i++) {
9943 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009944 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009945 if (mi.subitems != null) {
9946 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9947 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009948 }
9949 }
9950
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009951 // These are in KB.
9952 static final long[] DUMP_MEM_BUCKETS = new long[] {
9953 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9954 120*1024, 160*1024, 200*1024,
9955 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9956 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9957 };
9958
Dianne Hackborn672342c2011-11-29 11:29:02 -08009959 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9960 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009961 int start = label.lastIndexOf('.');
9962 if (start >= 0) start++;
9963 else start = 0;
9964 int end = label.length();
9965 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9966 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9967 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9968 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009969 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009970 out.append(label, start, end);
9971 return;
9972 }
9973 }
9974 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009975 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009976 out.append(label, start, end);
9977 }
9978
9979 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9980 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9981 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9982 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9983 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9984 };
9985 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9986 "System", "Persistent", "Foreground",
9987 "Visible", "Perceptible", "Heavy Weight",
9988 "Backup", "A Services", "Home", "Previous",
9989 "B Services", "Background"
9990 };
9991
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009992 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009993 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009994 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009995 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009996 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009997
9998 int opti = 0;
9999 while (opti < args.length) {
10000 String opt = args[opti];
10001 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10002 break;
10003 }
10004 opti++;
10005 if ("-a".equals(opt)) {
10006 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010007 } else if ("--oom".equals(opt)) {
10008 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010009 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010010 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010011 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010012 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010013 pw.println("If [process] is specified it can be the name or ");
10014 pw.println("pid of a specific process to dump.");
10015 return;
10016 } else {
10017 pw.println("Unknown argument: " + opt + "; use -h for help");
10018 }
10019 }
10020
10021 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010022 if (procs == null) {
10023 return;
10024 }
10025
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010026 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010027 long uptime = SystemClock.uptimeMillis();
10028 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010029
10030 if (procs.size() == 1 || isCheckinRequest) {
10031 dumpAll = true;
10032 }
10033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010034 if (isCheckinRequest) {
10035 // short checkin version
10036 pw.println(uptime + "," + realtime);
10037 pw.flush();
10038 } else {
10039 pw.println("Applications Memory Usage (kB):");
10040 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10041 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010042
Dianne Hackbornb437e092011-08-05 17:50:29 -070010043 String[] innerArgs = new String[args.length-opti];
10044 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10045
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010046 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10047 long nativePss=0, dalvikPss=0, otherPss=0;
10048 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10049
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010050 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10051 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10052 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010053
10054 long totalPss = 0;
10055
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010056 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10057 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010058 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010059 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10061 pw.flush();
10062 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010063 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010064 if (dumpAll) {
10065 try {
10066 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10067 } catch (RemoteException e) {
10068 if (!isCheckinRequest) {
10069 pw.println("Got RemoteException!");
10070 pw.flush();
10071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010072 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010073 } else {
10074 mi = new Debug.MemoryInfo();
10075 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010076 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010077
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010078 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010079 long myTotalPss = mi.getTotalPss();
10080 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010081 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010082 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010083 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010084
10085 nativePss += mi.nativePss;
10086 dalvikPss += mi.dalvikPss;
10087 otherPss += mi.otherPss;
10088 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10089 long mem = mi.getOtherPss(j);
10090 miscPss[j] += mem;
10091 otherPss -= mem;
10092 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010093
10094 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010095 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10096 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010097 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010098 if (oomProcs[oomIndex] == null) {
10099 oomProcs[oomIndex] = new ArrayList<MemItem>();
10100 }
10101 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010102 break;
10103 }
10104 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010106 }
10107 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108
10109 if (!isCheckinRequest && procs.size() > 1) {
10110 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10111
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010112 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10113 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10114 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010115 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010116 String label = Debug.MemoryInfo.getOtherLabel(j);
10117 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010118 }
10119
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10121 for (int j=0; j<oomPss.length; j++) {
10122 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010123 String label = DUMP_MEM_OOM_LABEL[j];
10124 MemItem item = new MemItem(label, label, oomPss[j],
10125 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010126 item.subitems = oomProcs[j];
10127 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128 }
10129 }
10130
Dianne Hackborn672342c2011-11-29 11:29:02 -080010131 if (outTag != null || outStack != null) {
10132 if (outTag != null) {
10133 appendMemBucket(outTag, totalPss, "total", false);
10134 }
10135 if (outStack != null) {
10136 appendMemBucket(outStack, totalPss, "total", true);
10137 }
10138 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010139 for (int i=0; i<oomMems.size(); i++) {
10140 MemItem miCat = oomMems.get(i);
10141 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10142 continue;
10143 }
10144 if (miCat.id < ProcessList.SERVICE_ADJ
10145 || miCat.id == ProcessList.HOME_APP_ADJ
10146 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010147 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10148 outTag.append(" / ");
10149 }
10150 if (outStack != null) {
10151 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10152 if (firstLine) {
10153 outStack.append(":");
10154 firstLine = false;
10155 }
10156 outStack.append("\n\t at ");
10157 } else {
10158 outStack.append("$");
10159 }
10160 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010161 for (int j=0; j<miCat.subitems.size(); j++) {
10162 MemItem mi = miCat.subitems.get(j);
10163 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010164 if (outTag != null) {
10165 outTag.append(" ");
10166 }
10167 if (outStack != null) {
10168 outStack.append("$");
10169 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010170 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010171 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10172 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10173 }
10174 if (outStack != null) {
10175 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10176 }
10177 }
10178 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10179 outStack.append("(");
10180 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10181 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10182 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10183 outStack.append(":");
10184 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10185 }
10186 }
10187 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010188 }
10189 }
10190 }
10191 }
10192
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010193 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010194 pw.println();
10195 pw.println("Total PSS by process:");
10196 dumpMemItems(pw, " ", procMems, true);
10197 pw.println();
10198 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010199 pw.println("Total PSS by OOM adjustment:");
10200 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010201 if (!oomOnly) {
10202 PrintWriter out = categoryPw != null ? categoryPw : pw;
10203 out.println();
10204 out.println("Total PSS by category:");
10205 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010206 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010207 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010208 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010209 final int[] SINGLE_LONG_FORMAT = new int[] {
10210 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10211 };
10212 long[] longOut = new long[1];
10213 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10214 SINGLE_LONG_FORMAT, null, longOut, null);
10215 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10216 longOut[0] = 0;
10217 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10218 SINGLE_LONG_FORMAT, null, longOut, null);
10219 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10220 longOut[0] = 0;
10221 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10222 SINGLE_LONG_FORMAT, null, longOut, null);
10223 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10224 longOut[0] = 0;
10225 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10226 SINGLE_LONG_FORMAT, null, longOut, null);
10227 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10228 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10229 pw.print(shared); pw.println(" kB");
10230 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10231 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010233 }
10234
10235 /**
10236 * Searches array of arguments for the specified string
10237 * @param args array of argument strings
10238 * @param value value to search for
10239 * @return true if the value is contained in the array
10240 */
10241 private static boolean scanArgs(String[] args, String value) {
10242 if (args != null) {
10243 for (String arg : args) {
10244 if (value.equals(arg)) {
10245 return true;
10246 }
10247 }
10248 }
10249 return false;
10250 }
10251
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010252 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10253 ContentProviderRecord cpr, boolean always) {
10254 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10255
10256 if (!inLaunching || always) {
10257 synchronized (cpr) {
10258 cpr.launchingApp = null;
10259 cpr.notifyAll();
10260 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010261 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010262 String names[] = cpr.info.authority.split(";");
10263 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010264 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010265 }
10266 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010267
10268 for (int i=0; i<cpr.connections.size(); i++) {
10269 ContentProviderConnection conn = cpr.connections.get(i);
10270 if (conn.waiting) {
10271 // If this connection is waiting for the provider, then we don't
10272 // need to mess with its process unless we are always removing
10273 // or for some reason the provider is not currently launching.
10274 if (inLaunching && !always) {
10275 continue;
10276 }
10277 }
10278 ProcessRecord capp = conn.client;
10279 conn.dead = true;
10280 if (conn.stableCount > 0) {
10281 if (!capp.persistent && capp.thread != null
10282 && capp.pid != 0
10283 && capp.pid != MY_PID) {
10284 Slog.i(TAG, "Kill " + capp.processName
10285 + " (pid " + capp.pid + "): provider " + cpr.info.name
10286 + " in dying process " + (proc != null ? proc.processName : "??"));
10287 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10288 capp.processName, capp.setAdj, "dying provider "
10289 + cpr.name.toShortString());
10290 Process.killProcessQuiet(capp.pid);
10291 }
10292 } else if (capp.thread != null && conn.provider.provider != null) {
10293 try {
10294 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10295 } catch (RemoteException e) {
10296 }
10297 // In the protocol here, we don't expect the client to correctly
10298 // clean up this connection, we'll just remove it.
10299 cpr.connections.remove(i);
10300 conn.client.conProviders.remove(conn);
10301 }
10302 }
10303
10304 if (inLaunching && always) {
10305 mLaunchingProviders.remove(cpr);
10306 }
10307 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 }
10309
10310 /**
10311 * Main code for cleaning up a process when it has gone away. This is
10312 * called both as a result of the process dying, or directly when stopping
10313 * a process when running in single process mode.
10314 */
10315 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010316 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010317 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010318 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010319 }
10320
Dianne Hackborn36124872009-10-08 16:22:03 -070010321 mProcessesToGc.remove(app);
10322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010323 // Dismiss any open dialogs.
10324 if (app.crashDialog != null) {
10325 app.crashDialog.dismiss();
10326 app.crashDialog = null;
10327 }
10328 if (app.anrDialog != null) {
10329 app.anrDialog.dismiss();
10330 app.anrDialog = null;
10331 }
10332 if (app.waitDialog != null) {
10333 app.waitDialog.dismiss();
10334 app.waitDialog = null;
10335 }
10336
10337 app.crashing = false;
10338 app.notResponding = false;
10339
10340 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010341 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 app.thread = null;
10343 app.forcingToForeground = null;
10344 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010345 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010346 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010347 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010348
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010349 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350
10351 boolean restart = false;
10352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010353 // Remove published content providers.
10354 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010355 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010356 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010357 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010358
10359 final boolean always = app.bad || !allowRestart;
10360 if (removeDyingProviderLocked(app, cpr, always) || always) {
10361 // We left the provider in the launching list, need to
10362 // restart it.
10363 restart = true;
10364 }
10365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010366 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010367 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010368 }
10369 app.pubProviders.clear();
10370 }
10371
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010372 // Take care of any launching providers waiting for this process.
10373 if (checkAppInLaunchingProvidersLocked(app, false)) {
10374 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010377 // Unregister from connected content providers.
10378 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010379 for (int i=0; i<app.conProviders.size(); i++) {
10380 ContentProviderConnection conn = app.conProviders.get(i);
10381 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383 app.conProviders.clear();
10384 }
10385
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010386 // At this point there may be remaining entries in mLaunchingProviders
10387 // where we were the only one waiting, so they are no longer of use.
10388 // Look for these and clean up if found.
10389 // XXX Commented out for now. Trying to figure out a way to reproduce
10390 // the actual situation to identify what is actually going on.
10391 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010392 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010393 ContentProviderRecord cpr = (ContentProviderRecord)
10394 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010395 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010396 synchronized (cpr) {
10397 cpr.launchingApp = null;
10398 cpr.notifyAll();
10399 }
10400 }
10401 }
10402 }
10403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010404 skipCurrentReceiverLocked(app);
10405
10406 // Unregister any receivers.
10407 if (app.receivers.size() > 0) {
10408 Iterator<ReceiverList> it = app.receivers.iterator();
10409 while (it.hasNext()) {
10410 removeReceiverLocked(it.next());
10411 }
10412 app.receivers.clear();
10413 }
10414
Christopher Tate181fafa2009-05-14 11:12:14 -070010415 // If the app is undergoing backup, tell the backup manager about it
10416 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010417 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010418 try {
10419 IBackupManager bm = IBackupManager.Stub.asInterface(
10420 ServiceManager.getService(Context.BACKUP_SERVICE));
10421 bm.agentDisconnected(app.info.packageName);
10422 } catch (RemoteException e) {
10423 // can't happen; backup manager is local
10424 }
10425 }
10426
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010427 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10428 ProcessChangeItem item = mPendingProcessChanges.get(i);
10429 if (item.pid == app.pid) {
10430 mPendingProcessChanges.remove(i);
10431 mAvailProcessChanges.add(item);
10432 }
10433 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010434 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 // If the caller is restarting this app, then leave it in its
10437 // current lists and let the caller take care of it.
10438 if (restarting) {
10439 return;
10440 }
10441
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010442 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010443 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010444 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010445 mProcessNames.remove(app.processName, app.uid);
10446 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010447 if (mHeavyWeightProcess == app) {
10448 mHeavyWeightProcess = null;
10449 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 } else if (!app.removed) {
10452 // This app is persistent, so we need to keep its record around.
10453 // If it is not already on the pending app list, add it there
10454 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010455 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10456 mPersistentStartingProcesses.add(app);
10457 restart = true;
10458 }
10459 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010460 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10461 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 mProcessesOnHold.remove(app);
10463
The Android Open Source Project4df24232009-03-05 14:34:35 -080010464 if (app == mHomeProcess) {
10465 mHomeProcess = null;
10466 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010467 if (app == mPreviousProcess) {
10468 mPreviousProcess = null;
10469 }
10470
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010471 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 // We have components that still need to be running in the
10473 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010474 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 startProcessLocked(app, "restart", app.processName);
10476 } else if (app.pid > 0 && app.pid != MY_PID) {
10477 // Goodbye!
10478 synchronized (mPidsSelfLocked) {
10479 mPidsSelfLocked.remove(app.pid);
10480 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10481 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010482 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 }
10484 }
10485
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010486 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10487 // Look through the content providers we are waiting to have launched,
10488 // and if any run in this process then either schedule a restart of
10489 // the process or kill the client waiting for it if this process has
10490 // gone bad.
10491 int NL = mLaunchingProviders.size();
10492 boolean restart = false;
10493 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010494 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010495 if (cpr.launchingApp == app) {
10496 if (!alwaysBad && !app.bad) {
10497 restart = true;
10498 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010499 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010500 NL = mLaunchingProviders.size();
10501 }
10502 }
10503 }
10504 return restart;
10505 }
10506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010507 // =========================================================
10508 // SERVICES
10509 // =========================================================
10510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010511 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10512 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010513 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010515 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 }
10517 }
10518
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010519 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010520 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010521 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010522 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010523 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010524 }
10525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010526 public ComponentName startService(IApplicationThread caller, Intent service,
10527 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010528 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 // Refuse possible leaked file descriptors
10530 if (service != null && service.hasFileDescriptors() == true) {
10531 throw new IllegalArgumentException("File descriptors passed in Intent");
10532 }
10533
Amith Yamasani742a6712011-05-04 14:49:28 -070010534 if (DEBUG_SERVICE)
10535 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010536 synchronized(this) {
10537 final int callingPid = Binder.getCallingPid();
10538 final int callingUid = Binder.getCallingUid();
10539 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010540 ComponentName res = mServices.startServiceLocked(caller, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010541 resolvedType, callingPid, callingUid);
10542 Binder.restoreCallingIdentity(origId);
10543 return res;
10544 }
10545 }
10546
10547 ComponentName startServiceInPackage(int uid,
10548 Intent service, String resolvedType) {
10549 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010550 if (DEBUG_SERVICE)
10551 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010553 ComponentName res = mServices.startServiceLocked(null, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010554 resolvedType, -1, uid);
10555 Binder.restoreCallingIdentity(origId);
10556 return res;
10557 }
10558 }
10559
10560 public int stopService(IApplicationThread caller, Intent service,
10561 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010562 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 // Refuse possible leaked file descriptors
10564 if (service != null && service.hasFileDescriptors() == true) {
10565 throw new IllegalArgumentException("File descriptors passed in Intent");
10566 }
10567
10568 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010569 return mServices.stopServiceLocked(caller, service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010571 }
10572
10573 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010574 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 // Refuse possible leaked file descriptors
10576 if (service != null && service.hasFileDescriptors() == true) {
10577 throw new IllegalArgumentException("File descriptors passed in Intent");
10578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010580 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 }
10583
10584 public boolean stopServiceToken(ComponentName className, IBinder token,
10585 int startId) {
10586 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010587 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 }
10590
10591 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010592 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010594 mServices.setServiceForegroundLocked(className, token, id, notification,
10595 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010596 }
10597 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010598
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010599 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10600 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010601 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010602 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010603 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10604 if (ActivityManager.checkUidPermission(
10605 android.Manifest.permission.INTERACT_ACROSS_USERS,
10606 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10607 ComponentName comp = new ComponentName(aInfo.packageName, className);
10608 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10609 + " requests FLAG_SINGLE_USER, but app does not hold "
10610 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10611 Slog.w(TAG, msg);
10612 throw new SecurityException(msg);
10613 }
10614 result = true;
10615 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010616 } else if (componentProcessName == aInfo.packageName) {
10617 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10618 } else if ("system".equals(componentProcessName)) {
10619 result = true;
10620 }
10621 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010622 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10623 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010624 }
10625 return result;
10626 }
10627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 public int bindService(IApplicationThread caller, IBinder token,
10629 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010630 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010631 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 // Refuse possible leaked file descriptors
10633 if (service != null && service.hasFileDescriptors() == true) {
10634 throw new IllegalArgumentException("File descriptors passed in Intent");
10635 }
10636
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010637 checkValidCaller(Binder.getCallingUid(), userId);
10638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010640 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10641 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010642 }
10643 }
10644
10645 public boolean unbindService(IServiceConnection connection) {
10646 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010647 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 }
10650
10651 public void publishService(IBinder token, Intent intent, IBinder service) {
10652 // Refuse possible leaked file descriptors
10653 if (intent != null && intent.hasFileDescriptors() == true) {
10654 throw new IllegalArgumentException("File descriptors passed in Intent");
10655 }
10656
10657 synchronized(this) {
10658 if (!(token instanceof ServiceRecord)) {
10659 throw new IllegalArgumentException("Invalid service token");
10660 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010661 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 }
10663 }
10664
10665 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10666 // Refuse possible leaked file descriptors
10667 if (intent != null && intent.hasFileDescriptors() == true) {
10668 throw new IllegalArgumentException("File descriptors passed in Intent");
10669 }
10670
10671 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010672 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 }
10674 }
10675
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010676 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010677 synchronized(this) {
10678 if (!(token instanceof ServiceRecord)) {
10679 throw new IllegalArgumentException("Invalid service token");
10680 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010681 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 }
10684
10685 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010686 // BACKUP AND RESTORE
10687 // =========================================================
10688
10689 // Cause the target app to be launched if necessary and its backup agent
10690 // instantiated. The backup agent will invoke backupAgentCreated() on the
10691 // activity manager to announce its creation.
10692 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010693 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010694 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10695
10696 synchronized(this) {
10697 // !!! TODO: currently no check here that we're already bound
10698 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10699 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10700 synchronized (stats) {
10701 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10702 }
10703
Dianne Hackborne7f97212011-02-24 14:40:20 -080010704 // Backup agent is now in use, its package can't be stopped.
10705 try {
10706 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010707 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010708 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010709 } catch (IllegalArgumentException e) {
10710 Slog.w(TAG, "Failed trying to unstop package "
10711 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010712 }
10713
Christopher Tate181fafa2009-05-14 11:12:14 -070010714 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010715 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10716 ? new ComponentName(app.packageName, app.backupAgentName)
10717 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010718 // startProcessLocked() returns existing proc's record if it's already running
10719 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010720 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010721 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010722 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010723 return false;
10724 }
10725
10726 r.app = proc;
10727 mBackupTarget = r;
10728 mBackupAppName = app.packageName;
10729
Christopher Tate6fa95972009-06-05 18:43:55 -070010730 // Try not to kill the process during backup
10731 updateOomAdjLocked(proc);
10732
Christopher Tate181fafa2009-05-14 11:12:14 -070010733 // If the process is already attached, schedule the creation of the backup agent now.
10734 // If it is not yet live, this will be done when it attaches to the framework.
10735 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010736 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010737 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010738 proc.thread.scheduleCreateBackupAgent(app,
10739 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010740 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010741 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010742 }
10743 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010744 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010745 }
10746 // Invariants: at this point, the target app process exists and the application
10747 // is either already running or in the process of coming up. mBackupTarget and
10748 // mBackupAppName describe the app, so that when it binds back to the AM we
10749 // know that it's scheduled for a backup-agent operation.
10750 }
10751
10752 return true;
10753 }
10754
10755 // A backup agent has just come up
10756 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010757 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010758 + " = " + agent);
10759
10760 synchronized(this) {
10761 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010762 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010763 return;
10764 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010765 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010766
Dianne Hackborn06740692010-09-22 22:46:21 -070010767 long oldIdent = Binder.clearCallingIdentity();
10768 try {
10769 IBackupManager bm = IBackupManager.Stub.asInterface(
10770 ServiceManager.getService(Context.BACKUP_SERVICE));
10771 bm.agentConnected(agentPackageName, agent);
10772 } catch (RemoteException e) {
10773 // can't happen; the backup manager service is local
10774 } catch (Exception e) {
10775 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10776 e.printStackTrace();
10777 } finally {
10778 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010779 }
10780 }
10781
10782 // done with this agent
10783 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010784 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010785 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010786 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010787 return;
10788 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010789
10790 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010791 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010792 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010793 return;
10794 }
10795
Christopher Tate181fafa2009-05-14 11:12:14 -070010796 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010797 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010798 return;
10799 }
10800
Christopher Tate6fa95972009-06-05 18:43:55 -070010801 ProcessRecord proc = mBackupTarget.app;
10802 mBackupTarget = null;
10803 mBackupAppName = null;
10804
10805 // Not backing this app up any more; reset its OOM adjustment
10806 updateOomAdjLocked(proc);
10807
Christopher Tatec7b31e32009-06-10 15:49:30 -070010808 // If the app crashed during backup, 'thread' will be null here
10809 if (proc.thread != null) {
10810 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010811 proc.thread.scheduleDestroyBackupAgent(appInfo,
10812 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010813 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010814 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010815 e.printStackTrace();
10816 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010817 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010818 }
10819 }
10820 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 // BROADCASTS
10822 // =========================================================
10823
Josh Bartel7f208742010-02-25 11:01:44 -060010824 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 List cur) {
10826 final ContentResolver resolver = mContext.getContentResolver();
10827 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10828 if (list == null) {
10829 return cur;
10830 }
10831 int N = list.size();
10832 for (int i=0; i<N; i++) {
10833 Intent intent = list.get(i);
10834 if (filter.match(resolver, intent, true, TAG) >= 0) {
10835 if (cur == null) {
10836 cur = new ArrayList<Intent>();
10837 }
10838 cur.add(intent);
10839 }
10840 }
10841 return cur;
10842 }
10843
Christopher Tatef46723b2012-01-26 14:19:24 -080010844 boolean isPendingBroadcastProcessLocked(int pid) {
10845 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
10846 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
10847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848
Christopher Tatef46723b2012-01-26 14:19:24 -080010849 void skipPendingBroadcastLocked(int pid) {
10850 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
10851 for (BroadcastQueue queue : mBroadcastQueues) {
10852 queue.skipPendingBroadcastLocked(pid);
10853 }
10854 }
10855
10856 // The app just attached; send any pending broadcasts that it should receive
10857 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
10858 boolean didSomething = false;
10859 for (BroadcastQueue queue : mBroadcastQueues) {
10860 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010862 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010863 }
10864
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010865 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010867 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010868 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010869 synchronized(this) {
10870 ProcessRecord callerApp = null;
10871 if (caller != null) {
10872 callerApp = getRecordForAppLocked(caller);
10873 if (callerApp == null) {
10874 throw new SecurityException(
10875 "Unable to find app for caller " + caller
10876 + " (pid=" + Binder.getCallingPid()
10877 + ") when registering receiver " + receiver);
10878 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010879 if (callerApp.info.uid != Process.SYSTEM_UID &&
10880 !callerApp.pkgList.contains(callerPackage)) {
10881 throw new SecurityException("Given caller package " + callerPackage
10882 + " is not running in process " + callerApp);
10883 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010884 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010885 } else {
10886 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010887 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 }
10889
10890 List allSticky = null;
10891
10892 // Look for any matching sticky broadcasts...
10893 Iterator actions = filter.actionsIterator();
10894 if (actions != null) {
10895 while (actions.hasNext()) {
10896 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010897 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010898 }
10899 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010900 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010901 }
10902
10903 // The first sticky in the list is returned directly back to
10904 // the client.
10905 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10906
Joe Onorato8a9b2202010-02-26 18:56:32 -080010907 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 + ": " + sticky);
10909
10910 if (receiver == null) {
10911 return sticky;
10912 }
10913
10914 ReceiverList rl
10915 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10916 if (rl == null) {
10917 rl = new ReceiverList(this, callerApp,
10918 Binder.getCallingPid(),
10919 Binder.getCallingUid(), receiver);
10920 if (rl.app != null) {
10921 rl.app.receivers.add(rl);
10922 } else {
10923 try {
10924 receiver.asBinder().linkToDeath(rl, 0);
10925 } catch (RemoteException e) {
10926 return sticky;
10927 }
10928 rl.linkedToDeath = true;
10929 }
10930 mRegisteredReceivers.put(receiver.asBinder(), rl);
10931 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010932 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
10933 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 rl.add(bf);
10935 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010936 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010937 }
10938 mReceiverResolver.addFilter(bf);
10939
10940 // Enqueue broadcasts for all existing stickies that match
10941 // this filter.
10942 if (allSticky != null) {
10943 ArrayList receivers = new ArrayList();
10944 receivers.add(bf);
10945
10946 int N = allSticky.size();
10947 for (int i=0; i<N; i++) {
10948 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080010949 BroadcastQueue queue = broadcastQueueForIntent(intent);
10950 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010952 false, true, true, false);
Christopher Tatef46723b2012-01-26 14:19:24 -080010953 queue.enqueueParallelBroadcastLocked(r);
10954 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010955 }
10956 }
10957
10958 return sticky;
10959 }
10960 }
10961
10962 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010963 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010964
Christopher Tatef46723b2012-01-26 14:19:24 -080010965 final long origId = Binder.clearCallingIdentity();
10966 try {
10967 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968
Christopher Tatef46723b2012-01-26 14:19:24 -080010969 synchronized(this) {
10970 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080010972 if (rl != null) {
10973 if (rl.curBroadcast != null) {
10974 BroadcastRecord r = rl.curBroadcast;
10975 final boolean doNext = finishReceiverLocked(
10976 receiver.asBinder(), r.resultCode, r.resultData,
10977 r.resultExtras, r.resultAbort, true);
10978 if (doNext) {
10979 doTrim = true;
10980 r.queue.processNextBroadcast(false);
10981 }
10982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010983
Christopher Tatef46723b2012-01-26 14:19:24 -080010984 if (rl.app != null) {
10985 rl.app.receivers.remove(rl);
10986 }
10987 removeReceiverLocked(rl);
10988 if (rl.linkedToDeath) {
10989 rl.linkedToDeath = false;
10990 rl.receiver.asBinder().unlinkToDeath(rl, 0);
10991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 }
10993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994
Christopher Tatef46723b2012-01-26 14:19:24 -080010995 // If we actually concluded any broadcasts, we might now be able
10996 // to trim the recipients' apps from our working set
10997 if (doTrim) {
10998 trimApplications();
10999 return;
11000 }
11001
11002 } finally {
11003 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011005 }
11006
11007 void removeReceiverLocked(ReceiverList rl) {
11008 mRegisteredReceivers.remove(rl.receiver.asBinder());
11009 int N = rl.size();
11010 for (int i=0; i<N; i++) {
11011 mReceiverResolver.removeFilter(rl.get(i));
11012 }
11013 }
11014
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011015 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
11016 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11017 ProcessRecord r = mLruProcesses.get(i);
11018 if (r.thread != null) {
11019 try {
11020 r.thread.dispatchPackageBroadcast(cmd, packages);
11021 } catch (RemoteException ex) {
11022 }
11023 }
11024 }
11025 }
11026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011027 private final int broadcastIntentLocked(ProcessRecord callerApp,
11028 String callerPackage, Intent intent, String resolvedType,
11029 IIntentReceiver resultTo, int resultCode, String resultData,
11030 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011031 boolean ordered, boolean sticky, int callingPid, int callingUid,
11032 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011033 intent = new Intent(intent);
11034
Dianne Hackborne7f97212011-02-24 14:40:20 -080011035 // By default broadcasts do not go to stopped apps.
11036 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11037
Joe Onorato8a9b2202010-02-26 18:56:32 -080011038 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011040 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011042 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011043 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011044
11045 boolean onlySendToCaller = false;
11046
11047 // If the caller is trying to send this broadcast to a different
11048 // user, verify that is allowed.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011049 if (UserHandle.getUserId(callingUid) != userId) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011050 if (checkComponentPermission(
11051 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11052 callingPid, callingUid, -1, true)
11053 != PackageManager.PERMISSION_GRANTED) {
11054 if (checkComponentPermission(
11055 android.Manifest.permission.INTERACT_ACROSS_USERS,
11056 callingPid, callingUid, -1, true)
11057 == PackageManager.PERMISSION_GRANTED) {
11058 onlySendToCaller = true;
11059 } else {
11060 String msg = "Permission Denial: " + intent.getAction()
11061 + " broadcast from " + callerPackage
11062 + " asks to send as user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011063 + " but is calling from user " + UserHandle.getUserId(callingUid)
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011064 + "; this requires "
11065 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11066 Slog.w(TAG, msg);
11067 throw new SecurityException(msg);
11068 }
11069 }
11070 }
11071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011072 // Handle special intents: if this broadcast is from the package
11073 // manager about a package being removed, we need to remove all of
11074 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011075 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011077 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11078 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011079 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011080 || uidRemoved) {
11081 if (checkComponentPermission(
11082 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011083 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011084 == PackageManager.PERMISSION_GRANTED) {
11085 if (uidRemoved) {
11086 final Bundle intentExtras = intent.getExtras();
11087 final int uid = intentExtras != null
11088 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11089 if (uid >= 0) {
11090 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11091 synchronized (bs) {
11092 bs.removeUidStatsLocked(uid);
11093 }
11094 }
11095 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011096 // If resources are unvailble just force stop all
11097 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011098 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011099 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11100 if (list != null && (list.length > 0)) {
11101 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011102 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011103 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011104 sendPackageBroadcastLocked(
11105 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011106 }
11107 } else {
11108 Uri data = intent.getData();
11109 String ssp;
11110 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11111 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11112 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011113 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11114 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011115 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011116 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011117 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11118 new String[] {ssp});
11119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 }
11121 }
11122 }
11123 } else {
11124 String msg = "Permission Denial: " + intent.getAction()
11125 + " broadcast from " + callerPackage + " (pid=" + callingPid
11126 + ", uid=" + callingUid + ")"
11127 + " requires "
11128 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011129 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 throw new SecurityException(msg);
11131 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011132
11133 // Special case for adding a package: by default turn on compatibility
11134 // mode.
11135 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011136 Uri data = intent.getData();
11137 String ssp;
11138 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11139 mCompatModePackages.handlePackageAddedLocked(ssp,
11140 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 }
11143
11144 /*
11145 * If this is the time zone changed action, queue up a message that will reset the timezone
11146 * of all currently running processes. This message will get queued up before the broadcast
11147 * happens.
11148 */
11149 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11150 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11151 }
11152
Robert Greenwalt03595d02010-11-02 14:08:23 -070011153 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11154 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11155 }
11156
Robert Greenwalt434203a2010-10-11 16:00:27 -070011157 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11158 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11159 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11160 }
11161
Dianne Hackborn854060af2009-07-09 18:14:31 -070011162 /*
11163 * Prevent non-system code (defined here to be non-persistent
11164 * processes) from sending protected broadcasts.
11165 */
11166 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070011167 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11168 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070011169 // Always okay.
11170 } else if (callerApp == null || !callerApp.persistent) {
11171 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011172 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011173 intent.getAction())) {
11174 String msg = "Permission Denial: not allowed to send broadcast "
11175 + intent.getAction() + " from pid="
11176 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011177 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011178 throw new SecurityException(msg);
11179 }
11180 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011181 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011182 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070011183 }
11184 }
11185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 // Add to the sticky list if requested.
11187 if (sticky) {
11188 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11189 callingPid, callingUid)
11190 != PackageManager.PERMISSION_GRANTED) {
11191 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11192 + callingPid + ", uid=" + callingUid
11193 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011194 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011195 throw new SecurityException(msg);
11196 }
11197 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011198 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011199 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011200 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 }
11202 if (intent.getComponent() != null) {
11203 throw new SecurityException(
11204 "Sticky broadcasts can't target a specific component");
11205 }
11206 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11207 if (list == null) {
11208 list = new ArrayList<Intent>();
11209 mStickyBroadcasts.put(intent.getAction(), list);
11210 }
11211 int N = list.size();
11212 int i;
11213 for (i=0; i<N; i++) {
11214 if (intent.filterEquals(list.get(i))) {
11215 // This sticky already exists, replace it.
11216 list.set(i, new Intent(intent));
11217 break;
11218 }
11219 }
11220 if (i >= N) {
11221 list.add(new Intent(intent));
11222 }
11223 }
11224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 // Figure out who all will receive this broadcast.
11226 List receivers = null;
11227 List<BroadcastFilter> registeredReceivers = null;
11228 try {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011229 // Need to resolve the intent to interested receivers...
11230 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11231 == 0) {
11232 receivers = AppGlobals.getPackageManager().queryIntentReceivers(
11233 intent, resolvedType, STOCK_PM_FLAGS, userId);
11234 }
11235 if (intent.getComponent() == null) {
11236 registeredReceivers = mReceiverResolver.queryIntent(intent,
11237 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011238 }
11239 } catch (RemoteException ex) {
11240 // pm is in same process, this will never happen.
11241 }
11242
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011243 final boolean replacePending =
11244 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11245
Joe Onorato8a9b2202010-02-26 18:56:32 -080011246 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011247 + " replacePending=" + replacePending);
11248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11250 if (!ordered && NR > 0) {
11251 // If we are not serializing this broadcast, then send the
11252 // registered receivers separately so they don't wait for the
11253 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011254 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11255 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 callerPackage, callingPid, callingUid, requiredPermission,
11257 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011258 ordered, sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011259 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011260 TAG, "Enqueueing parallel broadcast " + r);
11261 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011262 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011263 queue.enqueueParallelBroadcastLocked(r);
11264 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011266 registeredReceivers = null;
11267 NR = 0;
11268 }
11269
11270 // Merge into one list.
11271 int ir = 0;
11272 if (receivers != null) {
11273 // A special case for PACKAGE_ADDED: do not allow the package
11274 // being added to see this broadcast. This prevents them from
11275 // using this as a back door to get run as soon as they are
11276 // installed. Maybe in the future we want to have a special install
11277 // broadcast or such for apps, but we'd like to deliberately make
11278 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011279 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011280 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11281 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11282 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011283 Uri data = intent.getData();
11284 if (data != null) {
11285 String pkgName = data.getSchemeSpecificPart();
11286 if (pkgName != null) {
11287 skipPackages = new String[] { pkgName };
11288 }
11289 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011290 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011291 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011292 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011293 if (skipPackages != null && (skipPackages.length > 0)) {
11294 for (String skipPackage : skipPackages) {
11295 if (skipPackage != null) {
11296 int NT = receivers.size();
11297 for (int it=0; it<NT; it++) {
11298 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11299 if (curt.activityInfo.packageName.equals(skipPackage)) {
11300 receivers.remove(it);
11301 it--;
11302 NT--;
11303 }
11304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 }
11306 }
11307 }
11308
11309 int NT = receivers != null ? receivers.size() : 0;
11310 int it = 0;
11311 ResolveInfo curt = null;
11312 BroadcastFilter curr = null;
11313 while (it < NT && ir < NR) {
11314 if (curt == null) {
11315 curt = (ResolveInfo)receivers.get(it);
11316 }
11317 if (curr == null) {
11318 curr = registeredReceivers.get(ir);
11319 }
11320 if (curr.getPriority() >= curt.priority) {
11321 // Insert this broadcast record into the final list.
11322 receivers.add(it, curr);
11323 ir++;
11324 curr = null;
11325 it++;
11326 NT++;
11327 } else {
11328 // Skip to the next ResolveInfo in the final list.
11329 it++;
11330 curt = null;
11331 }
11332 }
11333 }
11334 while (ir < NR) {
11335 if (receivers == null) {
11336 receivers = new ArrayList();
11337 }
11338 receivers.add(registeredReceivers.get(ir));
11339 ir++;
11340 }
11341
11342 if ((receivers != null && receivers.size() > 0)
11343 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011344 BroadcastQueue queue = broadcastQueueForIntent(intent);
11345 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011346 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011347 receivers, resultTo, resultCode, resultData, map, ordered,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011348 sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011349 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011351 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011352 if (DEBUG_BROADCAST) {
11353 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011354 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011356 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011357 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011358 queue.enqueueOrderedBroadcastLocked(r);
11359 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011361 }
11362
Dianne Hackborna4972e92012-03-14 10:38:05 -070011363 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 }
11365
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011366 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 // Refuse possible leaked file descriptors
11368 if (intent != null && intent.hasFileDescriptors() == true) {
11369 throw new IllegalArgumentException("File descriptors passed in Intent");
11370 }
11371
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011372 int flags = intent.getFlags();
11373
11374 if (!mProcessesReady) {
11375 // if the caller really truly claims to know what they're doing, go
11376 // ahead and allow the broadcast without launching any receivers
11377 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11378 intent = new Intent(intent);
11379 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11380 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11381 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11382 + " before boot completion");
11383 throw new IllegalStateException("Cannot broadcast before boot completed");
11384 }
11385 }
11386
11387 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11388 throw new IllegalArgumentException(
11389 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11390 }
11391
11392 return intent;
11393 }
11394
11395 public final int broadcastIntent(IApplicationThread caller,
11396 Intent intent, String resolvedType, IIntentReceiver resultTo,
11397 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011398 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011399 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011401 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11404 final int callingPid = Binder.getCallingPid();
11405 final int callingUid = Binder.getCallingUid();
11406 final long origId = Binder.clearCallingIdentity();
11407 int res = broadcastIntentLocked(callerApp,
11408 callerApp != null ? callerApp.info.packageName : null,
11409 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011410 resultCode, resultData, map, requiredPermission, serialized, sticky,
11411 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 Binder.restoreCallingIdentity(origId);
11413 return res;
11414 }
11415 }
11416
11417 int broadcastIntentInPackage(String packageName, int uid,
11418 Intent intent, String resolvedType, IIntentReceiver resultTo,
11419 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011420 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011422 intent = verifyBroadcastLocked(intent);
11423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011424 final long origId = Binder.clearCallingIdentity();
11425 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11426 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011427 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 Binder.restoreCallingIdentity(origId);
11429 return res;
11430 }
11431 }
11432
Amith Yamasani742a6712011-05-04 14:49:28 -070011433 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
11434 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011435 // Refuse possible leaked file descriptors
11436 if (intent != null && intent.hasFileDescriptors() == true) {
11437 throw new IllegalArgumentException("File descriptors passed in Intent");
11438 }
11439
11440 synchronized(this) {
11441 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11442 != PackageManager.PERMISSION_GRANTED) {
11443 String msg = "Permission Denial: unbroadcastIntent() from pid="
11444 + Binder.getCallingPid()
11445 + ", uid=" + Binder.getCallingUid()
11446 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011447 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 throw new SecurityException(msg);
11449 }
11450 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11451 if (list != null) {
11452 int N = list.size();
11453 int i;
11454 for (i=0; i<N; i++) {
11455 if (intent.filterEquals(list.get(i))) {
11456 list.remove(i);
11457 break;
11458 }
11459 }
11460 }
11461 }
11462 }
11463
11464 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11465 String resultData, Bundle resultExtras, boolean resultAbort,
11466 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011467 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11468 if (r == null) {
11469 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011470 return false;
11471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011472
Christopher Tatef46723b2012-01-26 14:19:24 -080011473 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11474 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011475 }
11476
11477 public void finishReceiver(IBinder who, int resultCode, String resultData,
11478 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011479 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011480
11481 // Refuse possible leaked file descriptors
11482 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11483 throw new IllegalArgumentException("File descriptors passed in Bundle");
11484 }
11485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011487 try {
11488 boolean doNext = false;
11489 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490
Christopher Tatef46723b2012-01-26 14:19:24 -080011491 synchronized(this) {
11492 r = broadcastRecordForReceiverLocked(who);
11493 if (r != null) {
11494 doNext = r.queue.finishReceiverLocked(r, resultCode,
11495 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011498
Christopher Tatef46723b2012-01-26 14:19:24 -080011499 if (doNext) {
11500 r.queue.processNextBroadcast(false);
11501 }
11502 trimApplications();
11503 } finally {
11504 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 // =========================================================
11509 // INSTRUMENTATION
11510 // =========================================================
11511
11512 public boolean startInstrumentation(ComponentName className,
11513 String profileFile, int flags, Bundle arguments,
11514 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011515 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 // Refuse possible leaked file descriptors
11517 if (arguments != null && arguments.hasFileDescriptors()) {
11518 throw new IllegalArgumentException("File descriptors passed in Bundle");
11519 }
11520
11521 synchronized(this) {
11522 InstrumentationInfo ii = null;
11523 ApplicationInfo ai = null;
11524 try {
11525 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011526 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011528 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011529 } catch (PackageManager.NameNotFoundException e) {
11530 }
11531 if (ii == null) {
11532 reportStartInstrumentationFailure(watcher, className,
11533 "Unable to find instrumentation info for: " + className);
11534 return false;
11535 }
11536 if (ai == null) {
11537 reportStartInstrumentationFailure(watcher, className,
11538 "Unable to find instrumentation target package: " + ii.targetPackage);
11539 return false;
11540 }
11541
11542 int match = mContext.getPackageManager().checkSignatures(
11543 ii.targetPackage, ii.packageName);
11544 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11545 String msg = "Permission Denial: starting instrumentation "
11546 + className + " from pid="
11547 + Binder.getCallingPid()
11548 + ", uid=" + Binder.getCallingPid()
11549 + " not allowed because package " + ii.packageName
11550 + " does not have a signature matching the target "
11551 + ii.targetPackage;
11552 reportStartInstrumentationFailure(watcher, className, msg);
11553 throw new SecurityException(msg);
11554 }
11555
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011556 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011558 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011559 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011560 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011561 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011562 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 app.instrumentationProfileFile = profileFile;
11564 app.instrumentationArguments = arguments;
11565 app.instrumentationWatcher = watcher;
11566 app.instrumentationResultClass = className;
11567 Binder.restoreCallingIdentity(origId);
11568 }
11569
11570 return true;
11571 }
11572
11573 /**
11574 * Report errors that occur while attempting to start Instrumentation. Always writes the
11575 * error to the logs, but if somebody is watching, send the report there too. This enables
11576 * the "am" command to report errors with more information.
11577 *
11578 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11579 * @param cn The component name of the instrumentation.
11580 * @param report The error report.
11581 */
11582 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11583 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011584 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585 try {
11586 if (watcher != null) {
11587 Bundle results = new Bundle();
11588 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11589 results.putString("Error", report);
11590 watcher.instrumentationStatus(cn, -1, results);
11591 }
11592 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011593 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 }
11595 }
11596
11597 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11598 if (app.instrumentationWatcher != null) {
11599 try {
11600 // NOTE: IInstrumentationWatcher *must* be oneway here
11601 app.instrumentationWatcher.instrumentationFinished(
11602 app.instrumentationClass,
11603 resultCode,
11604 results);
11605 } catch (RemoteException e) {
11606 }
11607 }
11608 app.instrumentationWatcher = null;
11609 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011610 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 app.instrumentationProfileFile = null;
11612 app.instrumentationArguments = null;
11613
Amith Yamasani483f3b02012-03-13 16:08:00 -070011614 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 }
11616
11617 public void finishInstrumentation(IApplicationThread target,
11618 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011619 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 // Refuse possible leaked file descriptors
11621 if (results != null && results.hasFileDescriptors()) {
11622 throw new IllegalArgumentException("File descriptors passed in Intent");
11623 }
11624
11625 synchronized(this) {
11626 ProcessRecord app = getRecordForAppLocked(target);
11627 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011628 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 return;
11630 }
11631 final long origId = Binder.clearCallingIdentity();
11632 finishInstrumentationLocked(app, resultCode, results);
11633 Binder.restoreCallingIdentity(origId);
11634 }
11635 }
11636
11637 // =========================================================
11638 // CONFIGURATION
11639 // =========================================================
11640
11641 public ConfigurationInfo getDeviceConfigurationInfo() {
11642 ConfigurationInfo config = new ConfigurationInfo();
11643 synchronized (this) {
11644 config.reqTouchScreen = mConfiguration.touchscreen;
11645 config.reqKeyboardType = mConfiguration.keyboard;
11646 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011647 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11648 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011649 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11650 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011651 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11652 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11654 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011655 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011656 }
11657 return config;
11658 }
11659
11660 public Configuration getConfiguration() {
11661 Configuration ci;
11662 synchronized(this) {
11663 ci = new Configuration(mConfiguration);
11664 }
11665 return ci;
11666 }
11667
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011668 public void updatePersistentConfiguration(Configuration values) {
11669 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11670 "updateConfiguration()");
11671 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11672 "updateConfiguration()");
11673 if (values == null) {
11674 throw new NullPointerException("Configuration must not be null");
11675 }
11676
11677 synchronized(this) {
11678 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011679 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011680 Binder.restoreCallingIdentity(origId);
11681 }
11682 }
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 public void updateConfiguration(Configuration values) {
11685 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11686 "updateConfiguration()");
11687
11688 synchronized(this) {
11689 if (values == null && mWindowManager != null) {
11690 // sentinel: fetch the current configuration from the window manager
11691 values = mWindowManager.computeNewConfiguration();
11692 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011693
11694 if (mWindowManager != null) {
11695 mProcessList.applyDisplaySize(mWindowManager);
11696 }
11697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011699 if (values != null) {
11700 Settings.System.clearConfiguration(values);
11701 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011702 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011703 Binder.restoreCallingIdentity(origId);
11704 }
11705 }
11706
11707 /**
11708 * Do either or both things: (1) change the current configuration, and (2)
11709 * make sure the given activity is running with the (now) current
11710 * configuration. Returns true if the activity has been left running, or
11711 * false if <var>starting</var> is being destroyed to match the new
11712 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011713 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011715 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011716 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011717 // do nothing if we are headless
11718 if (mHeadless) return true;
11719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011720 int changes = 0;
11721
11722 boolean kept = true;
11723
11724 if (values != null) {
11725 Configuration newConfig = new Configuration(mConfiguration);
11726 changes = newConfig.updateFrom(values);
11727 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011728 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 }
11731
Doug Zongker2bec3d42009-12-04 12:52:44 -080011732 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733
Dianne Hackborn813075a62011-11-14 17:45:19 -080011734 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735 saveLocaleLocked(values.locale,
11736 !values.locale.equals(mConfiguration.locale),
11737 values.userSetLocale);
11738 }
11739
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011740 mConfigurationSeq++;
11741 if (mConfigurationSeq <= 0) {
11742 mConfigurationSeq = 1;
11743 }
11744 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011746 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011747
11748 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070011749
11750 // TODO: If our config changes, should we auto dismiss any currently
11751 // showing dialogs?
11752 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011753
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011754 AttributeCache ac = AttributeCache.instance();
11755 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080011756 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011758
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011759 // Make sure all resources in our process are updated
11760 // right now, so that anyone who is going to retrieve
11761 // resource values after we return will be sure to get
11762 // the new ones. This is especially important during
11763 // boot, where the first config change needs to guarantee
11764 // all resources have that config before following boot
11765 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080011766 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011767
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011768 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011769 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011770 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011771 mHandler.sendMessage(msg);
11772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011774 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11775 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 try {
11777 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011778 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011779 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011780 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011781 }
11782 } catch (Exception e) {
11783 }
11784 }
11785 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011786 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11787 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011789 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011790 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11791 broadcastIntentLocked(null, null,
11792 new Intent(Intent.ACTION_LOCALE_CHANGED),
11793 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011794 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 }
11797 }
11798
11799 if (changes != 0 && starting == null) {
11800 // If the configuration changed, and the caller is not already
11801 // in the process of starting an activity, then find the top
11802 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011803 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 }
11805
11806 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011807 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011808 // And we need to make sure at this point that all other activities
11809 // are made visible with the correct configuration.
11810 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 }
11812
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011813 if (values != null && mWindowManager != null) {
11814 mWindowManager.setNewConfiguration(mConfiguration);
11815 }
11816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 return kept;
11818 }
Joe Onorato54a4a412011-11-02 20:50:08 -070011819
11820 /**
11821 * Decide based on the configuration whether we should shouw the ANR,
11822 * crash, etc dialogs. The idea is that if there is no affordnace to
11823 * press the on-screen buttons, we shouldn't show the dialog.
11824 *
11825 * A thought: SystemUI might also want to get told about this, the Power
11826 * dialog / global actions also might want different behaviors.
11827 */
11828 private static final boolean shouldShowDialogs(Configuration config) {
11829 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
11830 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
11831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832
11833 /**
11834 * Save the locale. You must be inside a synchronized (this) block.
11835 */
11836 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11837 if(isDiff) {
11838 SystemProperties.set("user.language", l.getLanguage());
11839 SystemProperties.set("user.region", l.getCountry());
11840 }
11841
11842 if(isPersist) {
11843 SystemProperties.set("persist.sys.language", l.getLanguage());
11844 SystemProperties.set("persist.sys.country", l.getCountry());
11845 SystemProperties.set("persist.sys.localevar", l.getVariant());
11846 }
11847 }
11848
Adam Powelldd8fab22012-03-22 17:47:27 -070011849 @Override
11850 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
11851 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011852 return srec != null && srec.task.affinity != null &&
11853 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070011854 }
11855
11856 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
11857 Intent resultData) {
11858 ComponentName dest = destIntent.getComponent();
11859
11860 synchronized (this) {
11861 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011862 if (srec == null) {
11863 return false;
11864 }
Adam Powelldd8fab22012-03-22 17:47:27 -070011865 ArrayList<ActivityRecord> history = srec.stack.mHistory;
11866 final int start = history.indexOf(srec);
11867 if (start < 0) {
11868 // Current activity is not in history stack; do nothing.
11869 return false;
11870 }
11871 int finishTo = start - 1;
11872 ActivityRecord parent = null;
11873 boolean foundParentInTask = false;
11874 if (dest != null) {
11875 TaskRecord tr = srec.task;
11876 for (int i = start - 1; i >= 0; i--) {
11877 ActivityRecord r = history.get(i);
11878 if (tr != r.task) {
11879 // Couldn't find parent in the same task; stop at the one above this.
11880 // (Root of current task; in-app "home" behavior)
11881 // Always at least finish the current activity.
11882 finishTo = Math.min(start - 1, i + 1);
11883 parent = history.get(finishTo);
11884 break;
11885 } else if (r.info.packageName.equals(dest.getPackageName()) &&
11886 r.info.name.equals(dest.getClassName())) {
11887 finishTo = i;
11888 parent = r;
11889 foundParentInTask = true;
11890 break;
11891 }
11892 }
11893 }
11894
11895 if (mController != null) {
11896 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
11897 if (next != null) {
11898 // ask watcher if this is allowed
11899 boolean resumeOK = true;
11900 try {
11901 resumeOK = mController.activityResuming(next.packageName);
11902 } catch (RemoteException e) {
11903 mController = null;
11904 }
11905
11906 if (!resumeOK) {
11907 return false;
11908 }
11909 }
11910 }
11911 final long origId = Binder.clearCallingIdentity();
11912 for (int i = start; i > finishTo; i--) {
11913 ActivityRecord r = history.get(i);
11914 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
11915 "navigate-up");
11916 // Only return the supplied result for the first activity finished
11917 resultCode = Activity.RESULT_CANCELED;
11918 resultData = null;
11919 }
11920
11921 if (parent != null && foundParentInTask) {
11922 final int parentLaunchMode = parent.info.launchMode;
11923 final int destIntentFlags = destIntent.getFlags();
11924 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
11925 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
11926 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
11927 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070011928 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070011929 } else {
11930 try {
11931 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011932 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070011933 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
11934 null, aInfo, parent.appToken, null,
11935 0, -1, parent.launchedFromUid, 0, null, true, null);
11936 foundParentInTask = res == ActivityManager.START_SUCCESS;
11937 } catch (RemoteException e) {
11938 foundParentInTask = false;
11939 }
11940 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
11941 resultData, "navigate-up");
11942 }
11943 }
11944 Binder.restoreCallingIdentity(origId);
11945 return foundParentInTask;
11946 }
11947 }
11948
Dianne Hackborn5320eb82012-05-18 12:05:04 -070011949 public int getLaunchedFromUid(IBinder activityToken) {
11950 ActivityRecord srec = ActivityRecord.forToken(activityToken);
11951 if (srec == null) {
11952 return -1;
11953 }
11954 return srec.launchedFromUid;
11955 }
11956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 // =========================================================
11958 // LIFETIME MANAGEMENT
11959 // =========================================================
11960
Christopher Tatef46723b2012-01-26 14:19:24 -080011961 // Returns which broadcast queue the app is the current [or imminent] receiver
11962 // on, or 'null' if the app is not an active broadcast recipient.
11963 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
11964 BroadcastRecord r = app.curReceiver;
11965 if (r != null) {
11966 return r.queue;
11967 }
11968
11969 // It's not the current receiver, but it might be starting up to become one
11970 synchronized (this) {
11971 for (BroadcastQueue queue : mBroadcastQueues) {
11972 r = queue.mPendingBroadcast;
11973 if (r != null && r.curApp == app) {
11974 // found it; report which queue it's in
11975 return queue;
11976 }
11977 }
11978 }
11979
11980 return null;
11981 }
11982
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011983 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070011984 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011986 // This adjustment has already been computed. If we are calling
11987 // from the top, we may have already computed our adjustment with
11988 // an earlier hidden adjustment that isn't really for us... if
11989 // so, use the new hidden adjustment.
11990 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070011991 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
11992 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011993 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011994 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995 }
11996
11997 if (app.thread == null) {
11998 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080011999 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012000 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 }
12002
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012003 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12004 app.adjSource = null;
12005 app.adjTarget = null;
12006 app.empty = false;
12007 app.hidden = false;
12008
12009 final int activitiesSize = app.activities.size();
12010
Dianne Hackborn7d608422011-08-07 16:24:18 -070012011 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012012 // The max adjustment doesn't allow this app to be anything
12013 // below foreground, so it is not worth doing work for it.
12014 app.adjType = "fixed";
12015 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012016 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012017 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012018 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012019 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012020 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012021 // System process can do UI, and when they do we want to have
12022 // them trim their memory after the user leaves the UI. To
12023 // facilitate this, here we need to determine whether or not it
12024 // is currently showing UI.
12025 app.systemNoUi = true;
12026 if (app == TOP_APP) {
12027 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012028 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012029 } else if (activitiesSize > 0) {
12030 for (int j = 0; j < activitiesSize; j++) {
12031 final ActivityRecord r = app.activities.get(j);
12032 if (r.visible) {
12033 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012034 }
12035 if (r.app == app) {
12036 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012037 }
12038 }
12039 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012040 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012041 }
12042
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012043 app.keeping = false;
12044 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012045 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046
The Android Open Source Project4df24232009-03-05 14:34:35 -080012047 // Determine the importance of the process, starting with most
12048 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012050 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012051 boolean foregroundActivities = false;
12052 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012053 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012054 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012056 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012057 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012058 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012059 foregroundActivities = true;
12060 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012061 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012062 } else if (app.instrumentationClass != null) {
12063 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012064 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012065 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012066 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012067 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012068 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012070 // counts as being in the foreground for OOM killer purposes.
12071 // It's placed in a sched group based on the nature of the
12072 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012073 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012074 schedGroup = (queue == mFgBroadcastQueue)
12075 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012076 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 } else if (app.executingServices.size() > 0) {
12078 // An app that is currently executing a service callback also
12079 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012080 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012081 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012082 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012083 } else {
12084 // Assume process is hidden (has activities); we will correct
12085 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012086 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012087 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012088 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012089 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012090 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012091
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012092 boolean hasStoppingActivities = false;
12093
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012094 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012095 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012096 for (int j = 0; j < activitiesSize; j++) {
12097 final ActivityRecord r = app.activities.get(j);
12098 if (r.visible) {
12099 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012100 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12101 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012102 app.adjType = "visible";
12103 }
12104 schedGroup = Process.THREAD_GROUP_DEFAULT;
12105 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012106 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012107 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012108 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012109 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012110 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12111 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012112 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012113 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012114 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012115 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012116 } else if (r.state == ActivityState.STOPPING) {
12117 // We will apply the actual adjustment later, because
12118 // we want to allow this process to immediately go through
12119 // any memory trimming that is in effect.
12120 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012121 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012122 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012123 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012124 if (r.app == app) {
12125 app.hasActivities = true;
12126 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012127 }
12128 }
12129
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012130 if (adj == hiddenAdj && !app.hasActivities) {
12131 // Whoops, this process is completely empty as far as we know
12132 // at this point.
12133 adj = emptyAdj;
12134 app.empty = true;
12135 app.adjType = "bg-empty";
12136 }
12137
Dianne Hackborn7d608422011-08-07 16:24:18 -070012138 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012139 if (app.foregroundServices) {
12140 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012141 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012142 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012143 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012144 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012145 } else if (app.forcingToForeground != null) {
12146 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012147 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012148 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012149 app.adjType = "force-foreground";
12150 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012151 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012152 }
12153 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012154
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012155 if (app.foregroundServices) {
12156 interesting = true;
12157 }
12158
Dianne Hackborn7d608422011-08-07 16:24:18 -070012159 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012160 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012161 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012162 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012163 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012164 app.adjType = "heavy";
12165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166
Dianne Hackborn7d608422011-08-07 16:24:18 -070012167 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012168 // This process is hosting what we currently consider to be the
12169 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012170 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012171 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012172 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012173 app.adjType = "home";
12174 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012175
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012176 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12177 && app.activities.size() > 0) {
12178 // This was the previous process that showed UI to the user.
12179 // We want to try to keep it around more aggressively, to give
12180 // a good experience around switching between two apps.
12181 adj = ProcessList.PREVIOUS_APP_ADJ;
12182 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12183 app.hidden = false;
12184 app.adjType = "previous";
12185 }
12186
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012187 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12188 + " reason=" + app.adjType);
12189
The Android Open Source Project4df24232009-03-05 14:34:35 -080012190 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 // there are applications dependent on our services or providers, but
12192 // this gives us a baseline and makes sure we don't get into an
12193 // infinite recursion.
12194 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012195 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012196
Christopher Tate6fa95972009-06-05 18:43:55 -070012197 if (mBackupTarget != null && app == mBackupTarget.app) {
12198 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012199 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012200 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012201 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012202 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012203 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012204 }
12205 }
12206
Dianne Hackborn7d608422011-08-07 16:24:18 -070012207 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012208 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012209 final long now = SystemClock.uptimeMillis();
12210 // This process is more important if the top activity is
12211 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012212 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012213 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012214 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012215 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012216 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012217 // If this process has shown some UI, let it immediately
12218 // go to the LRU list because it may be pretty heavy with
12219 // UI stuff. We'll tag it with a label just to help
12220 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012221 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012222 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012223 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012224 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012225 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012226 // This service has seen some activity within
12227 // recent memory, so we will keep its process ahead
12228 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012229 if (adj > ProcessList.SERVICE_ADJ) {
12230 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012231 app.adjType = "started-services";
12232 app.hidden = false;
12233 }
12234 }
12235 // If we have let the service slide into the background
12236 // state, still have some text describing what it is doing
12237 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012238 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012239 app.adjType = "started-bg-services";
12240 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012241 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012242 // Don't kill this process because it is doing work; it
12243 // has said it is doing work.
12244 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012245 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012246 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012247 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012248 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012250 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012251 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012252 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012253 // XXX should compute this based on the max of
12254 // all connected clients.
12255 ConnectionRecord cr = clist.get(i);
12256 if (cr.binding.client == app) {
12257 // Binding to ourself is not interesting.
12258 continue;
12259 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012260 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012261 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012262 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012263 int myHiddenAdj = hiddenAdj;
12264 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012265 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012266 myHiddenAdj = client.hiddenAdj;
12267 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012268 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012269 }
12270 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012271 int myEmptyAdj = emptyAdj;
12272 if (myEmptyAdj > client.emptyAdj) {
12273 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12274 myEmptyAdj = client.emptyAdj;
12275 } else {
12276 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12277 }
12278 }
12279 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12280 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012281 String adjType = null;
12282 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12283 // Not doing bind OOM management, so treat
12284 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012285 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012286 // If this process has shown some UI, let it immediately
12287 // go to the LRU list because it may be pretty heavy with
12288 // UI stuff. We'll tag it with a label just to help
12289 // debug and understand what is going on.
12290 if (adj > clientAdj) {
12291 adjType = "bound-bg-ui-services";
12292 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012293 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012294 clientAdj = adj;
12295 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012296 if (now >= (s.lastActivity
12297 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012298 // This service has not seen activity within
12299 // recent memory, so allow it to drop to the
12300 // LRU list if there is no other reason to keep
12301 // it around. We'll also tag it with a label just
12302 // to help debug and undertand what is going on.
12303 if (adj > clientAdj) {
12304 adjType = "bound-bg-services";
12305 }
12306 clientAdj = adj;
12307 }
12308 }
12309 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012310 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012311 // If this process has recently shown UI, and
12312 // the process that is binding to it is less
12313 // important than being visible, then we don't
12314 // care about the binding as much as we care
12315 // about letting this process get into the LRU
12316 // list to be killed and restarted if needed for
12317 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012318 if (app.hasShownUi && app != mHomeProcess
12319 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012320 adjType = "bound-bg-ui-services";
12321 } else {
12322 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12323 |Context.BIND_IMPORTANT)) != 0) {
12324 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012325 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12326 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12327 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12328 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12329 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012330 adj = clientAdj;
12331 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012332 app.pendingUiClean = true;
12333 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12334 adj = ProcessList.VISIBLE_APP_ADJ;
12335 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012336 }
12337 if (!client.hidden) {
12338 app.hidden = false;
12339 }
12340 if (client.keeping) {
12341 app.keeping = true;
12342 }
12343 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012344 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012345 }
12346 if (adjType != null) {
12347 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012348 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12349 .REASON_SERVICE_IN_USE;
12350 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012351 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012352 app.adjTarget = s.name;
12353 }
12354 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12355 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12356 schedGroup = Process.THREAD_GROUP_DEFAULT;
12357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012358 }
12359 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012360 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12361 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012362 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012363 (a.visible || a.state == ActivityState.RESUMED
12364 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012365 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012366 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12367 schedGroup = Process.THREAD_GROUP_DEFAULT;
12368 }
12369 app.hidden = false;
12370 app.adjType = "service";
12371 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12372 .REASON_SERVICE_IN_USE;
12373 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012374 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012375 app.adjTarget = s.name;
12376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012378 }
12379 }
12380 }
12381 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012382
Dianne Hackborn287952c2010-09-22 22:34:31 -070012383 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012384 // would like to avoid killing it unless it would prevent the current
12385 // application from running. By default we put the process in
12386 // with the rest of the background processes; as we scan through
12387 // its services we may bump it up from there.
12388 if (adj > hiddenAdj) {
12389 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012390 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012391 app.adjType = "bg-services";
12392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012393 }
12394
Dianne Hackborn7d608422011-08-07 16:24:18 -070012395 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012396 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012397 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012398 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012399 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012400 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012401 for (int i = cpr.connections.size()-1;
12402 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12403 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12404 i--) {
12405 ContentProviderConnection conn = cpr.connections.get(i);
12406 ProcessRecord client = conn.client;
12407 if (client == app) {
12408 // Being our own client is not interesting.
12409 continue;
12410 }
12411 int myHiddenAdj = hiddenAdj;
12412 if (myHiddenAdj > client.hiddenAdj) {
12413 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12414 myHiddenAdj = client.hiddenAdj;
12415 } else {
12416 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012417 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012418 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012419 int myEmptyAdj = emptyAdj;
12420 if (myEmptyAdj > client.emptyAdj) {
12421 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12422 myEmptyAdj = client.emptyAdj;
12423 } else {
12424 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12425 }
12426 }
12427 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12428 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012429 if (adj > clientAdj) {
12430 if (app.hasShownUi && app != mHomeProcess
12431 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12432 app.adjType = "bg-ui-provider";
12433 } else {
12434 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12435 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12436 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012438 if (!client.hidden) {
12439 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012440 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012441 if (client.keeping) {
12442 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012443 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012444 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12445 .REASON_PROVIDER_IN_USE;
12446 app.adjSource = client;
12447 app.adjSourceOom = clientAdj;
12448 app.adjTarget = cpr.name;
12449 }
12450 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12451 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012452 }
12453 }
12454 // If the provider has external (non-framework) process
12455 // dependencies, ensure that its adjustment is at least
12456 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012457 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012458 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12459 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012460 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012461 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012462 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012463 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012464 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012465 }
12466 }
12467 }
12468 }
12469
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012470 if (adj == ProcessList.SERVICE_ADJ) {
12471 if (doingAll) {
12472 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12473 mNewNumServiceProcs++;
12474 }
12475 if (app.serviceb) {
12476 adj = ProcessList.SERVICE_B_ADJ;
12477 }
12478 } else {
12479 app.serviceb = false;
12480 }
12481
12482 app.nonStoppingAdj = adj;
12483
12484 if (hasStoppingActivities) {
12485 // Only upgrade adjustment.
12486 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12487 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12488 app.adjType = "stopping";
12489 }
12490 }
12491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 app.curRawAdj = adj;
12493
Joe Onorato8a9b2202010-02-26 18:56:32 -080012494 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012495 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12496 if (adj > app.maxAdj) {
12497 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012498 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012499 schedGroup = Process.THREAD_GROUP_DEFAULT;
12500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012502 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012503 app.keeping = true;
12504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012505
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012506 if (app.hasAboveClient) {
12507 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12508 // then we need to drop its adjustment to be lower than the service's
12509 // in order to honor the request. We want to drop it by one adjustment
12510 // level... but there is special meaning applied to various levels so
12511 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012512 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012513 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012514 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12515 adj = ProcessList.VISIBLE_APP_ADJ;
12516 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12517 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12518 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12519 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012520 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012521 adj++;
12522 }
12523 }
12524
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012525 int importance = app.memImportance;
12526 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12527 app.curAdj = adj;
12528 app.curSchedGroup = schedGroup;
12529 if (!interesting) {
12530 // For this reporting, if there is not something explicitly
12531 // interesting in this process then we will push it to the
12532 // background importance.
12533 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12534 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12535 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12536 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12537 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12538 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12539 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12540 } else if (adj >= ProcessList.SERVICE_ADJ) {
12541 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12542 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12543 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12544 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12545 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12546 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12547 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12548 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12549 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12550 } else {
12551 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12552 }
12553 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012554
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012555 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12556 if (foregroundActivities != app.foregroundActivities) {
12557 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12558 }
12559 if (changes != 0) {
12560 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12561 app.memImportance = importance;
12562 app.foregroundActivities = foregroundActivities;
12563 int i = mPendingProcessChanges.size()-1;
12564 ProcessChangeItem item = null;
12565 while (i >= 0) {
12566 item = mPendingProcessChanges.get(i);
12567 if (item.pid == app.pid) {
12568 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12569 break;
12570 }
12571 i--;
12572 }
12573 if (i < 0) {
12574 // No existing item in pending changes; need a new one.
12575 final int NA = mAvailProcessChanges.size();
12576 if (NA > 0) {
12577 item = mAvailProcessChanges.remove(NA-1);
12578 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12579 } else {
12580 item = new ProcessChangeItem();
12581 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12582 }
12583 item.changes = 0;
12584 item.pid = app.pid;
12585 item.uid = app.info.uid;
12586 if (mPendingProcessChanges.size() == 0) {
12587 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12588 "*** Enqueueing dispatch processes changed!");
12589 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12590 }
12591 mPendingProcessChanges.add(item);
12592 }
12593 item.changes |= changes;
12594 item.importance = importance;
12595 item.foregroundActivities = foregroundActivities;
12596 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12597 + Integer.toHexString(System.identityHashCode(item))
12598 + " " + app.toShortString() + ": changes=" + item.changes
12599 + " importance=" + item.importance
12600 + " foreground=" + item.foregroundActivities
12601 + " type=" + app.adjType + " source=" + app.adjSource
12602 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012603 }
12604
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012605 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012606 }
12607
12608 /**
12609 * Ask a given process to GC right now.
12610 */
12611 final void performAppGcLocked(ProcessRecord app) {
12612 try {
12613 app.lastRequestedGc = SystemClock.uptimeMillis();
12614 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012615 if (app.reportLowMemory) {
12616 app.reportLowMemory = false;
12617 app.thread.scheduleLowMemory();
12618 } else {
12619 app.thread.processInBackground();
12620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012621 }
12622 } catch (Exception e) {
12623 // whatever.
12624 }
12625 }
12626
12627 /**
12628 * Returns true if things are idle enough to perform GCs.
12629 */
Josh Bartel7f208742010-02-25 11:01:44 -060012630 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012631 boolean processingBroadcasts = false;
12632 for (BroadcastQueue q : mBroadcastQueues) {
12633 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12634 processingBroadcasts = true;
12635 }
12636 }
12637 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012638 && (mSleeping || (mMainStack.mResumedActivity != null &&
12639 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012640 }
12641
12642 /**
12643 * Perform GCs on all processes that are waiting for it, but only
12644 * if things are idle.
12645 */
12646 final void performAppGcsLocked() {
12647 final int N = mProcessesToGc.size();
12648 if (N <= 0) {
12649 return;
12650 }
Josh Bartel7f208742010-02-25 11:01:44 -060012651 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 while (mProcessesToGc.size() > 0) {
12653 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012654 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012655 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12656 <= SystemClock.uptimeMillis()) {
12657 // To avoid spamming the system, we will GC processes one
12658 // at a time, waiting a few seconds between each.
12659 performAppGcLocked(proc);
12660 scheduleAppGcsLocked();
12661 return;
12662 } else {
12663 // It hasn't been long enough since we last GCed this
12664 // process... put it in the list to wait for its time.
12665 addProcessToGcListLocked(proc);
12666 break;
12667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012668 }
12669 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012670
12671 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012672 }
12673 }
12674
12675 /**
12676 * If all looks good, perform GCs on all processes waiting for them.
12677 */
12678 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012679 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 performAppGcsLocked();
12681 return;
12682 }
12683 // Still not idle, wait some more.
12684 scheduleAppGcsLocked();
12685 }
12686
12687 /**
12688 * Schedule the execution of all pending app GCs.
12689 */
12690 final void scheduleAppGcsLocked() {
12691 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012692
12693 if (mProcessesToGc.size() > 0) {
12694 // Schedule a GC for the time to the next process.
12695 ProcessRecord proc = mProcessesToGc.get(0);
12696 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12697
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012698 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012699 long now = SystemClock.uptimeMillis();
12700 if (when < (now+GC_TIMEOUT)) {
12701 when = now + GC_TIMEOUT;
12702 }
12703 mHandler.sendMessageAtTime(msg, when);
12704 }
12705 }
12706
12707 /**
12708 * Add a process to the array of processes waiting to be GCed. Keeps the
12709 * list in sorted order by the last GC time. The process can't already be
12710 * on the list.
12711 */
12712 final void addProcessToGcListLocked(ProcessRecord proc) {
12713 boolean added = false;
12714 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12715 if (mProcessesToGc.get(i).lastRequestedGc <
12716 proc.lastRequestedGc) {
12717 added = true;
12718 mProcessesToGc.add(i+1, proc);
12719 break;
12720 }
12721 }
12722 if (!added) {
12723 mProcessesToGc.add(0, proc);
12724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 }
12726
12727 /**
12728 * Set up to ask a process to GC itself. This will either do it
12729 * immediately, or put it on the list of processes to gc the next
12730 * time things are idle.
12731 */
12732 final void scheduleAppGcLocked(ProcessRecord app) {
12733 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012734 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012735 return;
12736 }
12737 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012738 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 scheduleAppGcsLocked();
12740 }
12741 }
12742
Dianne Hackborn287952c2010-09-22 22:34:31 -070012743 final void checkExcessivePowerUsageLocked(boolean doKills) {
12744 updateCpuStatsNow();
12745
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012746 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012747 boolean doWakeKills = doKills;
12748 boolean doCpuKills = doKills;
12749 if (mLastPowerCheckRealtime == 0) {
12750 doWakeKills = false;
12751 }
12752 if (mLastPowerCheckUptime == 0) {
12753 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012754 }
12755 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012756 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012757 }
12758 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012759 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12760 final long curUptime = SystemClock.uptimeMillis();
12761 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12762 mLastPowerCheckRealtime = curRealtime;
12763 mLastPowerCheckUptime = curUptime;
12764 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12765 doWakeKills = false;
12766 }
12767 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12768 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012769 }
12770 int i = mLruProcesses.size();
12771 while (i > 0) {
12772 i--;
12773 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012774 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012775 long wtime;
12776 synchronized (stats) {
12777 wtime = stats.getProcessWakeTime(app.info.uid,
12778 app.pid, curRealtime);
12779 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012780 long wtimeUsed = wtime - app.lastWakeTime;
12781 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12782 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012783 StringBuilder sb = new StringBuilder(128);
12784 sb.append("Wake for ");
12785 app.toShortString(sb);
12786 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012787 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012788 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012789 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012790 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012791 sb.append((wtimeUsed*100)/realtimeSince);
12792 sb.append("%)");
12793 Slog.i(TAG, sb.toString());
12794 sb.setLength(0);
12795 sb.append("CPU for ");
12796 app.toShortString(sb);
12797 sb.append(": over ");
12798 TimeUtils.formatDuration(uptimeSince, sb);
12799 sb.append(" used ");
12800 TimeUtils.formatDuration(cputimeUsed, sb);
12801 sb.append(" (");
12802 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012803 sb.append("%)");
12804 Slog.i(TAG, sb.toString());
12805 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012806 // If a process has held a wake lock for more
12807 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012808 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012809 if (doWakeKills && realtimeSince > 0
12810 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12811 synchronized (stats) {
12812 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12813 realtimeSince, wtimeUsed);
12814 }
12815 Slog.w(TAG, "Excessive wake lock in " + app.processName
12816 + " (pid " + app.pid + "): held " + wtimeUsed
12817 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012818 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12819 app.processName, app.setAdj, "excessive wake lock");
12820 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012821 } else if (doCpuKills && uptimeSince > 0
12822 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12823 synchronized (stats) {
12824 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12825 uptimeSince, cputimeUsed);
12826 }
12827 Slog.w(TAG, "Excessive CPU in " + app.processName
12828 + " (pid " + app.pid + "): used " + cputimeUsed
12829 + " during " + uptimeSince);
12830 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12831 app.processName, app.setAdj, "excessive cpu");
12832 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012833 } else {
12834 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012835 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012836 }
12837 }
12838 }
12839 }
12840
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012841 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
12842 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012843 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012844 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012845
12846 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012847 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012848 }
12849
Dianne Hackborn287952c2010-09-22 22:34:31 -070012850 final boolean wasKeeping = app.keeping;
12851
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012852 boolean success = true;
12853
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012854 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855
Jeff Brown10e89712011-07-08 18:52:57 -070012856 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070012857 if (wasKeeping && !app.keeping) {
12858 // This app is no longer something we want to keep. Note
12859 // its current wake lock time to later know to kill it if
12860 // it is not behaving well.
12861 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12862 synchronized (stats) {
12863 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12864 app.pid, SystemClock.elapsedRealtime());
12865 }
12866 app.lastCpuTime = app.curCpuTime;
12867 }
12868
12869 app.setRawAdj = app.curRawAdj;
12870 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012871
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012872 if (app.curAdj != app.setAdj) {
12873 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080012874 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012875 TAG, "Set " + app.pid + " " + app.processName +
12876 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012877 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070012878 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012879 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012880 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070012881 }
12882 }
12883 if (app.setSchedGroup != app.curSchedGroup) {
12884 app.setSchedGroup = app.curSchedGroup;
12885 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
12886 "Setting process group of " + app.processName
12887 + " to " + app.curSchedGroup);
12888 if (app.waitingToKill != null &&
12889 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
12890 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
12891 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12892 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070012893 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070012894 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012895 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070012896 } else {
12897 if (true) {
12898 long oldId = Binder.clearCallingIdentity();
12899 try {
12900 Process.setProcessGroup(app.pid, app.curSchedGroup);
12901 } catch (Exception e) {
12902 Slog.w(TAG, "Failed setting process group of " + app.pid
12903 + " to " + app.curSchedGroup);
12904 e.printStackTrace();
12905 } finally {
12906 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012907 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012908 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070012909 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012910 try {
Jeff Brown10e89712011-07-08 18:52:57 -070012911 app.thread.setSchedulingGroup(app.curSchedGroup);
12912 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012913 }
12914 }
12915 }
12916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012917 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012918 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012919 }
12920
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012921 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012922 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080012924 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012925 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012926 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
12928 }
12929 return resumedActivity;
12930 }
12931
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012932 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012933 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012934 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12935 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012936 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12937 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012938
12939 mAdjSeq++;
12940
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012941 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
12942 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012943 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12944 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012945 if (nowHidden != wasHidden) {
12946 // Changed to/from hidden state, so apps after it in the LRU
12947 // list may also be changed.
12948 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012950 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012951 }
12952
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012953 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012954 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012955 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12956
12957 if (false) {
12958 RuntimeException e = new RuntimeException();
12959 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012960 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 }
12962
12963 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012964 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012966 // Let's determine how many processes we have running vs.
12967 // how many slots we have for background processes; we may want
12968 // to put multiple processes in a slot of there are enough of
12969 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012970 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
12971 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
12972 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
12973 if (emptyFactor < 1) emptyFactor = 1;
12974 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
12975 if (hiddenFactor < 1) hiddenFactor = 1;
12976 int stepHidden = 0;
12977 int stepEmpty = 0;
12978 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
12979 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070012980 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012981 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012982 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012983
12984 mNumNonHiddenProcs = 0;
12985 mNumHiddenProcs = 0;
12986
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012987 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012988 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012989 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012990 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012991 int nextHiddenAdj = curHiddenAdj+1;
12992 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
12993 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 while (i > 0) {
12995 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012996 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012997 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012998 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012999 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013000 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13001 // This process was assigned as a hidden process... step the
13002 // hidden level.
13003 mNumHiddenProcs++;
13004 if (curHiddenAdj != nextHiddenAdj) {
13005 stepHidden++;
13006 if (stepHidden >= hiddenFactor) {
13007 stepHidden = 0;
13008 curHiddenAdj = nextHiddenAdj;
13009 nextHiddenAdj += 2;
13010 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13011 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13012 }
13013 }
13014 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013015 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013016 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013017 Slog.i(TAG, "No longer want " + app.processName
13018 + " (pid " + app.pid + "): hidden #" + numHidden);
13019 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13020 app.processName, app.setAdj, "too many background");
13021 app.killedBackground = true;
13022 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013023 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013024 } else {
13025 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13026 // This process was assigned as an empty process... step the
13027 // empty level.
13028 if (curEmptyAdj != nextEmptyAdj) {
13029 stepEmpty++;
13030 if (stepEmpty >= emptyFactor) {
13031 stepEmpty = 0;
13032 curEmptyAdj = nextEmptyAdj;
13033 nextEmptyAdj += 2;
13034 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13035 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13036 }
13037 }
13038 }
13039 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13040 mNumNonHiddenProcs++;
13041 }
13042 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13043 numEmpty++;
13044 if (numEmpty > emptyProcessLimit) {
13045 Slog.i(TAG, "No longer want " + app.processName
13046 + " (pid " + app.pid + "): empty #" + numEmpty);
13047 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13048 app.processName, app.setAdj, "too many background");
13049 app.killedBackground = true;
13050 Process.killProcessQuiet(app.pid);
13051 }
13052 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013053 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013054 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013055 // If this is an isolated process, and there are no
13056 // services running in it, then the process is no longer
13057 // needed. We agressively kill these because we can by
13058 // definition not re-use the same process again, and it is
13059 // good to avoid having whatever code was running in them
13060 // left sitting around after no longer needed.
13061 Slog.i(TAG, "Isolated process " + app.processName
13062 + " (pid " + app.pid + ") no longer needed");
13063 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13064 app.processName, app.setAdj, "isolated not needed");
13065 app.killedBackground = true;
13066 Process.killProcessQuiet(app.pid);
13067 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013068 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13069 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13070 && !app.killedBackground) {
13071 numTrimming++;
13072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073 }
13074 }
13075
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013076 mNumServiceProcs = mNewNumServiceProcs;
13077
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013078 // Now determine the memory trimming level of background processes.
13079 // Unfortunately we need to start at the back of the list to do this
13080 // properly. We only do this if the number of background apps we
13081 // are managing to keep around is less than half the maximum we desire;
13082 // if we are keeping a good number around, we'll let them use whatever
13083 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013084 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13085 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13086 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013087 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013088 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013089 int minFactor = 2;
13090 if (mHomeProcess != null) minFactor++;
13091 if (mPreviousProcess != null) minFactor++;
13092 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013093 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013094 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013095 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013096 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013097 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013098 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13099 } else {
13100 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13101 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013102 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013103 for (i=0; i<N; i++) {
13104 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013105 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13106 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013107 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013108 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13109 try {
13110 app.thread.scheduleTrimMemory(curLevel);
13111 } catch (RemoteException e) {
13112 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013113 if (false) {
13114 // For now we won't do this; our memory trimming seems
13115 // to be good enough at this point that destroying
13116 // activities causes more harm than good.
13117 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13118 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013119 // Need to do this on its own message because the stack may not
13120 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013121 // For these apps we will also finish their activities
13122 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013123 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013124 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013125 }
13126 }
13127 app.trimMemoryLevel = curLevel;
13128 step++;
13129 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013130 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013131 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013132 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13133 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013134 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013135 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13136 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013137 break;
13138 }
13139 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013140 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013141 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013142 && app.thread != null) {
13143 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013144 app.thread.scheduleTrimMemory(
13145 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013146 } catch (RemoteException e) {
13147 }
13148 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013149 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013150 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013151 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013152 && app.pendingUiClean) {
13153 // If this application is now in the background and it
13154 // had done UI, then give it the special trim level to
13155 // have it free UI resources.
13156 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13157 if (app.trimMemoryLevel < level && app.thread != null) {
13158 try {
13159 app.thread.scheduleTrimMemory(level);
13160 } catch (RemoteException e) {
13161 }
13162 }
13163 app.pendingUiClean = false;
13164 }
13165 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013166 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013167 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013168 } catch (RemoteException e) {
13169 }
13170 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013171 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013172 }
13173 }
13174 } else {
13175 final int N = mLruProcesses.size();
13176 for (i=0; i<N; i++) {
13177 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013178 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013179 && app.pendingUiClean) {
13180 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13181 && app.thread != null) {
13182 try {
13183 app.thread.scheduleTrimMemory(
13184 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13185 } catch (RemoteException e) {
13186 }
13187 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013188 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013189 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013190 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013191 }
13192 }
13193
13194 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013195 // Need to do this on its own message because the stack may not
13196 // be in a consistent state at this point.
13197 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 }
13200
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013201 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 synchronized (this) {
13203 int i;
13204
13205 // First remove any unused application processes whose package
13206 // has been removed.
13207 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13208 final ProcessRecord app = mRemovedProcesses.get(i);
13209 if (app.activities.size() == 0
13210 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013211 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013212 TAG, "Exiting empty application process "
13213 + app.processName + " ("
13214 + (app.thread != null ? app.thread.asBinder() : null)
13215 + ")\n");
13216 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013217 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13218 app.processName, app.setAdj, "empty");
13219 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 } else {
13221 try {
13222 app.thread.scheduleExit();
13223 } catch (Exception e) {
13224 // Ignore exceptions.
13225 }
13226 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013227 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 mRemovedProcesses.remove(i);
13229
13230 if (app.persistent) {
13231 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013232 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013233 }
13234 }
13235 }
13236 }
13237
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013238 // Now update the oom adj for all processes.
13239 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013240 }
13241 }
13242
13243 /** This method sends the specified signal to each of the persistent apps */
13244 public void signalPersistentProcesses(int sig) throws RemoteException {
13245 if (sig != Process.SIGNAL_USR1) {
13246 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13247 }
13248
13249 synchronized (this) {
13250 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13251 != PackageManager.PERMISSION_GRANTED) {
13252 throw new SecurityException("Requires permission "
13253 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13254 }
13255
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013256 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13257 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013258 if (r.thread != null && r.persistent) {
13259 Process.sendSignal(r.pid, sig);
13260 }
13261 }
13262 }
13263 }
13264
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013265 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13266 if (proc == null || proc == mProfileProc) {
13267 proc = mProfileProc;
13268 path = mProfileFile;
13269 profileType = mProfileType;
13270 clearProfilerLocked();
13271 }
13272 if (proc == null) {
13273 return;
13274 }
13275 try {
13276 proc.thread.profilerControl(false, path, null, profileType);
13277 } catch (RemoteException e) {
13278 throw new IllegalStateException("Process disappeared");
13279 }
13280 }
13281
13282 private void clearProfilerLocked() {
13283 if (mProfileFd != null) {
13284 try {
13285 mProfileFd.close();
13286 } catch (IOException e) {
13287 }
13288 }
13289 mProfileApp = null;
13290 mProfileProc = null;
13291 mProfileFile = null;
13292 mProfileType = 0;
13293 mAutoStopProfiler = false;
13294 }
13295
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013296 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013297 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013298
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013299 try {
13300 synchronized (this) {
13301 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13302 // its own permission.
13303 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13304 != PackageManager.PERMISSION_GRANTED) {
13305 throw new SecurityException("Requires permission "
13306 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013307 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013308
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013309 if (start && fd == null) {
13310 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013311 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013312
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013313 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013314 if (process != null) {
13315 try {
13316 int pid = Integer.parseInt(process);
13317 synchronized (mPidsSelfLocked) {
13318 proc = mPidsSelfLocked.get(pid);
13319 }
13320 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013321 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013322
13323 if (proc == null) {
13324 HashMap<String, SparseArray<ProcessRecord>> all
13325 = mProcessNames.getMap();
13326 SparseArray<ProcessRecord> procs = all.get(process);
13327 if (procs != null && procs.size() > 0) {
13328 proc = procs.valueAt(0);
13329 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013330 }
13331 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013332
13333 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013334 throw new IllegalArgumentException("Unknown process: " + process);
13335 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013336
13337 if (start) {
13338 stopProfilerLocked(null, null, 0);
13339 setProfileApp(proc.info, proc.processName, path, fd, false);
13340 mProfileProc = proc;
13341 mProfileType = profileType;
13342 try {
13343 fd = fd.dup();
13344 } catch (IOException e) {
13345 fd = null;
13346 }
13347 proc.thread.profilerControl(start, path, fd, profileType);
13348 fd = null;
13349 mProfileFd = null;
13350 } else {
13351 stopProfilerLocked(proc, path, profileType);
13352 if (fd != null) {
13353 try {
13354 fd.close();
13355 } catch (IOException e) {
13356 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013357 }
13358 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013359
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013360 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013361 }
13362 } catch (RemoteException e) {
13363 throw new IllegalStateException("Process disappeared");
13364 } finally {
13365 if (fd != null) {
13366 try {
13367 fd.close();
13368 } catch (IOException e) {
13369 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013370 }
13371 }
13372 }
Andy McFadden824c5102010-07-09 16:26:57 -070013373
13374 public boolean dumpHeap(String process, boolean managed,
13375 String path, ParcelFileDescriptor fd) throws RemoteException {
13376
13377 try {
13378 synchronized (this) {
13379 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13380 // its own permission (same as profileControl).
13381 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13382 != PackageManager.PERMISSION_GRANTED) {
13383 throw new SecurityException("Requires permission "
13384 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13385 }
13386
13387 if (fd == null) {
13388 throw new IllegalArgumentException("null fd");
13389 }
13390
13391 ProcessRecord proc = null;
13392 try {
13393 int pid = Integer.parseInt(process);
13394 synchronized (mPidsSelfLocked) {
13395 proc = mPidsSelfLocked.get(pid);
13396 }
13397 } catch (NumberFormatException e) {
13398 }
13399
13400 if (proc == null) {
13401 HashMap<String, SparseArray<ProcessRecord>> all
13402 = mProcessNames.getMap();
13403 SparseArray<ProcessRecord> procs = all.get(process);
13404 if (procs != null && procs.size() > 0) {
13405 proc = procs.valueAt(0);
13406 }
13407 }
13408
13409 if (proc == null || proc.thread == null) {
13410 throw new IllegalArgumentException("Unknown process: " + process);
13411 }
13412
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013413 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13414 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013415 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13416 throw new SecurityException("Process not debuggable: " + proc);
13417 }
13418 }
13419
13420 proc.thread.dumpHeap(managed, path, fd);
13421 fd = null;
13422 return true;
13423 }
13424 } catch (RemoteException e) {
13425 throw new IllegalStateException("Process disappeared");
13426 } finally {
13427 if (fd != null) {
13428 try {
13429 fd.close();
13430 } catch (IOException e) {
13431 }
13432 }
13433 }
13434 }
13435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013436 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13437 public void monitor() {
13438 synchronized (this) { }
13439 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013440
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013441 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013442 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13443 ProcessRecord processRecord = mLruProcesses.get(i);
13444 try {
13445 if (processRecord.thread != null) {
13446 processRecord.thread.setCoreSettings(settings);
13447 }
13448 } catch (RemoteException re) {
13449 /* ignore */
13450 }
13451 }
13452 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013453
13454 // Multi-user methods
13455
Amith Yamasani742a6712011-05-04 14:49:28 -070013456 public boolean switchUser(int userId) {
13457 final int callingUid = Binder.getCallingUid();
13458 if (callingUid != 0 && callingUid != Process.myUid()) {
13459 Slog.e(TAG, "Trying to switch user from unauthorized app");
13460 return false;
13461 }
13462 if (mCurrentUserId == userId)
13463 return true;
13464
13465 synchronized (this) {
13466 // Check if user is already logged in, otherwise check if user exists first before
13467 // adding to the list of logged in users.
13468 if (mLoggedInUsers.indexOfKey(userId) < 0) {
13469 if (!userExists(userId)) {
13470 return false;
13471 }
13472 mLoggedInUsers.append(userId, userId);
13473 }
13474
13475 mCurrentUserId = userId;
13476 boolean haveActivities = mMainStack.switchUser(userId);
13477 if (!haveActivities) {
13478 startHomeActivityLocked(userId);
13479 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013480
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013481 }
Amith Yamasani13593602012-03-22 16:16:17 -070013482
13483 // Inform of user switch
13484 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13485 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
13486 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
13487
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013488 return true;
13489 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013490
Amith Yamasani52f1d752012-03-28 18:19:29 -070013491 @Override
13492 public UserInfo getCurrentUser() throws RemoteException {
13493 final int callingUid = Binder.getCallingUid();
13494 if (callingUid != 0 && callingUid != Process.myUid()) {
13495 Slog.e(TAG, "Trying to get user from unauthorized app");
13496 return null;
13497 }
Amith Yamasani258848d2012-08-10 17:06:33 -070013498 return getUserManager().getUserInfo(mCurrentUserId);
Amith Yamasani52f1d752012-03-28 18:19:29 -070013499 }
13500
Amith Yamasani13593602012-03-22 16:16:17 -070013501 private void onUserRemoved(Intent intent) {
13502 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
13503 if (extraUserId < 1) return;
13504
13505 // Kill all the processes for the user
13506 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
13507 synchronized (this) {
13508 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
13509 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
13510 SparseArray<ProcessRecord> uids = uidMap.getValue();
13511 for (int i = 0; i < uids.size(); i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013512 if (UserHandle.getUserId(uids.keyAt(i)) == extraUserId) {
Amith Yamasani13593602012-03-22 16:16:17 -070013513 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
13514 }
13515 }
13516 }
13517
13518 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
13519 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
13520 false, false, true, true, extraUserId);
13521 }
13522 }
13523 }
13524
Amith Yamasani742a6712011-05-04 14:49:28 -070013525 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013526 UserInfo user = getUserManager().getUserInfo(userId);
13527 return user != null;
13528 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013529
Amith Yamasani258848d2012-08-10 17:06:33 -070013530 UserManager getUserManager() {
13531 if (mUserManager == null) {
13532 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13533 }
13534 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013535 }
13536
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013537 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013538 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013539
13540 throw new SecurityException("Caller uid=" + uid
13541 + " is not privileged to communicate with user=" + userId);
13542 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013543
13544 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013545 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013546 }
13547
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013548 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013549 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013550 ApplicationInfo newInfo = new ApplicationInfo(info);
13551 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013552 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13553 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013554 return newInfo;
13555 }
13556
13557 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013558 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013559 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013560 return aInfo;
13561 }
13562
13563 ActivityInfo info = new ActivityInfo(aInfo);
13564 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13565 return info;
13566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567}