blob: 1bb144c76cab9c5cd046320517ddbe155b561461 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080054import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020055import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080056import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080057import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070058import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070060import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.ContentResolver;
62import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020063import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070064import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070078import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070080import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.pm.ProviderInfo;
82import android.content.pm.ResolveInfo;
83import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040084import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.content.res.Configuration;
86import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070087import android.net.Proxy;
88import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.net.Uri;
90import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080091import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080092import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070093import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080094import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080096import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.FileUtils;
98import android.os.Handler;
99import android.os.IBinder;
100import android.os.IPermissionController;
101import android.os.Looper;
102import android.os.Message;
103import android.os.Parcel;
104import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700106import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import android.os.RemoteException;
108import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700109import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.SystemClock;
111import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700112import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700113import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700115import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.util.EventLog;
Fabrice Di Meglio5f797992012-06-15 20:16:41 -0700117import android.util.LocaleUtil;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800118import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700121import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700123import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700124import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.view.Gravity;
126import android.view.LayoutInflater;
127import android.view.View;
128import android.view.WindowManager;
129import android.view.WindowManagerPolicy;
130
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.BufferedInputStream;
132import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700133import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.DataInputStream;
135import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.File;
137import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700140import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200141import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800142import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700144import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.lang.ref.WeakReference;
146import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700155import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700179 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700180 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800181 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700184 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700185 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_POWER = localLOGV || false;
187 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean VALIDATE_TOKENS = false;
190 static final boolean SHOW_ACTIVITY_START_TIME = true;
191
192 // Control over CPU and battery monitoring.
193 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
194 static final boolean MONITOR_CPU_USAGE = true;
195 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
196 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
197 static final boolean MONITOR_THREAD_CPU_USAGE = false;
198
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700200 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800202 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700204 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Maximum number of recent tasks that we can remember.
207 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700208
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700209 // Amount of time after a call to stopAppSwitches() during which we will
210 // prevent further untrusted switches from happening.
211 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 // How long we wait for a launched process to attach to the activity manager
214 // before we decide it's never going to come up for real.
215 static final int PROC_START_TIMEOUT = 10*1000;
216
Jeff Brown3f9dd282011-07-08 20:02:19 -0700217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real, when the process was
219 // started with a wrapper for instrumentation (such as Valgrind) because it
220 // could take much longer than usual.
221 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // How long to wait after going idle before forcing apps to GC.
224 static final int GC_TIMEOUT = 5*1000;
225
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700226 // The minimum amount of time between successive GC requests for a process.
227 static final int GC_MIN_INTERVAL = 60*1000;
228
Dianne Hackborn287952c2010-09-22 22:34:31 -0700229 // The rate at which we check for apps using excessive power -- 15 mins.
230 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
231
232 // The minimum sample duration we will allow before deciding we have
233 // enough data on wake locks to start killing things.
234 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on CPU usage to start killing things.
238 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800241 static final int BROADCAST_FG_TIMEOUT = 10*1000;
242 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we wait until we timeout on key dispatching.
245 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we wait until we timeout on key dispatching during instrumentation.
248 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
249
Dan Egnor42471dd2010-01-07 17:25:22 -0800250 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 static final String[] EMPTY_STRING_ARRAY = new String[0];
253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700254 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700255
256 private final boolean mHeadless;
257
Joe Onorato54a4a412011-11-02 20:50:08 -0700258 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
259 // default actuion automatically. Important for devices without direct input
260 // devices.
261 private boolean mShowDialogs = true;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700264 * Description of a request to start a new activity, which has been held
265 * due to app switches being disabled.
266 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700267 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700268 ActivityRecord r;
269 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700270 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700271 }
272
273 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
274 = new ArrayList<PendingActivityLaunch>();
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800277 BroadcastQueue mFgBroadcastQueue;
278 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800279 // Convenient for easy iteration over the queues. Foreground is first
280 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800282
283 BroadcastQueue broadcastQueueForIntent(Intent intent) {
284 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
285 if (DEBUG_BACKGROUND_BROADCAST) {
286 Slog.i(TAG, "Broadcast intent " + intent + " on "
287 + (isFg ? "foreground" : "background")
288 + " queue");
289 }
290 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
291 }
292
293 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
294 for (BroadcastQueue queue : mBroadcastQueues) {
295 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
296 if (r != null) {
297 return r;
298 }
299 }
300 return null;
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * Activity we have told the window manager to have key focus.
305 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700306 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * List of intents that were used to start the most recent tasks.
309 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700310 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700313 * Process management.
314 */
315 final ProcessList mProcessList = new ProcessList();
316
317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * All of the applications we currently have running organized by name.
319 * The keys are strings of the application package name (as
320 * returned by the package manager), and the keys are ApplicationRecord
321 * objects.
322 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700323 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800326 * The currently running isolated processes.
327 */
328 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
329
330 /**
331 * Counter for assigning isolated process uids, to avoid frequently reusing the
332 * same ones.
333 */
334 int mNextIsolatedProcessUid = 0;
335
336 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700337 * The currently running heavy-weight process, if any.
338 */
339 ProcessRecord mHeavyWeightProcess = null;
340
341 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 * The last time that various processes have crashed.
343 */
344 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
345
346 /**
347 * Set of applications that we consider to be bad, and will reject
348 * incoming broadcasts from (which the user has no control over).
349 * Processes are added to this set when they have crashed twice within
350 * a minimum amount of time; they are removed from it when they are
351 * later restarted (hopefully due to some user action). The value is the
352 * time it was added to the list.
353 */
354 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
355
356 /**
357 * All of the processes we currently have running organized by pid.
358 * The keys are the pid running the application.
359 *
360 * <p>NOTE: This object is protected by its own lock, NOT the global
361 * activity manager lock!
362 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 /**
366 * All of the processes that have been forced to be foreground. The key
367 * is the pid of the caller who requested it (we hold a death
368 * link on it).
369 */
370 abstract class ForegroundToken implements IBinder.DeathRecipient {
371 int pid;
372 IBinder token;
373 }
374 final SparseArray<ForegroundToken> mForegroundProcesses
375 = new SparseArray<ForegroundToken>();
376
377 /**
378 * List of records for processes that someone had tried to start before the
379 * system was ready. We don't start them at that point, but ensure they
380 * are started by the time booting is complete.
381 */
382 final ArrayList<ProcessRecord> mProcessesOnHold
383 = new ArrayList<ProcessRecord>();
384
385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * List of persistent applications that are in the process
387 * of being started.
388 */
389 final ArrayList<ProcessRecord> mPersistentStartingProcesses
390 = new ArrayList<ProcessRecord>();
391
392 /**
393 * Processes that are being forcibly torn down.
394 */
395 final ArrayList<ProcessRecord> mRemovedProcesses
396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * List of running applications, sorted by recent usage.
400 * The first entry in the list is the least recently used.
401 * It contains ApplicationRecord objects. This list does NOT include
402 * any persistent application records (since we never want to exit them).
403 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800404 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 = new ArrayList<ProcessRecord>();
406
407 /**
408 * List of processes that should gc as soon as things are idle.
409 */
410 final ArrayList<ProcessRecord> mProcessesToGc
411 = new ArrayList<ProcessRecord>();
412
413 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800414 * This is the process holding what we currently consider to be
415 * the "home" activity.
416 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800418
419 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700420 * This is the process holding the activity the user last visited that
421 * is in a different process from the one they are currently in.
422 */
423 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800424
425 /**
426 * The time at which the previous process was last visible.
427 */
428 long mPreviousProcessVisibleTime;
429
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700430 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400431 * Packages that the user has asked to have run in screen size
432 * compatibility mode instead of filling the screen.
433 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700434 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400435
436 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 * Set of PendingResultRecord objects that are currently active.
438 */
439 final HashSet mPendingResultRecords = new HashSet();
440
441 /**
442 * Set of IntentSenderRecord objects that are currently active.
443 */
444 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
445 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
446
447 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800448 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700449 * already logged DropBox entries for. Guarded by itself. If
450 * something (rogue user app) forces this over
451 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
452 */
453 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
454 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
455
456 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700457 * Strict Mode background batched logging state.
458 *
459 * The string buffer is guarded by itself, and its lock is also
460 * used to determine if another batched write is already
461 * in-flight.
462 */
463 private final StringBuilder mStrictModeBuffer = new StringBuilder();
464
465 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466 * Keeps track of all IIntentReceivers that have been registered for
467 * broadcasts. Hash keys are the receiver IBinder, hash value is
468 * a ReceiverList.
469 */
470 final HashMap mRegisteredReceivers = new HashMap();
471
472 /**
473 * Resolver for broadcast intents to registered receivers.
474 * Holds BroadcastFilter (subclass of IntentFilter).
475 */
476 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
477 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
478 @Override
479 protected boolean allowFilterResult(
480 BroadcastFilter filter, List<BroadcastFilter> dest) {
481 IBinder target = filter.receiverList.receiver.asBinder();
482 for (int i=dest.size()-1; i>=0; i--) {
483 if (dest.get(i).receiverList.receiver.asBinder() == target) {
484 return false;
485 }
486 }
487 return true;
488 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700489
490 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700491 protected BroadcastFilter[] newArray(int size) {
492 return new BroadcastFilter[size];
493 }
494
495 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700496 protected String packageForFilter(BroadcastFilter filter) {
497 return filter.packageName;
498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 };
500
501 /**
502 * State of all active sticky broadcasts. Keys are the action of the
503 * sticky Intent, values are an ArrayList of all broadcasted intents with
504 * that action (which should usually be one).
505 */
506 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
507 new HashMap<String, ArrayList<Intent>>();
508
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700509 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510
511 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700512 * Backup/restore process management
513 */
514 String mBackupAppName = null;
515 BackupRecord mBackupTarget = null;
516
517 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 * List of PendingThumbnailsRecord objects of clients who are still
519 * waiting to receive all of the thumbnails for a task.
520 */
521 final ArrayList mPendingThumbnails = new ArrayList();
522
523 /**
524 * List of HistoryRecord objects that have been finished and must
525 * still report back to a pending thumbnail receiver.
526 */
527 final ArrayList mCancelledThumbnails = new ArrayList();
528
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 final ProviderMap mProviderMap = new ProviderMap();
530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 /**
532 * List of content providers who have clients waiting for them. The
533 * application is currently being launched and the provider will be
534 * removed from this list once it is published.
535 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700536 final ArrayList<ContentProviderRecord> mLaunchingProviders
537 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538
539 /**
540 * Global set of specific Uri permissions that have been granted.
541 */
542 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
543 = new SparseArray<HashMap<Uri, UriPermission>>();
544
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800545 CoreSettingsObserver mCoreSettingsObserver;
546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 /**
548 * Thread-local storage used to carry caller permissions over through
549 * indirect content-provider access.
550 * @see #ActivityManagerService.openContentUri()
551 */
552 private class Identity {
553 public int pid;
554 public int uid;
555
556 Identity(int _pid, int _uid) {
557 pid = _pid;
558 uid = _uid;
559 }
560 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
563
564 /**
565 * All information we have collected about the runtime performance of
566 * any user id that can impact battery performance.
567 */
568 final BatteryStatsService mBatteryStatsService;
569
570 /**
571 * information about component usage
572 */
573 final UsageStatsService mUsageStatsService;
574
575 /**
576 * Current configuration information. HistoryRecord objects are given
577 * a reference to this object to indicate which configuration they are
578 * currently running in, so this object must be kept immutable.
579 */
580 Configuration mConfiguration = new Configuration();
581
582 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800583 * Current sequencing integer of the configuration, for skipping old
584 * configurations.
585 */
586 int mConfigurationSeq = 0;
587
588 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700589 * Hardware-reported OpenGLES version.
590 */
591 final int GL_ES_VERSION;
592
593 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 * List of initialization arguments to pass to all processes when binding applications to them.
595 * For example, references to the commonly used services.
596 */
597 HashMap<String, IBinder> mAppBindArgs;
598
599 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700600 * Temporary to avoid allocations. Protected by main lock.
601 */
602 final StringBuilder mStringBuilder = new StringBuilder(256);
603
604 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 * Used to control how we initialize the service.
606 */
607 boolean mStartRunning = false;
608 ComponentName mTopComponent;
609 String mTopAction;
610 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700611 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800612 boolean mSystemReady = false;
613 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700614 boolean mWaitingUpdate = false;
615 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700616 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700617 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618
619 Context mContext;
620
621 int mFactoryTest;
622
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700623 boolean mCheckedForSetup;
624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700626 * The time at which we will allow normal application switches again,
627 * after a call to {@link #stopAppSwitches()}.
628 */
629 long mAppSwitchesAllowedTime;
630
631 /**
632 * This is set to true after the first switch after mAppSwitchesAllowedTime
633 * is set; any switches after that will clear the time.
634 */
635 boolean mDidAppSwitch;
636
637 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700638 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700639 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700640 long mLastPowerCheckRealtime;
641
642 /**
643 * Last time (in uptime) at which we checked for power usage.
644 */
645 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700646
647 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 * Set while we are wanting to sleep, to prevent any
649 * activities from being started/resumed.
650 */
651 boolean mSleeping = false;
652
653 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700654 * State of external calls telling us if the device is asleep.
655 */
656 boolean mWentToSleep = false;
657
658 /**
659 * State of external call telling us if the lock screen is shown.
660 */
661 boolean mLockScreenShown = false;
662
663 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700664 * Set if we are shutting down the system, similar to sleeping.
665 */
666 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667
668 /**
669 * Task identifier that activities are currently being started
670 * in. Incremented each time a new task is created.
671 * todo: Replace this with a TokenSpace class that generates non-repeating
672 * integers that won't wrap.
673 */
674 int mCurTask = 1;
675
676 /**
677 * Current sequence id for oom_adj computation traversal.
678 */
679 int mAdjSeq = 0;
680
681 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700682 * Current sequence id for process LRU updating.
683 */
684 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685
686 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700687 * Keep track of the non-hidden/empty process we last found, to help
688 * determine how to distribute hidden/empty processes next time.
689 */
690 int mNumNonHiddenProcs = 0;
691
692 /**
693 * Keep track of the number of hidden procs, to balance oom adj
694 * distribution between those and empty procs.
695 */
696 int mNumHiddenProcs = 0;
697
698 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700699 * Keep track of the number of service processes we last found, to
700 * determine on the next iteration which should be B services.
701 */
702 int mNumServiceProcs = 0;
703 int mNewNumServiceProcs = 0;
704
705 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 * System monitoring: number of processes that died since the last
707 * N procs were started.
708 */
709 int[] mProcDeaths = new int[20];
710
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700711 /**
712 * This is set if we had to do a delayed dexopt of an app before launching
713 * it, to increasing the ANR timeouts in that case.
714 */
715 boolean mDidDexOpt;
716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 String mDebugApp = null;
718 boolean mWaitForDebugger = false;
719 boolean mDebugTransient = false;
720 String mOrigDebugApp = null;
721 boolean mOrigWaitForDebugger = false;
722 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700723 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700724 String mProfileApp = null;
725 ProcessRecord mProfileProc = null;
726 String mProfileFile;
727 ParcelFileDescriptor mProfileFd;
728 int mProfileType = 0;
729 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800730 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700732 static class ProcessChangeItem {
733 static final int CHANGE_ACTIVITIES = 1<<0;
734 static final int CHANGE_IMPORTANCE= 1<<1;
735 int changes;
736 int uid;
737 int pid;
738 int importance;
739 boolean foregroundActivities;
740 }
741
Jeff Sharkeya4620792011-05-20 15:29:23 -0700742 final RemoteCallbackList<IProcessObserver> mProcessObservers
743 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700744 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
745
746 final ArrayList<ProcessChangeItem> mPendingProcessChanges
747 = new ArrayList<ProcessChangeItem>();
748 final ArrayList<ProcessChangeItem> mAvailProcessChanges
749 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 /**
752 * Callback of last caller to {@link #requestPss}.
753 */
754 Runnable mRequestPssCallback;
755
756 /**
757 * Remaining processes for which we are waiting results from the last
758 * call to {@link #requestPss}.
759 */
760 final ArrayList<ProcessRecord> mRequestPssList
761 = new ArrayList<ProcessRecord>();
762
763 /**
764 * Runtime statistics collection thread. This object's lock is used to
765 * protect all related state.
766 */
767 final Thread mProcessStatsThread;
768
769 /**
770 * Used to collect process stats when showing not responding dialog.
771 * Protected by mProcessStatsThread.
772 */
773 final ProcessStats mProcessStats = new ProcessStats(
774 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700775 final AtomicLong mLastCpuTime = new AtomicLong(0);
776 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 long mLastWriteTime = 0;
779
780 /**
781 * Set to true after the system has finished booting.
782 */
783 boolean mBooted = false;
784
Dianne Hackborn7d608422011-08-07 16:24:18 -0700785 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700786 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787
788 WindowManagerService mWindowManager;
789
790 static ActivityManagerService mSelf;
791 static ActivityThread mSystemThread;
792
Amith Yamasani258848d2012-08-10 17:06:33 -0700793 private int mCurrentUserId;
794 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
795 private UserManager mUserManager;
796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800797 private final class AppDeathRecipient implements IBinder.DeathRecipient {
798 final ProcessRecord mApp;
799 final int mPid;
800 final IApplicationThread mAppThread;
801
802 AppDeathRecipient(ProcessRecord app, int pid,
803 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800804 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 TAG, "New death recipient " + this
806 + " for thread " + thread.asBinder());
807 mApp = app;
808 mPid = pid;
809 mAppThread = thread;
810 }
811
812 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800813 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 TAG, "Death received in " + this
815 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 synchronized(ActivityManagerService.this) {
817 appDiedLocked(mApp, mPid, mAppThread);
818 }
819 }
820 }
821
822 static final int SHOW_ERROR_MSG = 1;
823 static final int SHOW_NOT_RESPONDING_MSG = 2;
824 static final int SHOW_FACTORY_ERROR_MSG = 3;
825 static final int UPDATE_CONFIGURATION_MSG = 4;
826 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
827 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 static final int SERVICE_TIMEOUT_MSG = 12;
829 static final int UPDATE_TIME_ZONE = 13;
830 static final int SHOW_UID_ERROR_MSG = 14;
831 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700833 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700834 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800835 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700836 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
837 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700838 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700839 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700840 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700841 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700842 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700843 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700844 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700845 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800847 static final int FIRST_ACTIVITY_STACK_MSG = 100;
848 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
849 static final int FIRST_COMPAT_MODE_MSG = 300;
850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700852 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700853 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
855 final Handler mHandler = new Handler() {
856 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 //}
859
860 public void handleMessage(Message msg) {
861 switch (msg.what) {
862 case SHOW_ERROR_MSG: {
863 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 synchronized (ActivityManagerService.this) {
865 ProcessRecord proc = (ProcessRecord)data.get("app");
866 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 return;
869 }
870 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700871 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800872 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 d.show();
874 proc.crashDialog = d;
875 } else {
876 // The device is asleep, so just pretend that the user
877 // saw a crash dialog and hit "force quit".
878 res.set(0);
879 }
880 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700881
882 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 } break;
884 case SHOW_NOT_RESPONDING_MSG: {
885 synchronized (ActivityManagerService.this) {
886 HashMap data = (HashMap) msg.obj;
887 ProcessRecord proc = (ProcessRecord)data.get("app");
888 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 return;
891 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800892
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700893 Intent intent = new Intent("android.intent.action.ANR");
894 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800895 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
896 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700897 }
898 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800899 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700900 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800901
Justin Kohbc52ca22012-03-29 15:11:44 -0700902 if (mShowDialogs) {
903 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700904 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700905 d.show();
906 proc.anrDialog = d;
907 } else {
908 // Just kill the app if there is no dialog to be shown.
909 killAppAtUsersRequest(proc, null);
910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700912
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700913 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800914 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700915 case SHOW_STRICT_MODE_VIOLATION_MSG: {
916 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
917 synchronized (ActivityManagerService.this) {
918 ProcessRecord proc = (ProcessRecord) data.get("app");
919 if (proc == null) {
920 Slog.e(TAG, "App not found when showing strict mode dialog.");
921 break;
922 }
923 if (proc.crashDialog != null) {
924 Slog.e(TAG, "App already has strict mode dialog: " + proc);
925 return;
926 }
927 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700928 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700929 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
930 d.show();
931 proc.crashDialog = d;
932 } else {
933 // The device is asleep, so just pretend that the user
934 // saw a crash dialog and hit "force quit".
935 res.set(0);
936 }
937 }
938 ensureBootCompleted();
939 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 case SHOW_FACTORY_ERROR_MSG: {
941 Dialog d = new FactoryErrorDialog(
942 mContext, msg.getData().getCharSequence("msg"));
943 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700944 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800945 } break;
946 case UPDATE_CONFIGURATION_MSG: {
947 final ContentResolver resolver = mContext.getContentResolver();
948 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
949 } break;
950 case GC_BACKGROUND_PROCESSES_MSG: {
951 synchronized (ActivityManagerService.this) {
952 performAppGcsIfAppropriateLocked();
953 }
954 } break;
955 case WAIT_FOR_DEBUGGER_MSG: {
956 synchronized (ActivityManagerService.this) {
957 ProcessRecord app = (ProcessRecord)msg.obj;
958 if (msg.arg1 != 0) {
959 if (!app.waitedForDebugger) {
960 Dialog d = new AppWaitingForDebuggerDialog(
961 ActivityManagerService.this,
962 mContext, app);
963 app.waitDialog = d;
964 app.waitedForDebugger = true;
965 d.show();
966 }
967 } else {
968 if (app.waitDialog != null) {
969 app.waitDialog.dismiss();
970 app.waitDialog = null;
971 }
972 }
973 }
974 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700976 if (mDidDexOpt) {
977 mDidDexOpt = false;
978 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
979 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700980 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700981 return;
982 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700983 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 } break;
985 case UPDATE_TIME_ZONE: {
986 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800987 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
988 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 if (r.thread != null) {
990 try {
991 r.thread.updateTimeZone();
992 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800993 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995 }
996 }
997 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700998 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700999 case CLEAR_DNS_CACHE: {
1000 synchronized (ActivityManagerService.this) {
1001 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1002 ProcessRecord r = mLruProcesses.get(i);
1003 if (r.thread != null) {
1004 try {
1005 r.thread.clearDnsCache();
1006 } catch (RemoteException ex) {
1007 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1008 }
1009 }
1010 }
1011 }
1012 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001013 case UPDATE_HTTP_PROXY: {
1014 ProxyProperties proxy = (ProxyProperties)msg.obj;
1015 String host = "";
1016 String port = "";
1017 String exclList = "";
1018 if (proxy != null) {
1019 host = proxy.getHost();
1020 port = Integer.toString(proxy.getPort());
1021 exclList = proxy.getExclusionList();
1022 }
1023 synchronized (ActivityManagerService.this) {
1024 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1025 ProcessRecord r = mLruProcesses.get(i);
1026 if (r.thread != null) {
1027 try {
1028 r.thread.setHttpProxy(host, port, exclList);
1029 } catch (RemoteException ex) {
1030 Slog.w(TAG, "Failed to update http proxy for: " +
1031 r.info.processName);
1032 }
1033 }
1034 }
1035 }
1036 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001038 String title = "System UIDs Inconsistent";
1039 String text = "UIDs on the system are inconsistent, you need to wipe your"
1040 + " data partition or your device will be unstable.";
1041 Log.e(TAG, title + ": " + text);
1042 if (mShowDialogs) {
1043 // XXX This is a temporary dialog, no need to localize.
1044 AlertDialog d = new BaseErrorDialog(mContext);
1045 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1046 d.setCancelable(false);
1047 d.setTitle(title);
1048 d.setMessage(text);
1049 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1050 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1051 mUidAlert = d;
1052 d.show();
1053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 } break;
1055 case IM_FEELING_LUCKY_MSG: {
1056 if (mUidAlert != null) {
1057 mUidAlert.dismiss();
1058 mUidAlert = null;
1059 }
1060 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001062 if (mDidDexOpt) {
1063 mDidDexOpt = false;
1064 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1065 nmsg.obj = msg.obj;
1066 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1067 return;
1068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 ProcessRecord app = (ProcessRecord)msg.obj;
1070 synchronized (ActivityManagerService.this) {
1071 processStartTimedOutLocked(app);
1072 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001073 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001074 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1075 synchronized (ActivityManagerService.this) {
1076 doPendingActivityLaunchesLocked(true);
1077 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001078 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001079 case KILL_APPLICATION_MSG: {
1080 synchronized (ActivityManagerService.this) {
1081 int uid = msg.arg1;
1082 boolean restart = (msg.arg2 == 1);
1083 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001084 forceStopPackageLocked(pkg, uid, restart, false, true, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001085 UserHandle.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001086 }
1087 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001088 case FINALIZE_PENDING_INTENT_MSG: {
1089 ((PendingIntentRecord)msg.obj).completeFinalize();
1090 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001091 case POST_HEAVY_NOTIFICATION_MSG: {
1092 INotificationManager inm = NotificationManager.getService();
1093 if (inm == null) {
1094 return;
1095 }
1096
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001097 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001098 ProcessRecord process = root.app;
1099 if (process == null) {
1100 return;
1101 }
1102
1103 try {
1104 Context context = mContext.createPackageContext(process.info.packageName, 0);
1105 String text = mContext.getString(R.string.heavy_weight_notification,
1106 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1107 Notification notification = new Notification();
1108 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1109 notification.when = 0;
1110 notification.flags = Notification.FLAG_ONGOING_EVENT;
1111 notification.tickerText = text;
1112 notification.defaults = 0; // please be quiet
1113 notification.sound = null;
1114 notification.vibrate = null;
1115 notification.setLatestEventInfo(context, text,
1116 mContext.getText(R.string.heavy_weight_notification_detail),
1117 PendingIntent.getActivity(mContext, 0, root.intent,
1118 PendingIntent.FLAG_CANCEL_CURRENT));
1119
1120 try {
1121 int[] outId = new int[1];
1122 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1123 notification, outId);
1124 } catch (RuntimeException e) {
1125 Slog.w(ActivityManagerService.TAG,
1126 "Error showing notification for heavy-weight app", e);
1127 } catch (RemoteException e) {
1128 }
1129 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001130 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001131 }
1132 } break;
1133 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1134 INotificationManager inm = NotificationManager.getService();
1135 if (inm == null) {
1136 return;
1137 }
1138 try {
1139 inm.cancelNotification("android",
1140 R.string.heavy_weight_notification);
1141 } catch (RuntimeException e) {
1142 Slog.w(ActivityManagerService.TAG,
1143 "Error canceling notification for service", e);
1144 } catch (RemoteException e) {
1145 }
1146 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001147 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1148 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001149 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001150 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001151 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1152 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001153 }
1154 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001155 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1156 synchronized (ActivityManagerService.this) {
1157 ActivityRecord ar = (ActivityRecord)msg.obj;
1158 if (mCompatModeDialog != null) {
1159 if (mCompatModeDialog.mAppInfo.packageName.equals(
1160 ar.info.applicationInfo.packageName)) {
1161 return;
1162 }
1163 mCompatModeDialog.dismiss();
1164 mCompatModeDialog = null;
1165 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001166 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001167 if (mCompatModePackages.getPackageAskCompatModeLocked(
1168 ar.packageName)) {
1169 int mode = mCompatModePackages.computeCompatModeLocked(
1170 ar.info.applicationInfo);
1171 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1172 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1173 mCompatModeDialog = new CompatModeDialog(
1174 ActivityManagerService.this, mContext,
1175 ar.info.applicationInfo);
1176 mCompatModeDialog.show();
1177 }
1178 }
1179 }
1180 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001181 break;
1182 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001183 case DISPATCH_PROCESSES_CHANGED: {
1184 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001185 break;
1186 }
1187 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001188 final int pid = msg.arg1;
1189 final int uid = msg.arg2;
1190 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001191 break;
1192 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001193 case REPORT_MEM_USAGE: {
1194 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1195 if (!isDebuggable) {
1196 return;
1197 }
1198 synchronized (ActivityManagerService.this) {
1199 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001200 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1201 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001202 // avoid spamming.
1203 return;
1204 }
1205 mLastMemUsageReportTime = now;
1206 }
1207 Thread thread = new Thread() {
1208 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001209 StringBuilder dropBuilder = new StringBuilder(1024);
1210 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001211 StringWriter oomSw = new StringWriter();
1212 PrintWriter oomPw = new PrintWriter(oomSw);
1213 StringWriter catSw = new StringWriter();
1214 PrintWriter catPw = new PrintWriter(catSw);
1215 String[] emptyArgs = new String[] { };
1216 StringBuilder tag = new StringBuilder(128);
1217 StringBuilder stack = new StringBuilder(128);
1218 tag.append("Low on memory -- ");
1219 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1220 tag, stack);
1221 dropBuilder.append(stack);
1222 dropBuilder.append('\n');
1223 dropBuilder.append('\n');
1224 String oomString = oomSw.toString();
1225 dropBuilder.append(oomString);
1226 dropBuilder.append('\n');
1227 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001228 try {
1229 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1230 "procrank", });
1231 final InputStreamReader converter = new InputStreamReader(
1232 proc.getInputStream());
1233 BufferedReader in = new BufferedReader(converter);
1234 String line;
1235 while (true) {
1236 line = in.readLine();
1237 if (line == null) {
1238 break;
1239 }
1240 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 logBuilder.append(line);
1242 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001243 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001244 dropBuilder.append(line);
1245 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001246 }
1247 converter.close();
1248 } catch (IOException e) {
1249 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001250 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001251 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001252 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001253 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001254 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1255 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001256 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001257 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001258 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001259 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001260 addErrorToDropBox("lowmem", null, "system_server", null,
1261 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001262 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 synchronized (ActivityManagerService.this) {
1264 long now = SystemClock.uptimeMillis();
1265 if (mLastMemUsageReportTime < now) {
1266 mLastMemUsageReportTime = now;
1267 }
1268 }
1269 }
1270 };
1271 thread.start();
1272 break;
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
1275 }
1276 };
1277
1278 public static void setSystemProcess() {
1279 try {
1280 ActivityManagerService m = mSelf;
1281
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001282 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001284 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001285 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (MONITOR_CPU_USAGE) {
1287 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 ServiceManager.addService("permission", new PermissionController(m));
1290
1291 ApplicationInfo info =
1292 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001293 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001294 mSystemThread.installSystemApplicationInfo(info);
1295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 synchronized (mSelf) {
1297 ProcessRecord app = mSelf.newProcessRecordLocked(
1298 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001299 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001301 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001302 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001303 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 synchronized (mSelf.mPidsSelfLocked) {
1305 mSelf.mPidsSelfLocked.put(app.pid, app);
1306 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001307 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 }
1309 } catch (PackageManager.NameNotFoundException e) {
1310 throw new RuntimeException(
1311 "Unable to find android system package", e);
1312 }
1313 }
1314
1315 public void setWindowManager(WindowManagerService wm) {
1316 mWindowManager = wm;
1317 }
1318
1319 public static final Context main(int factoryTest) {
1320 AThread thr = new AThread();
1321 thr.start();
1322
1323 synchronized (thr) {
1324 while (thr.mService == null) {
1325 try {
1326 thr.wait();
1327 } catch (InterruptedException e) {
1328 }
1329 }
1330 }
1331
1332 ActivityManagerService m = thr.mService;
1333 mSelf = m;
1334 ActivityThread at = ActivityThread.systemMain();
1335 mSystemThread = at;
1336 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001337 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 m.mContext = context;
1339 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001340 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341
1342 m.mBatteryStatsService.publish(context);
1343 m.mUsageStatsService.publish(context);
1344
1345 synchronized (thr) {
1346 thr.mReady = true;
1347 thr.notifyAll();
1348 }
1349
1350 m.startRunning(null, null, null, null);
1351
1352 return context;
1353 }
1354
1355 public static ActivityManagerService self() {
1356 return mSelf;
1357 }
1358
1359 static class AThread extends Thread {
1360 ActivityManagerService mService;
1361 boolean mReady = false;
1362
1363 public AThread() {
1364 super("ActivityManager");
1365 }
1366
1367 public void run() {
1368 Looper.prepare();
1369
1370 android.os.Process.setThreadPriority(
1371 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001372 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373
1374 ActivityManagerService m = new ActivityManagerService();
1375
1376 synchronized (this) {
1377 mService = m;
1378 notifyAll();
1379 }
1380
1381 synchronized (this) {
1382 while (!mReady) {
1383 try {
1384 wait();
1385 } catch (InterruptedException e) {
1386 }
1387 }
1388 }
1389
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001390 // For debug builds, log event loop stalls to dropbox for analysis.
1391 if (StrictMode.conditionallyEnableDebugLogging()) {
1392 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1393 }
1394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 Looper.loop();
1396 }
1397 }
1398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 static class MemBinder extends Binder {
1400 ActivityManagerService mActivityManagerService;
1401 MemBinder(ActivityManagerService activityManagerService) {
1402 mActivityManagerService = activityManagerService;
1403 }
1404
1405 @Override
1406 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001407 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1408 != PackageManager.PERMISSION_GRANTED) {
1409 pw.println("Permission Denial: can't dump meminfo from from pid="
1410 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1411 + " without permission " + android.Manifest.permission.DUMP);
1412 return;
1413 }
1414
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001415 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001416 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
Chet Haase9c1e23b2011-03-24 10:51:31 -07001420 static class GraphicsBinder extends Binder {
1421 ActivityManagerService mActivityManagerService;
1422 GraphicsBinder(ActivityManagerService activityManagerService) {
1423 mActivityManagerService = activityManagerService;
1424 }
1425
1426 @Override
1427 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001428 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1429 != PackageManager.PERMISSION_GRANTED) {
1430 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1431 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1432 + " without permission " + android.Manifest.permission.DUMP);
1433 return;
1434 }
1435
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001436 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001437 }
1438 }
1439
Jeff Brown6754ba22011-12-14 20:20:01 -08001440 static class DbBinder extends Binder {
1441 ActivityManagerService mActivityManagerService;
1442 DbBinder(ActivityManagerService activityManagerService) {
1443 mActivityManagerService = activityManagerService;
1444 }
1445
1446 @Override
1447 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1448 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1449 != PackageManager.PERMISSION_GRANTED) {
1450 pw.println("Permission Denial: can't dump dbinfo from from pid="
1451 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1452 + " without permission " + android.Manifest.permission.DUMP);
1453 return;
1454 }
1455
1456 mActivityManagerService.dumpDbInfo(fd, pw, args);
1457 }
1458 }
1459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001460 static class CpuBinder extends Binder {
1461 ActivityManagerService mActivityManagerService;
1462 CpuBinder(ActivityManagerService activityManagerService) {
1463 mActivityManagerService = activityManagerService;
1464 }
1465
1466 @Override
1467 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001468 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1469 != PackageManager.PERMISSION_GRANTED) {
1470 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1471 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1472 + " without permission " + android.Manifest.permission.DUMP);
1473 return;
1474 }
1475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001477 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1478 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1479 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481 }
1482 }
1483
1484 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001485 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001486
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001487 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1488 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1489 mBroadcastQueues[0] = mFgBroadcastQueue;
1490 mBroadcastQueues[1] = mBgBroadcastQueue;
1491
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001492 mServices = new ActiveServices(this);
1493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 File dataDir = Environment.getDataDirectory();
1495 File systemDir = new File(dataDir, "system");
1496 systemDir.mkdirs();
1497 mBatteryStatsService = new BatteryStatsService(new File(
1498 systemDir, "batterystats.bin").toString());
1499 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001500 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001501 mOnBattery = DEBUG_POWER ? true
1502 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001503 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001505 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001506 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001507 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Jack Palevichb90d28c2009-07-22 15:35:24 -07001509 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1510 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1511
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001512 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001513 mConfiguration.setLocale(Locale.getDefault());
1514
Dianne Hackborn813075a62011-11-14 17:45:19 -08001515 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 mProcessStats.init();
1517
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001518 mCompatModePackages = new CompatModePackages(this, systemDir);
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 // Add ourself to the Watchdog monitors.
1521 Watchdog.getInstance().addMonitor(this);
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 mProcessStatsThread = new Thread("ProcessStats") {
1524 public void run() {
1525 while (true) {
1526 try {
1527 try {
1528 synchronized(this) {
1529 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001530 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 // + ", write delay=" + nextWriteDelay);
1534 if (nextWriteDelay < nextCpuDelay) {
1535 nextCpuDelay = nextWriteDelay;
1536 }
1537 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001538 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 this.wait(nextCpuDelay);
1540 }
1541 }
1542 } catch (InterruptedException e) {
1543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 updateCpuStatsNow();
1545 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 };
1551 mProcessStatsThread.start();
1552 }
1553
1554 @Override
1555 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1556 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001557 if (code == SYSPROPS_TRANSACTION) {
1558 // We need to tell all apps about the system property change.
1559 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1560 synchronized(this) {
1561 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1562 final int NA = apps.size();
1563 for (int ia=0; ia<NA; ia++) {
1564 ProcessRecord app = apps.valueAt(ia);
1565 if (app.thread != null) {
1566 procs.add(app.thread.asBinder());
1567 }
1568 }
1569 }
1570 }
1571
1572 int N = procs.size();
1573 for (int i=0; i<N; i++) {
1574 Parcel data2 = Parcel.obtain();
1575 try {
1576 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1577 } catch (RemoteException e) {
1578 }
1579 data2.recycle();
1580 }
1581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 try {
1583 return super.onTransact(code, data, reply, flags);
1584 } catch (RuntimeException e) {
1585 // The activity manager only throws security exceptions, so let's
1586 // log all others.
1587 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001588 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590 throw e;
1591 }
1592 }
1593
1594 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001595 final long now = SystemClock.uptimeMillis();
1596 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1597 return;
1598 }
1599 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1600 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 mProcessStatsThread.notify();
1602 }
1603 }
1604 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 void updateCpuStatsNow() {
1607 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001608 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 final long now = SystemClock.uptimeMillis();
1610 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001613 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1614 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 haveNewCpuStats = true;
1616 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001617 //Slog.i(TAG, mProcessStats.printCurrentState());
1618 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 // + mProcessStats.getTotalCpuPercent() + "%");
1620
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 if ("true".equals(SystemProperties.get("events.cpu"))) {
1623 int user = mProcessStats.getLastUserTime();
1624 int system = mProcessStats.getLastSystemTime();
1625 int iowait = mProcessStats.getLastIoWaitTime();
1626 int irq = mProcessStats.getLastIrqTime();
1627 int softIrq = mProcessStats.getLastSoftIrqTime();
1628 int idle = mProcessStats.getLastIdleTime();
1629
1630 int total = user + system + iowait + irq + softIrq + idle;
1631 if (total == 0) total = 1;
1632
Doug Zongker2bec3d42009-12-04 12:52:44 -08001633 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 ((user+system+iowait+irq+softIrq) * 100) / total,
1635 (user * 100) / total,
1636 (system * 100) / total,
1637 (iowait * 100) / total,
1638 (irq * 100) / total,
1639 (softIrq * 100) / total);
1640 }
1641 }
1642
Amith Yamasanie43530a2009-08-21 13:11:37 -07001643 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001644 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001645 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 synchronized(mPidsSelfLocked) {
1647 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001648 if (mOnBattery) {
1649 int perc = bstats.startAddingCpuLocked();
1650 int totalUTime = 0;
1651 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001652 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001654 ProcessStats.Stats st = mProcessStats.getStats(i);
1655 if (!st.working) {
1656 continue;
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001659 int otherUTime = (st.rel_utime*perc)/100;
1660 int otherSTime = (st.rel_stime*perc)/100;
1661 totalUTime += otherUTime;
1662 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (pr != null) {
1664 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001665 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1666 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001667 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001668 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001669 } else {
1670 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001671 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001672 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001673 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1674 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001675 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 }
1678 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001679 bstats.finishAddingCpuLocked(perc, totalUTime,
1680 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682 }
1683 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1686 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001687 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 }
1690 }
1691 }
1692
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001693 @Override
1694 public void batteryNeedsCpuUpdate() {
1695 updateCpuStatsNow();
1696 }
1697
1698 @Override
1699 public void batteryPowerChanged(boolean onBattery) {
1700 // When plugging in, update the CPU stats first before changing
1701 // the plug state.
1702 updateCpuStatsNow();
1703 synchronized (this) {
1704 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001705 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001706 }
1707 }
1708 }
1709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 /**
1711 * Initialize the application bind args. These are passed to each
1712 * process when the bindApplication() IPC is sent to the process. They're
1713 * lazily setup to make sure the services are running when they're asked for.
1714 */
1715 private HashMap<String, IBinder> getCommonServicesLocked() {
1716 if (mAppBindArgs == null) {
1717 mAppBindArgs = new HashMap<String, IBinder>();
1718
1719 // Setup the application init args
1720 mAppBindArgs.put("package", ServiceManager.getService("package"));
1721 mAppBindArgs.put("window", ServiceManager.getService("window"));
1722 mAppBindArgs.put(Context.ALARM_SERVICE,
1723 ServiceManager.getService(Context.ALARM_SERVICE));
1724 }
1725 return mAppBindArgs;
1726 }
1727
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001728 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 if (mFocusedActivity != r) {
1730 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001731 if (r != null) {
1732 mWindowManager.setFocusedApp(r.appToken, true);
1733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735 }
1736
Dianne Hackborn906497c2010-05-10 15:57:38 -07001737 private final void updateLruProcessInternalLocked(ProcessRecord app,
1738 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 int lrui = mLruProcesses.indexOf(app);
1741 if (lrui >= 0) mLruProcesses.remove(lrui);
1742
1743 int i = mLruProcesses.size()-1;
1744 int skipTop = 0;
1745
Dianne Hackborn906497c2010-05-10 15:57:38 -07001746 app.lruSeq = mLruSeq;
1747
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001748 // compute the new weight for this process.
1749 if (updateActivityTime) {
1750 app.lastActivityTime = SystemClock.uptimeMillis();
1751 }
1752 if (app.activities.size() > 0) {
1753 // If this process has activities, we more strongly want to keep
1754 // it around.
1755 app.lruWeight = app.lastActivityTime;
1756 } else if (app.pubProviders.size() > 0) {
1757 // If this process contains content providers, we want to keep
1758 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001759 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001760 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001761 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001762 } else {
1763 // If this process doesn't have activities, we less strongly
1764 // want to keep it around, and generally want to avoid getting
1765 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001766 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001768 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001769 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001770
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001771 while (i >= 0) {
1772 ProcessRecord p = mLruProcesses.get(i);
1773 // If this app shouldn't be in front of the first N background
1774 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001775 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001776 skipTop--;
1777 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001778 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001779 mLruProcesses.add(i+1, app);
1780 break;
1781 }
1782 i--;
1783 }
1784 if (i < 0) {
1785 mLruProcesses.add(0, app);
1786 }
1787
Dianne Hackborn906497c2010-05-10 15:57:38 -07001788 // If the app is currently using a content provider or service,
1789 // bump those processes as well.
1790 if (app.connections.size() > 0) {
1791 for (ConnectionRecord cr : app.connections) {
1792 if (cr.binding != null && cr.binding.service != null
1793 && cr.binding.service.app != null
1794 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001795 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001796 updateActivityTime, i+1);
1797 }
1798 }
1799 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001800 for (int j=app.conProviders.size()-1; j>=0; j--) {
1801 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1802 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001803 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001804 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001805 }
1806 }
1807
Joe Onorato8a9b2202010-02-26 18:56:32 -08001808 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 if (oomAdj) {
1810 updateOomAdjLocked();
1811 }
1812 }
1813
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001814 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001815 boolean oomAdj, boolean updateActivityTime) {
1816 mLruSeq++;
1817 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1818 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001819
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001822 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001823 // The system gets to run in any process. If there are multiple
1824 // processes with the same uid, just pick the first (this
1825 // should never happen).
1826 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1827 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001828 if (procs == null) return null;
1829 final int N = procs.size();
1830 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001831 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834 ProcessRecord proc = mProcessNames.get(processName, uid);
1835 return proc;
1836 }
1837
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001838 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001839 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001840 try {
1841 if (pm.performDexOpt(packageName)) {
1842 mDidDexOpt = true;
1843 }
1844 } catch (RemoteException e) {
1845 }
1846 }
1847
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 int transit = mWindowManager.getPendingAppTransition();
1850 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1851 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1852 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1853 }
1854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001855 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001857 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1858 boolean isolated) {
1859 ProcessRecord app;
1860 if (!isolated) {
1861 app = getProcessRecordLocked(processName, info.uid);
1862 } else {
1863 // If this is an isolated process, it can't re-use an existing process.
1864 app = null;
1865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 // We don't have to do anything more if:
1867 // (1) There is an existing application record; and
1868 // (2) The caller doesn't think it is dead, OR there is no thread
1869 // object attached to it so we know it couldn't have crashed; and
1870 // (3) There is a pid assigned to it, so it is either starting or
1871 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001872 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 + " app=" + app + " knownToBeDead=" + knownToBeDead
1874 + " thread=" + (app != null ? app.thread : null)
1875 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001876 if (app != null && app.pid > 0) {
1877 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001878 // We already have the app running, or are waiting for it to
1879 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001880 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001881 // If this is a new package in the process, add the package to the list
1882 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001883 return app;
1884 } else {
1885 // An application record is attached to a previous process,
1886 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001887 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001888 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 String hostingNameStr = hostingName != null
1893 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001894
1895 if (!isolated) {
1896 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1897 // If we are in the background, then check to see if this process
1898 // is bad. If so, we will just silently fail.
1899 if (mBadProcesses.get(info.processName, info.uid) != null) {
1900 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1901 + "/" + info.processName);
1902 return null;
1903 }
1904 } else {
1905 // When the user is explicitly starting a process, then clear its
1906 // crash count so that we won't make it bad until they see at
1907 // least one crash dialog again, and make the process good again
1908 // if it had been bad.
1909 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001910 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911 mProcessCrashTimes.remove(info.processName, info.uid);
1912 if (mBadProcesses.get(info.processName, info.uid) != null) {
1913 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1914 info.processName);
1915 mBadProcesses.remove(info.processName, info.uid);
1916 if (app != null) {
1917 app.bad = false;
1918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 }
1920 }
1921 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001924 app = newProcessRecordLocked(null, info, processName, isolated);
1925 if (app == null) {
1926 Slog.w(TAG, "Failed making new process record for "
1927 + processName + "/" + info.uid + " isolated=" + isolated);
1928 return null;
1929 }
1930 mProcessNames.put(processName, app.uid, app);
1931 if (isolated) {
1932 mIsolatedProcesses.put(app.uid, app);
1933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 } else {
1935 // If this is a new package in the process, add the package to the list
1936 app.addPackage(info.packageName);
1937 }
1938
1939 // If the system is not ready yet, then hold off on starting this
1940 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001941 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001942 && !isAllowedWhileBooting(info)
1943 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 if (!mProcessesOnHold.contains(app)) {
1945 mProcessesOnHold.add(app);
1946 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001947 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 return app;
1949 }
1950
1951 startProcessLocked(app, hostingType, hostingNameStr);
1952 return (app.pid != 0) ? app : null;
1953 }
1954
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001955 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1956 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1957 }
1958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 private final void startProcessLocked(ProcessRecord app,
1960 String hostingType, String hostingNameStr) {
1961 if (app.pid > 0 && app.pid != MY_PID) {
1962 synchronized (mPidsSelfLocked) {
1963 mPidsSelfLocked.remove(app.pid);
1964 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1965 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001966 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001969 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1970 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 mProcessesOnHold.remove(app);
1972
1973 updateCpuStats();
1974
1975 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1976 mProcDeaths[0] = 0;
1977
1978 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001979 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07001982 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001983 if (!app.isolated) {
1984 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07001985 final PackageManager pm = mContext.getPackageManager();
1986 gids = pm.getPackageGids(app.info.packageName);
1987 if (pm.checkPermission(
1988 android.Manifest.permission.READ_EXTERNAL_STORAGE, app.info.packageName)
1989 == PERMISSION_GRANTED) {
1990 if (Environment.isExternalStorageEmulated()) {
1991 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
1992 } else {
1993 mountExternal = Zygote.MOUNT_EXTERNAL_SINGLEUSER;
1994 }
1995 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 } catch (PackageManager.NameNotFoundException e) {
1997 Slog.w(TAG, "Unable to retrieve gids", e);
1998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
2000 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2001 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2002 && mTopComponent != null
2003 && app.processName.equals(mTopComponent.getPackageName())) {
2004 uid = 0;
2005 }
2006 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2007 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2008 uid = 0;
2009 }
2010 }
2011 int debugFlags = 0;
2012 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2013 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002014 // Also turn on CheckJNI for debuggable apps. It's quite
2015 // awkward to turn on otherwise.
2016 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002018 // Run the app in safe mode if its manifest requests so or the
2019 // system is booted in safe mode.
2020 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2021 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002022 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2025 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2026 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002027 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2028 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 if ("1".equals(SystemProperties.get("debug.assert"))) {
2031 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2032 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002033
2034 // Start the process. It will either succeed and return a result containing
2035 // the PID of the new process, or else throw a RuntimeException.
2036 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002037 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002038 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2041 synchronized (bs) {
2042 if (bs.isOnBattery()) {
2043 app.batteryStats.incStartsLocked();
2044 }
2045 }
2046
Jeff Brown3f9dd282011-07-08 20:02:19 -07002047 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 app.processName, hostingType,
2049 hostingNameStr != null ? hostingNameStr : "");
2050
2051 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002052 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
2054
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002055 StringBuilder buf = mStringBuilder;
2056 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 buf.append("Start proc ");
2058 buf.append(app.processName);
2059 buf.append(" for ");
2060 buf.append(hostingType);
2061 if (hostingNameStr != null) {
2062 buf.append(" ");
2063 buf.append(hostingNameStr);
2064 }
2065 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002066 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 buf.append(" uid=");
2068 buf.append(uid);
2069 buf.append(" gids={");
2070 if (gids != null) {
2071 for (int gi=0; gi<gids.length; gi++) {
2072 if (gi != 0) buf.append(", ");
2073 buf.append(gids[gi]);
2074
2075 }
2076 }
2077 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002078 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002079 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002080 app.usingWrapper = startResult.usingWrapper;
2081 app.removed = false;
2082 synchronized (mPidsSelfLocked) {
2083 this.mPidsSelfLocked.put(startResult.pid, app);
2084 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2085 msg.obj = app;
2086 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2087 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 }
2089 } catch (RuntimeException e) {
2090 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002091 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002092 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094 }
2095
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002096 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 if (resumed) {
2098 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2099 } else {
2100 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2101 }
2102 }
2103
Amith Yamasani742a6712011-05-04 14:49:28 -07002104 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002105 if (mHeadless) {
2106 // Added because none of the other calls to ensureBootCompleted seem to fire
2107 // when running headless.
2108 ensureBootCompleted();
2109 return false;
2110 }
2111
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002112 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2113 && mTopAction == null) {
2114 // We are running in factory test mode, but unable to find
2115 // the factory test app, so just sit around displaying the
2116 // error message and don't try to start anything.
2117 return false;
2118 }
2119 Intent intent = new Intent(
2120 mTopAction,
2121 mTopData != null ? Uri.parse(mTopData) : null);
2122 intent.setComponent(mTopComponent);
2123 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2124 intent.addCategory(Intent.CATEGORY_HOME);
2125 }
2126 ActivityInfo aInfo =
2127 intent.resolveActivityInfo(mContext.getPackageManager(),
2128 STOCK_PM_FLAGS);
2129 if (aInfo != null) {
2130 intent.setComponent(new ComponentName(
2131 aInfo.applicationInfo.packageName, aInfo.name));
2132 // Don't do this if the home app is currently being
2133 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002134 aInfo = new ActivityInfo(aInfo);
2135 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002136 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2137 aInfo.applicationInfo.uid);
2138 if (app == null || app.instrumentationClass == null) {
2139 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002140 mMainStack.startActivityLocked(null, intent, null, aInfo,
2141 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002142 }
2143 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002144
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002145 return true;
2146 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002147
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002148 /**
2149 * Starts the "new version setup screen" if appropriate.
2150 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002152 // Only do this once per boot.
2153 if (mCheckedForSetup) {
2154 return;
2155 }
2156
2157 // We will show this screen if the current one is a different
2158 // version than the last one shown, and we are not running in
2159 // low-level factory test mode.
2160 final ContentResolver resolver = mContext.getContentResolver();
2161 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2162 Settings.Secure.getInt(resolver,
2163 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2164 mCheckedForSetup = true;
2165
2166 // See if we should be showing the platform update setup UI.
2167 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2168 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2169 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2170
2171 // We don't allow third party apps to replace this.
2172 ResolveInfo ri = null;
2173 for (int i=0; ris != null && i<ris.size(); i++) {
2174 if ((ris.get(i).activityInfo.applicationInfo.flags
2175 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2176 ri = ris.get(i);
2177 break;
2178 }
2179 }
2180
2181 if (ri != null) {
2182 String vers = ri.activityInfo.metaData != null
2183 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2184 : null;
2185 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2186 vers = ri.activityInfo.applicationInfo.metaData.getString(
2187 Intent.METADATA_SETUP_VERSION);
2188 }
2189 String lastVers = Settings.Secure.getString(
2190 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2191 if (vers != null && !vers.equals(lastVers)) {
2192 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2193 intent.setComponent(new ComponentName(
2194 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002195 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2196 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002197 }
2198 }
2199 }
2200 }
2201
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002202 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002203 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002204 }
2205
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002206 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002207 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002208 throw new SecurityException("Isolated process not allowed to call " + caller);
2209 }
2210 }
2211
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002212 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002213 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002214 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002215 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2216 }
2217 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002218
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002219 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002220 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2221 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002222 synchronized (this) {
2223 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2224 }
2225 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002226
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002227 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002228 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002229 synchronized (this) {
2230 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2231 }
2232 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002233
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002234 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002235 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2236 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002237 synchronized (this) {
2238 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002239 }
2240 }
2241
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002242 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002243 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002244 synchronized (this) {
2245 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2246 }
2247 }
2248
2249 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002250 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2251 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002252 synchronized (this) {
2253 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2254 }
2255 }
2256
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002258 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002259 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002262 private void dispatchProcessesChanged() {
2263 int N;
2264 synchronized (this) {
2265 N = mPendingProcessChanges.size();
2266 if (mActiveProcessChanges.length < N) {
2267 mActiveProcessChanges = new ProcessChangeItem[N];
2268 }
2269 mPendingProcessChanges.toArray(mActiveProcessChanges);
2270 mAvailProcessChanges.addAll(mPendingProcessChanges);
2271 mPendingProcessChanges.clear();
2272 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2273 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002274 int i = mProcessObservers.beginBroadcast();
2275 while (i > 0) {
2276 i--;
2277 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2278 if (observer != null) {
2279 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002280 for (int j=0; j<N; j++) {
2281 ProcessChangeItem item = mActiveProcessChanges[j];
2282 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2283 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2284 + item.pid + " uid=" + item.uid + ": "
2285 + item.foregroundActivities);
2286 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2287 item.foregroundActivities);
2288 }
2289 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2290 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2291 + item.pid + " uid=" + item.uid + ": " + item.importance);
2292 observer.onImportanceChanged(item.pid, item.uid,
2293 item.importance);
2294 }
2295 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002296 } catch (RemoteException e) {
2297 }
2298 }
2299 }
2300 mProcessObservers.finishBroadcast();
2301 }
2302
2303 private void dispatchProcessDied(int pid, int uid) {
2304 int i = mProcessObservers.beginBroadcast();
2305 while (i > 0) {
2306 i--;
2307 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2308 if (observer != null) {
2309 try {
2310 observer.onProcessDied(pid, uid);
2311 } catch (RemoteException e) {
2312 }
2313 }
2314 }
2315 mProcessObservers.finishBroadcast();
2316 }
2317
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002318 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002319 final int N = mPendingActivityLaunches.size();
2320 if (N <= 0) {
2321 return;
2322 }
2323 for (int i=0; i<N; i++) {
2324 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002325 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002326 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002327 }
2328 mPendingActivityLaunches.clear();
2329 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002330
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002331 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002332 Intent intent, String resolvedType, IBinder resultTo,
2333 String resultWho, int requestCode, int startFlags,
2334 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002335 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002336 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002337 }
2338
2339 public final int startActivityAsUser(IApplicationThread caller,
2340 Intent intent, String resolvedType, IBinder resultTo,
2341 String resultWho, int requestCode, int startFlags,
2342 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002343 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002344 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07002345 // Requesting a different user, make sure that they have the permission
2346 if (checkComponentPermission(
2347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2348 Binder.getCallingPid(), Binder.getCallingUid(), -1, true)
2349 == PackageManager.PERMISSION_GRANTED) {
2350 // Translate to the current user id, if caller wasn't aware
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002351 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07002352 userId = mCurrentUserId;
2353 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002354 } else {
Amith Yamasani82644082012-08-03 13:09:11 -07002355 String msg = "Permission Denial: "
2356 + "Request to startActivity as user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002357 + " but is calling from user " + UserHandle.getCallingUserId()
Amith Yamasani82644082012-08-03 13:09:11 -07002358 + "; this requires "
2359 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
2360 Slog.w(TAG, msg);
2361 throw new SecurityException(msg);
2362 }
2363 } else {
2364 if (intent.getCategories() != null
2365 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2366 // Requesting home, set the identity to the current user
2367 // HACK!
2368 userId = mCurrentUserId;
2369 } else {
2370 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2371 // the current user's userId
2372 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2373 userId = 0;
2374 } else {
2375 userId = Binder.getOrigCallingUser();
2376 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002377 }
2378 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002379 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002380 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2381 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002382 }
2383
2384 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 Intent intent, String resolvedType, IBinder resultTo,
2386 String resultWho, int requestCode, int startFlags, String profileFile,
2387 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002388 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002389 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002390 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002391 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2393 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002394 return res;
2395 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002396
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002397 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 Intent intent, String resolvedType, IBinder resultTo,
2399 String resultWho, int requestCode, int startFlags, Configuration config,
2400 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002401 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002402 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002403 resultTo, resultWho, requestCode, startFlags,
2404 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002405 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002406 }
2407
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002408 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002409 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002410 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002412 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002413 // Refuse possible leaked file descriptors
2414 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2415 throw new IllegalArgumentException("File descriptors passed in Intent");
2416 }
2417
2418 IIntentSender sender = intent.getTarget();
2419 if (!(sender instanceof PendingIntentRecord)) {
2420 throw new IllegalArgumentException("Bad PendingIntent object");
2421 }
2422
2423 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002424
2425 synchronized (this) {
2426 // If this is coming from the currently resumed activity, it is
2427 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002428 if (mMainStack.mResumedActivity != null
2429 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002430 Binder.getCallingUid()) {
2431 mAppSwitchesAllowedTime = 0;
2432 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002433 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2435 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002436 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002437 }
2438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 // Refuse possible leaked file descriptors
2442 if (intent != null && intent.hasFileDescriptors() == true) {
2443 throw new IllegalArgumentException("File descriptors passed in Intent");
2444 }
2445
2446 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002447 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2448 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002449 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 return false;
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if (r.app == null || r.app.thread == null) {
2453 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002454 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 intent = new Intent(intent);
2458 // The caller is not allowed to change the data.
2459 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2460 // And we are resetting to find the next component...
2461 intent.setComponent(null);
2462
2463 ActivityInfo aInfo = null;
2464 try {
2465 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002466 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002468 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002469 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470
2471 // Look for the original activity in the list...
2472 final int N = resolves != null ? resolves.size() : 0;
2473 for (int i=0; i<N; i++) {
2474 ResolveInfo rInfo = resolves.get(i);
2475 if (rInfo.activityInfo.packageName.equals(r.packageName)
2476 && rInfo.activityInfo.name.equals(r.info.name)) {
2477 // We found the current one... the next matching is
2478 // after it.
2479 i++;
2480 if (i<N) {
2481 aInfo = resolves.get(i).activityInfo;
2482 }
2483 break;
2484 }
2485 }
2486 } catch (RemoteException e) {
2487 }
2488
2489 if (aInfo == null) {
2490 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002491 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 return false;
2493 }
2494
2495 intent.setComponent(new ComponentName(
2496 aInfo.applicationInfo.packageName, aInfo.name));
2497 intent.setFlags(intent.getFlags()&~(
2498 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2499 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2500 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2501 Intent.FLAG_ACTIVITY_NEW_TASK));
2502
2503 // Okay now we need to start the new activity, replacing the
2504 // currently running activity. This is a little tricky because
2505 // we want to start the new one as if the current one is finished,
2506 // but not finish the current one first so that there is no flicker.
2507 // And thus...
2508 final boolean wasFinishing = r.finishing;
2509 r.finishing = true;
2510
2511 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002512 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 final String resultWho = r.resultWho;
2514 final int requestCode = r.requestCode;
2515 r.resultTo = null;
2516 if (resultTo != null) {
2517 resultTo.removeResultsLocked(r, resultWho, requestCode);
2518 }
2519
2520 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002522 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2523 resultWho, requestCode, -1, r.launchedFromUid, 0,
2524 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Binder.restoreCallingIdentity(origId);
2526
2527 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 return false;
2530 }
2531 return true;
2532 }
2533 }
2534
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002535 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002537 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002538
2539 // This is so super not safe, that only the system (or okay root)
2540 // can do it.
2541 final int callingUid = Binder.getCallingUid();
2542 if (callingUid != 0 && callingUid != Process.myUid()) {
2543 throw new SecurityException(
2544 "startActivityInPackage only available to the system");
2545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546
Amith Yamasani742a6712011-05-04 14:49:28 -07002547 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002548 resultTo, resultWho, requestCode, startFlags,
Amith Yamasani7300dbe2012-08-17 14:17:57 -07002549 null, null, null, null, options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002550 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002551 }
2552
2553 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002554 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002555 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002556 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002558 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002559 }
2560
2561 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002562 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2563 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002564
2565 // This is so super not safe, that only the system (or okay root)
2566 // can do it.
2567 final int callingUid = Binder.getCallingUid();
2568 if (callingUid != 0 && callingUid != Process.myUid()) {
2569 throw new SecurityException(
2570 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002572 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002573 options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002574 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002577 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002579 // Quick case: check if the top-most recent task is the same.
2580 if (N > 0 && mRecentTasks.get(0) == task) {
2581 return;
2582 }
2583 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 for (int i=0; i<N; i++) {
2585 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002586 if (task.userId == tr.userId
2587 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2588 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 mRecentTasks.remove(i);
2590 i--;
2591 N--;
2592 if (task.intent == null) {
2593 // If the new recent task we are adding is not fully
2594 // specified, then replace it with the existing recent task.
2595 task = tr;
2596 }
2597 }
2598 }
2599 if (N >= MAX_RECENT_TASKS) {
2600 mRecentTasks.remove(N-1);
2601 }
2602 mRecentTasks.add(0, task);
2603 }
2604
2605 public void setRequestedOrientation(IBinder token,
2606 int requestedOrientation) {
2607 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002608 ActivityRecord r = mMainStack.isInStackLocked(token);
2609 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 return;
2611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002613 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002615 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002616 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 if (config != null) {
2618 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002619 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002620 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 }
2622 }
2623 Binder.restoreCallingIdentity(origId);
2624 }
2625 }
2626
2627 public int getRequestedOrientation(IBinder token) {
2628 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002629 ActivityRecord r = mMainStack.isInStackLocked(token);
2630 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2632 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002633 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 }
2635 }
2636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 /**
2638 * This is the internal entry point for handling Activity.finish().
2639 *
2640 * @param token The Binder token referencing the Activity we want to finish.
2641 * @param resultCode Result code, if any, from this Activity.
2642 * @param resultData Result data (Intent), if any, from this Activity.
2643 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002644 * @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 -08002645 */
2646 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2647 // Refuse possible leaked file descriptors
2648 if (resultData != null && resultData.hasFileDescriptors() == true) {
2649 throw new IllegalArgumentException("File descriptors passed in Intent");
2650 }
2651
2652 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002653 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002655 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (next != null) {
2657 // ask watcher if this is allowed
2658 boolean resumeOK = true;
2659 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002660 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002662 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002663 }
2664
2665 if (!resumeOK) {
2666 return false;
2667 }
2668 }
2669 }
2670 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 resultData, "app-request");
2673 Binder.restoreCallingIdentity(origId);
2674 return res;
2675 }
2676 }
2677
Dianne Hackborn860755f2010-06-03 18:47:52 -07002678 public final void finishHeavyWeightApp() {
2679 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2680 != PackageManager.PERMISSION_GRANTED) {
2681 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2682 + Binder.getCallingPid()
2683 + ", uid=" + Binder.getCallingUid()
2684 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2685 Slog.w(TAG, msg);
2686 throw new SecurityException(msg);
2687 }
2688
2689 synchronized(this) {
2690 if (mHeavyWeightProcess == null) {
2691 return;
2692 }
2693
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002694 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002695 mHeavyWeightProcess.activities);
2696 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002697 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002698 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002699 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002700 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002701 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002702 null, "finish-heavy");
2703 }
2704 }
2705 }
2706
2707 mHeavyWeightProcess = null;
2708 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2709 }
2710 }
2711
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002712 public void crashApplication(int uid, int initialPid, String packageName,
2713 String message) {
2714 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2715 != PackageManager.PERMISSION_GRANTED) {
2716 String msg = "Permission Denial: crashApplication() from pid="
2717 + Binder.getCallingPid()
2718 + ", uid=" + Binder.getCallingUid()
2719 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2720 Slog.w(TAG, msg);
2721 throw new SecurityException(msg);
2722 }
2723
2724 synchronized(this) {
2725 ProcessRecord proc = null;
2726
2727 // Figure out which process to kill. We don't trust that initialPid
2728 // still has any relation to current pids, so must scan through the
2729 // list.
2730 synchronized (mPidsSelfLocked) {
2731 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2732 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002733 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002734 continue;
2735 }
2736 if (p.pid == initialPid) {
2737 proc = p;
2738 break;
2739 }
2740 for (String str : p.pkgList) {
2741 if (str.equals(packageName)) {
2742 proc = p;
2743 }
2744 }
2745 }
2746 }
2747
2748 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002749 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002750 + " initialPid=" + initialPid
2751 + " packageName=" + packageName);
2752 return;
2753 }
2754
2755 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002756 if (proc.pid == Process.myPid()) {
2757 Log.w(TAG, "crashApplication: trying to crash self!");
2758 return;
2759 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002760 long ident = Binder.clearCallingIdentity();
2761 try {
2762 proc.thread.scheduleCrash(message);
2763 } catch (RemoteException e) {
2764 }
2765 Binder.restoreCallingIdentity(ident);
2766 }
2767 }
2768 }
2769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 public final void finishSubActivity(IBinder token, String resultWho,
2771 int requestCode) {
2772 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002773 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002774 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 Binder.restoreCallingIdentity(origId);
2776 }
2777 }
2778
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002779 public boolean finishActivityAffinity(IBinder token) {
2780 synchronized(this) {
2781 final long origId = Binder.clearCallingIdentity();
2782 boolean res = mMainStack.finishActivityAffinityLocked(token);
2783 Binder.restoreCallingIdentity(origId);
2784 return res;
2785 }
2786 }
2787
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002788 public boolean willActivityBeVisible(IBinder token) {
2789 synchronized(this) {
2790 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002791 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2792 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002793 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002794 return true;
2795 }
2796 if (r.fullscreen && !r.finishing) {
2797 return false;
2798 }
2799 }
2800 return true;
2801 }
2802 }
2803
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002804 public void overridePendingTransition(IBinder token, String packageName,
2805 int enterAnim, int exitAnim) {
2806 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002807 ActivityRecord self = mMainStack.isInStackLocked(token);
2808 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002809 return;
2810 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002811
2812 final long origId = Binder.clearCallingIdentity();
2813
2814 if (self.state == ActivityState.RESUMED
2815 || self.state == ActivityState.PAUSING) {
2816 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002817 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002818 }
2819
2820 Binder.restoreCallingIdentity(origId);
2821 }
2822 }
2823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 * Main function for removing an existing process from the activity manager
2826 * as a result of that process going away. Clears out all connections
2827 * to the process.
2828 */
2829 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002830 boolean restarting, boolean allowRestart) {
2831 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002833 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002834 }
2835
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002836 if (mProfileProc == app) {
2837 clearProfilerLocked();
2838 }
2839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002841 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2842 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2843 mMainStack.mPausingActivity = null;
2844 }
2845 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2846 mMainStack.mLastPausedActivity = null;
2847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848
2849 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851
2852 boolean atTop = true;
2853 boolean hasVisibleActivities = false;
2854
2855 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002856 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002857 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 TAG, "Removing app " + app + " from history with " + i + " entries");
2859 while (i > 0) {
2860 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002861 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002862 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2864 if (r.app == app) {
2865 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002866 if (ActivityStack.DEBUG_ADD_REMOVE) {
2867 RuntimeException here = new RuntimeException("here");
2868 here.fillInStackTrace();
2869 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2870 + ": haveState=" + r.haveState
2871 + " stateNotNeeded=" + r.stateNotNeeded
2872 + " finishing=" + r.finishing
2873 + " state=" + r.state, here);
2874 }
2875 if (!r.finishing) {
2876 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002877 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2878 System.identityHashCode(r),
2879 r.task.taskId, r.shortComponentName,
2880 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002881 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002882 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883
2884 } else {
2885 // We have the current state for this activity, so
2886 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002887 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 TAG, "Keeping entry, setting app to null");
2889 if (r.visible) {
2890 hasVisibleActivities = true;
2891 }
2892 r.app = null;
2893 r.nowVisible = false;
2894 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002895 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2896 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 r.icicle = null;
2898 }
2899 }
2900
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002901 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 }
2903 atTop = false;
2904 }
2905
2906 app.activities.clear();
2907
2908 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002909 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 + " running instrumentation " + app.instrumentationClass);
2911 Bundle info = new Bundle();
2912 info.putString("shortMsg", "Process crashed.");
2913 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2914 }
2915
2916 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002917 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 // If there was nothing to resume, and we are not already
2919 // restarting this process, but there is a visible activity that
2920 // is hosted by the process... then make sure all visible
2921 // activities are running, taking care of restarting this
2922 // process.
2923 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002924 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
2927 }
2928 }
2929
2930 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2931 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002932 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002933 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2934 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2936 return i;
2937 }
2938 }
2939 return -1;
2940 }
2941
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002942 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 IApplicationThread thread) {
2944 if (thread == null) {
2945 return null;
2946 }
2947
2948 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002949 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
2951
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 IApplicationThread thread) {
2954
2955 mProcDeaths[0]++;
2956
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002957 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2958 synchronized (stats) {
2959 stats.noteProcessDiedLocked(app.info.uid, pid);
2960 }
2961
Magnus Edlund7bb25812010-02-24 15:45:06 +01002962 // Clean up already done if the process has been re-started.
2963 if (app.pid == pid && app.thread != null &&
2964 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002965 if (!app.killedBackground) {
2966 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2967 + ") has died.");
2968 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002969 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002970 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 TAG, "Dying app: " + app + ", pid: " + pid
2972 + ", thread: " + thread.asBinder());
2973 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002974 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975
2976 if (doLowMem) {
2977 // If there are no longer any background processes running,
2978 // and the app that died was not running instrumentation,
2979 // then tell everyone we are now low on memory.
2980 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002981 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2982 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002983 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 haveBg = true;
2985 break;
2986 }
2987 }
2988
2989 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002990 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002991 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002992 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2993 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002994 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002995 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2996 // The low memory report is overriding any current
2997 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002998 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002999 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003000 rec.lastRequestedGc = 0;
3001 } else {
3002 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003004 rec.reportLowMemory = true;
3005 rec.lastLowMemory = now;
3006 mProcessesToGc.remove(rec);
3007 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 }
3009 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003010 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003011 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 }
3013 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003014 } else if (app.pid != pid) {
3015 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003016 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003017 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003018 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003019 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003020 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 + thread.asBinder());
3022 }
3023 }
3024
Dan Egnor42471dd2010-01-07 17:25:22 -08003025 /**
3026 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003027 * @param clearTraces causes the dump file to be erased prior to the new
3028 * traces being written, if true; when false, the new traces will be
3029 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003030 * @param firstPids of dalvik VM processes to dump stack traces for first
3031 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003032 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003033 * @return file containing stack traces, or null if no dump file is configured
3034 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003036 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003037 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3038 if (tracesPath == null || tracesPath.length() == 0) {
3039 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003041
3042 File tracesFile = new File(tracesPath);
3043 try {
3044 File tracesDir = tracesFile.getParentFile();
3045 if (!tracesDir.exists()) tracesFile.mkdirs();
3046 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3047
Christopher Tate6ee412d2010-05-28 12:01:56 -07003048 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003049 tracesFile.createNewFile();
3050 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3051 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003052 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003053 return null;
3054 }
3055
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003056 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003057 return tracesFile;
3058 }
3059
3060 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003061 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003062 // Use a FileObserver to detect when traces finish writing.
3063 // The order of traces is considered important to maintain for legibility.
3064 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3065 public synchronized void onEvent(int event, String path) { notify(); }
3066 };
3067
3068 try {
3069 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003070
3071 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003072 if (firstPids != null) {
3073 try {
3074 int num = firstPids.size();
3075 for (int i = 0; i < num; i++) {
3076 synchronized (observer) {
3077 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3078 observer.wait(200); // Wait for write-close, give up after 200msec
3079 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003080 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003081 } catch (InterruptedException e) {
3082 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003083 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003084 }
3085
3086 // Next measure CPU usage.
3087 if (processStats != null) {
3088 processStats.init();
3089 System.gc();
3090 processStats.update();
3091 try {
3092 synchronized (processStats) {
3093 processStats.wait(500); // measure over 1/2 second.
3094 }
3095 } catch (InterruptedException e) {
3096 }
3097 processStats.update();
3098
3099 // We'll take the stack crawls of just the top apps using CPU.
3100 final int N = processStats.countWorkingStats();
3101 int numProcs = 0;
3102 for (int i=0; i<N && numProcs<5; i++) {
3103 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3104 if (lastPids.indexOfKey(stats.pid) >= 0) {
3105 numProcs++;
3106 try {
3107 synchronized (observer) {
3108 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3109 observer.wait(200); // Wait for write-close, give up after 200msec
3110 }
3111 } catch (InterruptedException e) {
3112 Log.wtf(TAG, e);
3113 }
3114
3115 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003116 }
3117 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003118
Dan Egnor42471dd2010-01-07 17:25:22 -08003119 } finally {
3120 observer.stopWatching();
3121 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003122
3123 if (nativeProcs != null) {
3124 int[] pids = Process.getPidsForCommands(nativeProcs);
3125 if (pids != null) {
3126 for (int pid : pids) {
3127 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3128 }
3129 }
3130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 }
3132
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003133 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003134 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003135 return;
3136 }
3137 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3138 if (tracesPath == null || tracesPath.length() == 0) {
3139 return;
3140 }
3141
3142 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3143 StrictMode.allowThreadDiskWrites();
3144 try {
3145 final File tracesFile = new File(tracesPath);
3146 final File tracesDir = tracesFile.getParentFile();
3147 final File tracesTmp = new File(tracesDir, "__tmp__");
3148 try {
3149 if (!tracesDir.exists()) tracesFile.mkdirs();
3150 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3151
3152 if (tracesFile.exists()) {
3153 tracesTmp.delete();
3154 tracesFile.renameTo(tracesTmp);
3155 }
3156 StringBuilder sb = new StringBuilder();
3157 Time tobj = new Time();
3158 tobj.set(System.currentTimeMillis());
3159 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3160 sb.append(": ");
3161 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3162 sb.append(" since ");
3163 sb.append(msg);
3164 FileOutputStream fos = new FileOutputStream(tracesFile);
3165 fos.write(sb.toString().getBytes());
3166 if (app == null) {
3167 fos.write("\n*** No application process!".getBytes());
3168 }
3169 fos.close();
3170 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3171 } catch (IOException e) {
3172 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3173 return;
3174 }
3175
3176 if (app != null) {
3177 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3178 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003179 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003180 }
3181
3182 File lastTracesFile = null;
3183 File curTracesFile = null;
3184 for (int i=9; i>=0; i--) {
3185 String name = String.format("slow%02d.txt", i);
3186 curTracesFile = new File(tracesDir, name);
3187 if (curTracesFile.exists()) {
3188 if (lastTracesFile != null) {
3189 curTracesFile.renameTo(lastTracesFile);
3190 } else {
3191 curTracesFile.delete();
3192 }
3193 }
3194 lastTracesFile = curTracesFile;
3195 }
3196 tracesFile.renameTo(curTracesFile);
3197 if (tracesTmp.exists()) {
3198 tracesTmp.renameTo(tracesFile);
3199 }
3200 } finally {
3201 StrictMode.setThreadPolicy(oldPolicy);
3202 }
3203 }
3204
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003205 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3206 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003207 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3208 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3209
Dianne Hackborn287952c2010-09-22 22:34:31 -07003210 if (mController != null) {
3211 try {
3212 // 0 == continue, -1 = kill process immediately
3213 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3214 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3215 } catch (RemoteException e) {
3216 mController = null;
3217 }
3218 }
3219
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003220 long anrTime = SystemClock.uptimeMillis();
3221 if (MONITOR_CPU_USAGE) {
3222 updateCpuStatsNow();
3223 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003224
3225 synchronized (this) {
3226 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3227 if (mShuttingDown) {
3228 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3229 return;
3230 } else if (app.notResponding) {
3231 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3232 return;
3233 } else if (app.crashing) {
3234 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3235 return;
3236 }
3237
3238 // In case we come through here for the same app before completing
3239 // this one, mark as anring now so we will bail out.
3240 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003241
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003242 // Log the ANR to the event log.
3243 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3244 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003245
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003247 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003248
3249 int parentPid = app.pid;
3250 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003251 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003252
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003253 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003254
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003255 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3256 ProcessRecord r = mLruProcesses.get(i);
3257 if (r != null && r.thread != null) {
3258 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003259 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3260 if (r.persistent) {
3261 firstPids.add(pid);
3262 } else {
3263 lastPids.put(pid, Boolean.TRUE);
3264 }
3265 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
3268 }
3269
Dan Egnor42471dd2010-01-07 17:25:22 -08003270 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003271 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003272 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003273 info.append("ANR in ").append(app.processName);
3274 if (activity != null && activity.shortComponentName != null) {
3275 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003276 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003277 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003279 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003281 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003282 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284
Dianne Hackborn287952c2010-09-22 22:34:31 -07003285 final ProcessStats processStats = new ProcessStats(true);
3286
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003287 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003288
Dan Egnor42471dd2010-01-07 17:25:22 -08003289 String cpuInfo = null;
3290 if (MONITOR_CPU_USAGE) {
3291 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003292 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003293 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003294 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003295 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003296 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003299 info.append(processStats.printCurrentState(anrTime));
3300
Joe Onorato8a9b2202010-02-26 18:56:32 -08003301 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003302 if (tracesFile == null) {
3303 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3304 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3305 }
3306
Jeff Sharkeya353d262011-10-28 11:12:06 -07003307 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3308 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003309
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003310 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003312 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3313 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003315 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3316 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 }
3318 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003319 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 }
3321 }
3322
Dan Egnor42471dd2010-01-07 17:25:22 -08003323 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3324 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3325 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003326
3327 synchronized (this) {
3328 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003329 Slog.w(TAG, "Killing " + app + ": background ANR");
3330 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3331 app.processName, app.setAdj, "background ANR");
3332 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003333 return;
3334 }
3335
3336 // Set the app's notResponding state, and look up the errorReportReceiver
3337 makeAppNotRespondingLocked(app,
3338 activity != null ? activity.shortComponentName : null,
3339 annotation != null ? "ANR " + annotation : "ANR",
3340 info.toString());
3341
3342 // Bring up the infamous App Not Responding dialog
3343 Message msg = Message.obtain();
3344 HashMap map = new HashMap();
3345 msg.what = SHOW_NOT_RESPONDING_MSG;
3346 msg.obj = map;
3347 map.put("app", app);
3348 if (activity != null) {
3349 map.put("activity", activity);
3350 }
3351
3352 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003356 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3357 if (!mLaunchWarningShown) {
3358 mLaunchWarningShown = true;
3359 mHandler.post(new Runnable() {
3360 @Override
3361 public void run() {
3362 synchronized (ActivityManagerService.this) {
3363 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3364 d.show();
3365 mHandler.postDelayed(new Runnable() {
3366 @Override
3367 public void run() {
3368 synchronized (ActivityManagerService.this) {
3369 d.dismiss();
3370 mLaunchWarningShown = false;
3371 }
3372 }
3373 }, 4000);
3374 }
3375 }
3376 });
3377 }
3378 }
3379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003381 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003382 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 int uid = Binder.getCallingUid();
3384 int pid = Binder.getCallingPid();
3385 long callingId = Binder.clearCallingIdentity();
3386 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003387 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003388 int pkgUid = -1;
3389 synchronized(this) {
3390 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003391 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 } catch (RemoteException e) {
3393 }
3394 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003395 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 return false;
3397 }
3398 if (uid == pkgUid || checkComponentPermission(
3399 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003400 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003402 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 } else {
3404 throw new SecurityException(pid+" does not have permission:"+
3405 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3406 "for process:"+packageName);
3407 }
3408 }
3409
3410 try {
3411 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003412 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3414 Uri.fromParts("package", packageName, null));
3415 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003416 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003417 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 } catch (RemoteException e) {
3419 }
3420 } finally {
3421 Binder.restoreCallingIdentity(callingId);
3422 }
3423 return true;
3424 }
3425
Dianne Hackborn03abb812010-01-04 18:43:19 -08003426 public void killBackgroundProcesses(final String packageName) {
3427 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3428 != PackageManager.PERMISSION_GRANTED &&
3429 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3430 != PackageManager.PERMISSION_GRANTED) {
3431 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003432 + Binder.getCallingPid()
3433 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003435 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 throw new SecurityException(msg);
3437 }
3438
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003439 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 long callingId = Binder.clearCallingIdentity();
3441 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003442 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 int pkgUid = -1;
3444 synchronized(this) {
3445 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003446 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 } catch (RemoteException e) {
3448 }
3449 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003450 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 return;
3452 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003453 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003454 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3455 }
3456 } finally {
3457 Binder.restoreCallingIdentity(callingId);
3458 }
3459 }
3460
3461 public void killAllBackgroundProcesses() {
3462 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3463 != PackageManager.PERMISSION_GRANTED) {
3464 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3465 + Binder.getCallingPid()
3466 + ", uid=" + Binder.getCallingUid()
3467 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3468 Slog.w(TAG, msg);
3469 throw new SecurityException(msg);
3470 }
3471
3472 long callingId = Binder.clearCallingIdentity();
3473 try {
3474 synchronized(this) {
3475 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3476 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3477 final int NA = apps.size();
3478 for (int ia=0; ia<NA; ia++) {
3479 ProcessRecord app = apps.valueAt(ia);
3480 if (app.persistent) {
3481 // we don't kill persistent processes
3482 continue;
3483 }
3484 if (app.removed) {
3485 procs.add(app);
3486 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3487 app.removed = true;
3488 procs.add(app);
3489 }
3490 }
3491 }
3492
3493 int N = procs.size();
3494 for (int i=0; i<N; i++) {
3495 removeProcessLocked(procs.get(i), false, true, "kill all background");
3496 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003497 }
3498 } finally {
3499 Binder.restoreCallingIdentity(callingId);
3500 }
3501 }
3502
3503 public void forceStopPackage(final String packageName) {
3504 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3505 != PackageManager.PERMISSION_GRANTED) {
3506 String msg = "Permission Denial: forceStopPackage() from pid="
3507 + Binder.getCallingPid()
3508 + ", uid=" + Binder.getCallingUid()
3509 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003510 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003511 throw new SecurityException(msg);
3512 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003513 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003514 long callingId = Binder.clearCallingIdentity();
3515 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003516 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003517 int pkgUid = -1;
3518 synchronized(this) {
3519 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003520 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003521 } catch (RemoteException e) {
3522 }
3523 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003524 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003525 return;
3526 }
3527 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003528 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003529 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003530 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003531 } catch (IllegalArgumentException e) {
3532 Slog.w(TAG, "Failed trying to unstop package "
3533 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 }
3536 } finally {
3537 Binder.restoreCallingIdentity(callingId);
3538 }
3539 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003540
3541 /*
3542 * The pkg name and uid have to be specified.
3543 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3544 */
3545 public void killApplicationWithUid(String pkg, int uid) {
3546 if (pkg == null) {
3547 return;
3548 }
3549 // Make sure the uid is valid.
3550 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003551 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003552 return;
3553 }
3554 int callerUid = Binder.getCallingUid();
3555 // Only the system server can kill an application
3556 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003557 // Post an aysnc message to kill the application
3558 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3559 msg.arg1 = uid;
3560 msg.arg2 = 0;
3561 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003562 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003563 } else {
3564 throw new SecurityException(callerUid + " cannot kill pkg: " +
3565 pkg);
3566 }
3567 }
3568
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003569 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003570 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003571
3572 final int uid = Binder.getCallingUid();
3573 final long origId = Binder.clearCallingIdentity();
3574 synchronized (this) {
3575 closeSystemDialogsLocked(uid, reason);
3576 }
3577 Binder.restoreCallingIdentity(origId);
3578 }
3579
3580 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003581 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003582 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003583 if (reason != null) {
3584 intent.putExtra("reason", reason);
3585 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003586 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003587
Dianne Hackborne302a162012-05-15 14:58:32 -07003588 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3589 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003590 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003591 r.stack.finishActivityLocked(r, i,
3592 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003593 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003594 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003595
3596 broadcastIntentLocked(null, null, intent, null,
3597 null, 0, null, null, null, false, false, -1,
3598 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003599 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003600
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003601 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003602 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003603 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003604 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3605 for (int i=pids.length-1; i>=0; i--) {
3606 infos[i] = new Debug.MemoryInfo();
3607 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003608 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003609 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003610 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003611
Dianne Hackbornb437e092011-08-05 17:50:29 -07003612 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003613 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003614 long[] pss = new long[pids.length];
3615 for (int i=pids.length-1; i>=0; i--) {
3616 pss[i] = Debug.getPss(pids[i]);
3617 }
3618 return pss;
3619 }
3620
Christopher Tate5e1ab332009-09-01 20:32:49 -07003621 public void killApplicationProcess(String processName, int uid) {
3622 if (processName == null) {
3623 return;
3624 }
3625
3626 int callerUid = Binder.getCallingUid();
3627 // Only the system server can kill an application
3628 if (callerUid == Process.SYSTEM_UID) {
3629 synchronized (this) {
3630 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003631 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003632 try {
3633 app.thread.scheduleSuicide();
3634 } catch (RemoteException e) {
3635 // If the other end already died, then our work here is done.
3636 }
3637 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003638 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003639 + processName + " / " + uid);
3640 }
3641 }
3642 } else {
3643 throw new SecurityException(callerUid + " cannot kill app process: " +
3644 processName);
3645 }
3646 }
3647
Dianne Hackborn03abb812010-01-04 18:43:19 -08003648 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003649 forceStopPackageLocked(packageName, uid, false, false, true, false, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3651 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003652 if (!mProcessesReady) {
3653 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 intent.putExtra(Intent.EXTRA_UID, uid);
3656 broadcastIntentLocked(null, null, intent,
3657 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003658 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003659 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
3661
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003662 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003663 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003664 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003665 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666
Dianne Hackborn03abb812010-01-04 18:43:19 -08003667 // Remove all processes this package may have touched: all with the
3668 // same UID (except for the system or root user), and all whose name
3669 // matches the package name.
3670 final String procNamePrefix = packageName + ":";
3671 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3672 final int NA = apps.size();
3673 for (int ia=0; ia<NA; ia++) {
3674 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003675 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003676 // we don't kill persistent processes
3677 continue;
3678 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003679 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003680 if (doit) {
3681 procs.add(app);
3682 }
Amith Yamasani13593602012-03-22 16:16:17 -07003683 // If uid is specified and the uid and process name match
3684 // Or, the uid is not specified and the process name matches
3685 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003686 || ((app.processName.equals(packageName)
3687 || app.processName.startsWith(procNamePrefix))
3688 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003689 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003690 if (!doit) {
3691 return true;
3692 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003693 app.removed = true;
3694 procs.add(app);
3695 }
3696 }
3697 }
3698 }
3699
3700 int N = procs.size();
3701 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003702 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003703 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003704 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003705 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003706
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003707 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003708 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003709 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003710 int i;
3711 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003713 if (uid < 0) {
3714 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003715 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 } catch (RemoteException e) {
3717 }
3718 }
3719
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003720 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003721 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003722
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003723 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3724 while (badApps.hasNext()) {
3725 SparseArray<Long> ba = badApps.next();
3726 if (ba.get(uid) != null) {
3727 badApps.remove();
3728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
3730 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003731
3732 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003733 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003735 TaskRecord lastTask = null;
3736 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003737 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003738 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003739 if (r.userId == userId
3740 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003741 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003742 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003743 if (r.finishing) {
3744 // If this activity is just finishing, then it is not
3745 // interesting as far as something to stop.
3746 continue;
3747 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003748 return true;
3749 }
3750 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003751 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003752 if (samePackage) {
3753 if (r.app != null) {
3754 r.app.removed = true;
3755 }
3756 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003758 lastTask = r.task;
3759 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003760 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003761 i--;
3762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 }
3764 }
3765
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003766 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3767 if (!doit) {
3768 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003770 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003772
3773 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003774 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003775 if (provider.info.packageName.equals(name)
3776 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3777 if (!doit) {
3778 return true;
3779 }
3780 didSomething = true;
3781 providers.add(provider);
3782 }
3783 }
3784
3785 N = providers.size();
3786 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003787 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003788 }
3789
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003790 if (doit) {
3791 if (purgeCache) {
3792 AttributeCache ac = AttributeCache.instance();
3793 if (ac != null) {
3794 ac.removePackage(name);
3795 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003796 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003797 if (mBooted) {
3798 mMainStack.resumeTopActivityLocked(null);
3799 mMainStack.scheduleIdleLocked();
3800 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003801 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003802
3803 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 }
3805
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003806 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003807 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003809 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003811 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 + "/" + uid + ")");
3813
3814 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003815 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003816 if (mHeavyWeightProcess == app) {
3817 mHeavyWeightProcess = null;
3818 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 boolean needRestart = false;
3821 if (app.pid > 0 && app.pid != MY_PID) {
3822 int pid = app.pid;
3823 synchronized (mPidsSelfLocked) {
3824 mPidsSelfLocked.remove(pid);
3825 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3826 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003827 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003828 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003829 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003830 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003832 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003833 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003834 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 } else {
3836 needRestart = true;
3837 }
3838 }
3839 } else {
3840 mRemovedProcesses.add(app);
3841 }
3842
3843 return needRestart;
3844 }
3845
3846 private final void processStartTimedOutLocked(ProcessRecord app) {
3847 final int pid = app.pid;
3848 boolean gone = false;
3849 synchronized (mPidsSelfLocked) {
3850 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3851 if (knownApp != null && knownApp.thread == null) {
3852 mPidsSelfLocked.remove(pid);
3853 gone = true;
3854 }
3855 }
3856
3857 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003858 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003859 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003860 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003861 mProcessNames.remove(app.processName, app.uid);
3862 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003863 if (mHeavyWeightProcess == app) {
3864 mHeavyWeightProcess = null;
3865 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3866 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003867 // Take care of any launching providers waiting for this process.
3868 checkAppInLaunchingProvidersLocked(app, true);
3869 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003870 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003871 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3872 app.processName, app.setAdj, "start timeout");
3873 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003874 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003875 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003876 try {
3877 IBackupManager bm = IBackupManager.Stub.asInterface(
3878 ServiceManager.getService(Context.BACKUP_SERVICE));
3879 bm.agentDisconnected(app.info.packageName);
3880 } catch (RemoteException e) {
3881 // Can't happen; the backup manager is local
3882 }
3883 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003884 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003885 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003886 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003889 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 }
3891 }
3892
3893 private final boolean attachApplicationLocked(IApplicationThread thread,
3894 int pid) {
3895
3896 // Find the application record that is being attached... either via
3897 // the pid if we are running in multiple processes, or just pull the
3898 // next app record if we are emulating process with anonymous threads.
3899 ProcessRecord app;
3900 if (pid != MY_PID && pid >= 0) {
3901 synchronized (mPidsSelfLocked) {
3902 app = mPidsSelfLocked.get(pid);
3903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 } else {
3905 app = null;
3906 }
3907
3908 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003909 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003911 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003913 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 } else {
3915 try {
3916 thread.scheduleExit();
3917 } catch (Exception e) {
3918 // Ignore exceptions.
3919 }
3920 }
3921 return false;
3922 }
3923
3924 // If this application record is still attached to a previous
3925 // process, clean it up now.
3926 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003927 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 }
3929
3930 // Tell the process all about itself.
3931
Joe Onorato8a9b2202010-02-26 18:56:32 -08003932 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 TAG, "Binding process pid " + pid + " to record " + app);
3934
3935 String processName = app.processName;
3936 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003937 AppDeathRecipient adr = new AppDeathRecipient(
3938 app, pid, thread);
3939 thread.asBinder().linkToDeath(adr, 0);
3940 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 } catch (RemoteException e) {
3942 app.resetPackageList();
3943 startProcessLocked(app, "link fail", processName);
3944 return false;
3945 }
3946
Doug Zongker2bec3d42009-12-04 12:52:44 -08003947 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948
3949 app.thread = thread;
3950 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003951 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3952 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 app.forcingToForeground = null;
3954 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003955 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 app.debugging = false;
3957
3958 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3959
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003960 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003961 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003963 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003964 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003965 }
3966
Joe Onorato8a9b2202010-02-26 18:56:32 -08003967 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 TAG, "New app record " + app
3969 + " thread=" + thread.asBinder() + " pid=" + pid);
3970 try {
3971 int testMode = IApplicationThread.DEBUG_OFF;
3972 if (mDebugApp != null && mDebugApp.equals(processName)) {
3973 testMode = mWaitForDebugger
3974 ? IApplicationThread.DEBUG_WAIT
3975 : IApplicationThread.DEBUG_ON;
3976 app.debugging = true;
3977 if (mDebugTransient) {
3978 mDebugApp = mOrigDebugApp;
3979 mWaitForDebugger = mOrigWaitForDebugger;
3980 }
3981 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003982 String profileFile = app.instrumentationProfileFile;
3983 ParcelFileDescriptor profileFd = null;
3984 boolean profileAutoStop = false;
3985 if (mProfileApp != null && mProfileApp.equals(processName)) {
3986 mProfileProc = app;
3987 profileFile = mProfileFile;
3988 profileFd = mProfileFd;
3989 profileAutoStop = mAutoStopProfiler;
3990 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003991 boolean enableOpenGlTrace = false;
3992 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3993 enableOpenGlTrace = true;
3994 mOpenGlTraceApp = null;
3995 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003996
Christopher Tate181fafa2009-05-14 11:12:14 -07003997 // If the app is being launched for restore or full backup, set it up specially
3998 boolean isRestrictedBackupMode = false;
3999 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4000 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004001 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004002 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4003 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004004
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004005 ensurePackageDexOpt(app.instrumentationInfo != null
4006 ? app.instrumentationInfo.packageName
4007 : app.info.packageName);
4008 if (app.instrumentationClass != null) {
4009 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004010 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004011 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004012 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004013 ApplicationInfo appInfo = app.instrumentationInfo != null
4014 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004015 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004016 if (profileFd != null) {
4017 profileFd = profileFd.dup();
4018 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004019 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004020 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004021 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4022 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004023 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004024 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004025 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004026 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 } catch (Exception e) {
4028 // todo: Yikes! What should we do? For now we will try to
4029 // start another process, but that could easily get us in
4030 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004031 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
4033 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004034 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 startProcessLocked(app, "bind fail", processName);
4036 return false;
4037 }
4038
4039 // Remove this record from the list of starting applications.
4040 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004041 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4042 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 mProcessesOnHold.remove(app);
4044
4045 boolean badApp = false;
4046 boolean didSomething = false;
4047
4048 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004049 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004050 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004051 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 && processName.equals(hr.processName)) {
4053 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004054 if (mHeadless) {
4055 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4056 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 didSomething = true;
4058 }
4059 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004060 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 + hr.intent.getComponent().flattenToShortString(), e);
4062 badApp = true;
4063 }
4064 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004065 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 }
4067 }
4068
4069 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004070 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004072 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 badApp = true;
4075 }
4076 }
4077
Christopher Tatef46723b2012-01-26 14:19:24 -08004078 // Check if a next-broadcast receiver is in this process...
4079 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004081 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004083 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 }
4086 }
4087
Christopher Tate181fafa2009-05-14 11:12:14 -07004088 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004089 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004090 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004091 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004092 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004093 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4094 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4095 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004096 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004097 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004098 e.printStackTrace();
4099 }
4100 }
4101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 if (badApp) {
4103 // todo: Also need to kill application to deal with all
4104 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004105 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 return false;
4107 }
4108
4109 if (!didSomething) {
4110 updateOomAdjLocked();
4111 }
4112
4113 return true;
4114 }
4115
4116 public final void attachApplication(IApplicationThread thread) {
4117 synchronized (this) {
4118 int callingPid = Binder.getCallingPid();
4119 final long origId = Binder.clearCallingIdentity();
4120 attachApplicationLocked(thread, callingPid);
4121 Binder.restoreCallingIdentity(origId);
4122 }
4123 }
4124
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004125 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004127 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4128 if (stopProfiling) {
4129 synchronized (this) {
4130 if (mProfileProc == r.app) {
4131 if (mProfileFd != null) {
4132 try {
4133 mProfileFd.close();
4134 } catch (IOException e) {
4135 }
4136 clearProfilerLocked();
4137 }
4138 }
4139 }
4140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 Binder.restoreCallingIdentity(origId);
4142 }
4143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004145 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004146 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004148
4149 synchronized (this) {
4150 updateEventDispatchingLocked();
4151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 }
4153
Dianne Hackborn661cd522011-08-22 00:26:20 -07004154 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004155 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004156 mWindowManager.showBootMessage(msg, always);
4157 }
4158
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004159 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004160 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004161 final long token = Binder.clearCallingIdentity();
4162 try {
4163 synchronized (this) {
4164 if (mLockScreenShown) {
4165 mLockScreenShown = false;
4166 comeOutOfSleepIfNeededLocked();
4167 }
4168 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004169 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004170 } finally {
4171 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004172 }
4173 }
4174
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004175 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004176 IntentFilter pkgFilter = new IntentFilter();
4177 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4178 pkgFilter.addDataScheme("package");
4179 mContext.registerReceiver(new BroadcastReceiver() {
4180 @Override
4181 public void onReceive(Context context, Intent intent) {
4182 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4183 if (pkgs != null) {
4184 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004185 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004186 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4187 setResultCode(Activity.RESULT_OK);
4188 return;
4189 }
4190 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004191 }
4192 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004193 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004194 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004195
4196 IntentFilter userFilter = new IntentFilter();
4197 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4198 mContext.registerReceiver(new BroadcastReceiver() {
4199 @Override
4200 public void onReceive(Context context, Intent intent) {
4201 onUserRemoved(intent);
4202 }
4203 }, userFilter);
4204
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004205 synchronized (this) {
4206 // Ensure that any processes we had put on hold are now started
4207 // up.
4208 final int NP = mProcessesOnHold.size();
4209 if (NP > 0) {
4210 ArrayList<ProcessRecord> procs =
4211 new ArrayList<ProcessRecord>(mProcessesOnHold);
4212 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004213 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4214 + procs.get(ip));
4215 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004216 }
4217 }
4218
4219 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004220 // Start looking for apps that are abusing wake locks.
4221 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004222 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004223 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004224 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004225 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani258848d2012-08-10 17:06:33 -07004226 List<UserInfo> users = getUserManager().getUsers();
4227 for (UserInfo user : users) {
4228 broadcastIntentLocked(null, null,
4229 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4230 null, null, 0, null, null,
4231 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
4232 false, false, MY_PID, Process.SYSTEM_UID, user.id);
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004233 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004234 }
4235 }
4236 }
4237
4238 final void ensureBootCompleted() {
4239 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004240 boolean enableScreen;
4241 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004242 booting = mBooting;
4243 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004244 enableScreen = !mBooted;
4245 mBooted = true;
4246 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004247
4248 if (booting) {
4249 finishBooting();
4250 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004251
4252 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004253 enableScreenAfterBoot();
4254 }
4255 }
4256
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004257 public final void activityPaused(IBinder token) {
4258 final long origId = Binder.clearCallingIdentity();
4259 mMainStack.activityPaused(token, false);
4260 Binder.restoreCallingIdentity(origId);
4261 }
4262
4263 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4264 CharSequence description) {
4265 if (localLOGV) Slog.v(
4266 TAG, "Activity stopped: token=" + token);
4267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004268 // Refuse possible leaked file descriptors
4269 if (icicle != null && icicle.hasFileDescriptors()) {
4270 throw new IllegalArgumentException("File descriptors passed in Bundle");
4271 }
4272
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004273 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004274
4275 final long origId = Binder.clearCallingIdentity();
4276
4277 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004278 r = mMainStack.isInStackLocked(token);
4279 if (r != null) {
4280 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 }
4282 }
4283
4284 if (r != null) {
4285 sendPendingThumbnail(r, null, null, null, false);
4286 }
4287
4288 trimApplications();
4289
4290 Binder.restoreCallingIdentity(origId);
4291 }
4292
4293 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004294 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004295 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 }
4297
4298 public String getCallingPackage(IBinder token) {
4299 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004300 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004301 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 }
4303 }
4304
4305 public ComponentName getCallingActivity(IBinder token) {
4306 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004307 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 return r != null ? r.intent.getComponent() : null;
4309 }
4310 }
4311
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004312 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004313 ActivityRecord r = mMainStack.isInStackLocked(token);
4314 if (r == null) {
4315 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004317 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004318 }
4319
4320 public ComponentName getActivityClassForToken(IBinder token) {
4321 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004322 ActivityRecord r = mMainStack.isInStackLocked(token);
4323 if (r == null) {
4324 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004326 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 }
4328 }
4329
4330 public String getPackageForToken(IBinder token) {
4331 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004332 ActivityRecord r = mMainStack.isInStackLocked(token);
4333 if (r == null) {
4334 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004336 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004337 }
4338 }
4339
4340 public IIntentSender getIntentSender(int type,
4341 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004342 int requestCode, Intent[] intents, String[] resolvedTypes,
4343 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004344 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004346 if (intents != null) {
4347 if (intents.length < 1) {
4348 throw new IllegalArgumentException("Intents array length must be >= 1");
4349 }
4350 for (int i=0; i<intents.length; i++) {
4351 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004352 if (intent != null) {
4353 if (intent.hasFileDescriptors()) {
4354 throw new IllegalArgumentException("File descriptors passed in Intent");
4355 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004356 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004357 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4358 throw new IllegalArgumentException(
4359 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4360 }
4361 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004362 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004363 }
4364 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004365 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004366 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004367 }
4368 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004369 if (options != null) {
4370 if (options.hasFileDescriptors()) {
4371 throw new IllegalArgumentException("File descriptors passed in options");
4372 }
4373 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 synchronized(this) {
4376 int callingUid = Binder.getCallingUid();
4377 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004378 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004379 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004380 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4381 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 String msg = "Permission Denial: getIntentSender() from pid="
4383 + Binder.getCallingPid()
4384 + ", uid=" + Binder.getCallingUid()
4385 + ", (need uid=" + uid + ")"
4386 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004387 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 throw new SecurityException(msg);
4389 }
4390 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004391
Amith Yamasani742a6712011-05-04 14:49:28 -07004392 if (DEBUG_MU)
4393 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4394 + Binder.getOrigCallingUid());
4395 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004396 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004398 } catch (RemoteException e) {
4399 throw new SecurityException(e);
4400 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004401 }
4402 }
4403
4404 IIntentSender getIntentSenderLocked(int type,
4405 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004406 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4407 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004408 if (DEBUG_MU)
4409 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004410 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004411 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004412 activity = mMainStack.isInStackLocked(token);
4413 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004414 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004416 if (activity.finishing) {
4417 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004419 }
4420
4421 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4422 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4423 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4424 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4425 |PendingIntent.FLAG_UPDATE_CURRENT);
4426
4427 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4428 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004429 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004430 WeakReference<PendingIntentRecord> ref;
4431 ref = mIntentSenderRecords.get(key);
4432 PendingIntentRecord rec = ref != null ? ref.get() : null;
4433 if (rec != null) {
4434 if (!cancelCurrent) {
4435 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004436 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004437 rec.key.requestIntent.replaceExtras(intents != null ?
4438 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004439 }
4440 if (intents != null) {
4441 intents[intents.length-1] = rec.key.requestIntent;
4442 rec.key.allIntents = intents;
4443 rec.key.allResolvedTypes = resolvedTypes;
4444 } else {
4445 rec.key.allIntents = null;
4446 rec.key.allResolvedTypes = null;
4447 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004449 return rec;
4450 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004451 rec.canceled = true;
4452 mIntentSenderRecords.remove(key);
4453 }
4454 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004455 return rec;
4456 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004457 rec = new PendingIntentRecord(this, key, callingUid);
4458 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004459 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004460 if (activity.pendingResults == null) {
4461 activity.pendingResults
4462 = new HashSet<WeakReference<PendingIntentRecord>>();
4463 }
4464 activity.pendingResults.add(rec.ref);
4465 }
4466 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 }
4468
4469 public void cancelIntentSender(IIntentSender sender) {
4470 if (!(sender instanceof PendingIntentRecord)) {
4471 return;
4472 }
4473 synchronized(this) {
4474 PendingIntentRecord rec = (PendingIntentRecord)sender;
4475 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004476 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004477 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4478 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 String msg = "Permission Denial: cancelIntentSender() from pid="
4480 + Binder.getCallingPid()
4481 + ", uid=" + Binder.getCallingUid()
4482 + " is not allowed to cancel packges "
4483 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004484 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 throw new SecurityException(msg);
4486 }
4487 } catch (RemoteException e) {
4488 throw new SecurityException(e);
4489 }
4490 cancelIntentSenderLocked(rec, true);
4491 }
4492 }
4493
4494 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4495 rec.canceled = true;
4496 mIntentSenderRecords.remove(rec.key);
4497 if (cleanActivity && rec.key.activity != null) {
4498 rec.key.activity.pendingResults.remove(rec.ref);
4499 }
4500 }
4501
4502 public String getPackageForIntentSender(IIntentSender pendingResult) {
4503 if (!(pendingResult instanceof PendingIntentRecord)) {
4504 return null;
4505 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004506 try {
4507 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4508 return res.key.packageName;
4509 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 return null;
4512 }
4513
Christopher Tatec4a07d12012-04-06 14:19:13 -07004514 public int getUidForIntentSender(IIntentSender sender) {
4515 if (sender instanceof PendingIntentRecord) {
4516 try {
4517 PendingIntentRecord res = (PendingIntentRecord)sender;
4518 return res.uid;
4519 } catch (ClassCastException e) {
4520 }
4521 }
4522 return -1;
4523 }
4524
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004525 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4526 if (!(pendingResult instanceof PendingIntentRecord)) {
4527 return false;
4528 }
4529 try {
4530 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4531 if (res.key.allIntents == null) {
4532 return false;
4533 }
4534 for (int i=0; i<res.key.allIntents.length; i++) {
4535 Intent intent = res.key.allIntents[i];
4536 if (intent.getPackage() != null && intent.getComponent() != null) {
4537 return false;
4538 }
4539 }
4540 return true;
4541 } catch (ClassCastException e) {
4542 }
4543 return false;
4544 }
4545
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004546 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4547 if (!(pendingResult instanceof PendingIntentRecord)) {
4548 return false;
4549 }
4550 try {
4551 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4552 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4553 return true;
4554 }
4555 return false;
4556 } catch (ClassCastException e) {
4557 }
4558 return false;
4559 }
4560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 public void setProcessLimit(int max) {
4562 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4563 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004564 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004565 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004566 mProcessLimitOverride = max;
4567 }
4568 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004569 }
4570
4571 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004572 synchronized (this) {
4573 return mProcessLimitOverride;
4574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
4576
4577 void foregroundTokenDied(ForegroundToken token) {
4578 synchronized (ActivityManagerService.this) {
4579 synchronized (mPidsSelfLocked) {
4580 ForegroundToken cur
4581 = mForegroundProcesses.get(token.pid);
4582 if (cur != token) {
4583 return;
4584 }
4585 mForegroundProcesses.remove(token.pid);
4586 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4587 if (pr == null) {
4588 return;
4589 }
4590 pr.forcingToForeground = null;
4591 pr.foregroundServices = false;
4592 }
4593 updateOomAdjLocked();
4594 }
4595 }
4596
4597 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4598 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4599 "setProcessForeground()");
4600 synchronized(this) {
4601 boolean changed = false;
4602
4603 synchronized (mPidsSelfLocked) {
4604 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004605 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004606 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004607 return;
4608 }
4609 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4610 if (oldToken != null) {
4611 oldToken.token.unlinkToDeath(oldToken, 0);
4612 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004613 if (pr != null) {
4614 pr.forcingToForeground = null;
4615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004616 changed = true;
4617 }
4618 if (isForeground && token != null) {
4619 ForegroundToken newToken = new ForegroundToken() {
4620 public void binderDied() {
4621 foregroundTokenDied(this);
4622 }
4623 };
4624 newToken.pid = pid;
4625 newToken.token = token;
4626 try {
4627 token.linkToDeath(newToken, 0);
4628 mForegroundProcesses.put(pid, newToken);
4629 pr.forcingToForeground = token;
4630 changed = true;
4631 } catch (RemoteException e) {
4632 // If the process died while doing this, we will later
4633 // do the cleanup with the process death link.
4634 }
4635 }
4636 }
4637
4638 if (changed) {
4639 updateOomAdjLocked();
4640 }
4641 }
4642 }
4643
4644 // =========================================================
4645 // PERMISSIONS
4646 // =========================================================
4647
4648 static class PermissionController extends IPermissionController.Stub {
4649 ActivityManagerService mActivityManagerService;
4650 PermissionController(ActivityManagerService activityManagerService) {
4651 mActivityManagerService = activityManagerService;
4652 }
4653
4654 public boolean checkPermission(String permission, int pid, int uid) {
4655 return mActivityManagerService.checkPermission(permission, pid,
4656 uid) == PackageManager.PERMISSION_GRANTED;
4657 }
4658 }
4659
4660 /**
4661 * This can be called with or without the global lock held.
4662 */
4663 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004664 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 // We might be performing an operation on behalf of an indirect binder
4666 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4667 // client identity accordingly before proceeding.
4668 Identity tlsIdentity = sCallerIdentity.get();
4669 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004670 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004671 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4672 uid = tlsIdentity.uid;
4673 pid = tlsIdentity.pid;
4674 }
4675
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004676 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004677 return PackageManager.PERMISSION_GRANTED;
4678 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004679
4680 return ActivityManager.checkComponentPermission(permission, uid,
4681 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 }
4683
4684 /**
4685 * As the only public entry point for permissions checking, this method
4686 * can enforce the semantic that requesting a check on a null global
4687 * permission is automatically denied. (Internally a null permission
4688 * string is used when calling {@link #checkComponentPermission} in cases
4689 * when only uid-based security is needed.)
4690 *
4691 * This can be called with or without the global lock held.
4692 */
4693 public int checkPermission(String permission, int pid, int uid) {
4694 if (permission == null) {
4695 return PackageManager.PERMISSION_DENIED;
4696 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004697 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 }
4699
4700 /**
4701 * Binder IPC calls go through the public entry point.
4702 * This can be called with or without the global lock held.
4703 */
4704 int checkCallingPermission(String permission) {
4705 return checkPermission(permission,
4706 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004707 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 }
4709
4710 /**
4711 * This can be called with or without the global lock held.
4712 */
4713 void enforceCallingPermission(String permission, String func) {
4714 if (checkCallingPermission(permission)
4715 == PackageManager.PERMISSION_GRANTED) {
4716 return;
4717 }
4718
4719 String msg = "Permission Denial: " + func + " from pid="
4720 + Binder.getCallingPid()
4721 + ", uid=" + Binder.getCallingUid()
4722 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004723 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 throw new SecurityException(msg);
4725 }
4726
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004727 /**
4728 * Determine if UID is holding permissions required to access {@link Uri} in
4729 * the given {@link ProviderInfo}. Final permission checking is always done
4730 * in {@link ContentProvider}.
4731 */
4732 private final boolean checkHoldingPermissionsLocked(
4733 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004734 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4735 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004736
4737 if (pi.applicationInfo.uid == uid) {
4738 return true;
4739 } else if (!pi.exported) {
4740 return false;
4741 }
4742
4743 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4744 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004745 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004746 // check if target holds top-level <provider> permissions
4747 if (!readMet && pi.readPermission != null
4748 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4749 readMet = true;
4750 }
4751 if (!writeMet && pi.writePermission != null
4752 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4753 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004754 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004755
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004756 // track if unprotected read/write is allowed; any denied
4757 // <path-permission> below removes this ability
4758 boolean allowDefaultRead = pi.readPermission == null;
4759 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004760
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004761 // check if target holds any <path-permission> that match uri
4762 final PathPermission[] pps = pi.pathPermissions;
4763 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004764 final String path = uri.getPath();
4765 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004766 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004767 i--;
4768 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004769 if (pp.match(path)) {
4770 if (!readMet) {
4771 final String pprperm = pp.getReadPermission();
4772 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4773 + pprperm + " for " + pp.getPath()
4774 + ": match=" + pp.match(path)
4775 + " check=" + pm.checkUidPermission(pprperm, uid));
4776 if (pprperm != null) {
4777 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4778 readMet = true;
4779 } else {
4780 allowDefaultRead = false;
4781 }
4782 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004783 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004784 if (!writeMet) {
4785 final String ppwperm = pp.getWritePermission();
4786 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4787 + ppwperm + " for " + pp.getPath()
4788 + ": match=" + pp.match(path)
4789 + " check=" + pm.checkUidPermission(ppwperm, uid));
4790 if (ppwperm != null) {
4791 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4792 writeMet = true;
4793 } else {
4794 allowDefaultWrite = false;
4795 }
4796 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004797 }
4798 }
4799 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004800 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004801
4802 // grant unprotected <provider> read/write, if not blocked by
4803 // <path-permission> above
4804 if (allowDefaultRead) readMet = true;
4805 if (allowDefaultWrite) writeMet = true;
4806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 } catch (RemoteException e) {
4808 return false;
4809 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004810
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004811 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 }
4813
4814 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4815 int modeFlags) {
4816 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004817 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 return true;
4819 }
4820 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4821 if (perms == null) return false;
4822 UriPermission perm = perms.get(uri);
4823 if (perm == null) return false;
4824 return (modeFlags&perm.modeFlags) == modeFlags;
4825 }
4826
4827 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004828 enforceNotIsolatedCaller("checkUriPermission");
4829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004830 // Another redirected-binder-call permissions check as in
4831 // {@link checkComponentPermission}.
4832 Identity tlsIdentity = sCallerIdentity.get();
4833 if (tlsIdentity != null) {
4834 uid = tlsIdentity.uid;
4835 pid = tlsIdentity.pid;
4836 }
4837
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004838 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004839 // Our own process gets to do everything.
4840 if (pid == MY_PID) {
4841 return PackageManager.PERMISSION_GRANTED;
4842 }
4843 synchronized(this) {
4844 return checkUriPermissionLocked(uri, uid, modeFlags)
4845 ? PackageManager.PERMISSION_GRANTED
4846 : PackageManager.PERMISSION_DENIED;
4847 }
4848 }
4849
Dianne Hackborn39792d22010-08-19 18:01:52 -07004850 /**
4851 * Check if the targetPkg can be granted permission to access uri by
4852 * the callingUid using the given modeFlags. Throws a security exception
4853 * if callingUid is not allowed to do this. Returns the uid of the target
4854 * if the URI permission grant should be performed; returns -1 if it is not
4855 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004856 * If you already know the uid of the target, you can supply it in
4857 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004858 */
4859 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004860 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004861 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4862 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4863 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004864 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 }
4866
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004867 if (targetPkg != null) {
4868 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4869 "Checking grant " + targetPkg + " permission to " + uri);
4870 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004871
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004872 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873
4874 // If this is not a content: uri, we can't do anything with it.
4875 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004876 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004877 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004878 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 }
4880
4881 String name = uri.getAuthority();
4882 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004883 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004884 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004885 if (cpr != null) {
4886 pi = cpr.info;
4887 } else {
4888 try {
4889 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004890 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004891 } catch (RemoteException ex) {
4892 }
4893 }
4894 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004895 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004896 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004897 }
4898
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004899 int targetUid = lastTargetUid;
4900 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004901 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004902 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004903 if (targetUid < 0) {
4904 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4905 "Can't grant URI permission no uid for: " + targetPkg);
4906 return -1;
4907 }
4908 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004909 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004911 }
4912
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004913 if (targetUid >= 0) {
4914 // First... does the target actually need this permission?
4915 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4916 // No need to grant the target this permission.
4917 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4918 "Target " + targetPkg + " already has full permission to " + uri);
4919 return -1;
4920 }
4921 } else {
4922 // First... there is no target package, so can anyone access it?
4923 boolean allowed = pi.exported;
4924 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4925 if (pi.readPermission != null) {
4926 allowed = false;
4927 }
4928 }
4929 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4930 if (pi.writePermission != null) {
4931 allowed = false;
4932 }
4933 }
4934 if (allowed) {
4935 return -1;
4936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004937 }
4938
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004939 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004940 if (!pi.grantUriPermissions) {
4941 throw new SecurityException("Provider " + pi.packageName
4942 + "/" + pi.name
4943 + " does not allow granting of Uri permissions (uri "
4944 + uri + ")");
4945 }
4946 if (pi.uriPermissionPatterns != null) {
4947 final int N = pi.uriPermissionPatterns.length;
4948 boolean allowed = false;
4949 for (int i=0; i<N; i++) {
4950 if (pi.uriPermissionPatterns[i] != null
4951 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4952 allowed = true;
4953 break;
4954 }
4955 }
4956 if (!allowed) {
4957 throw new SecurityException("Provider " + pi.packageName
4958 + "/" + pi.name
4959 + " does not allow granting of permission to path of Uri "
4960 + uri);
4961 }
4962 }
4963
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004964 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004966 if (callingUid != Process.myUid()) {
4967 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4968 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4969 throw new SecurityException("Uid " + callingUid
4970 + " does not have permission to uri " + uri);
4971 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004972 }
4973 }
4974
Dianne Hackborn39792d22010-08-19 18:01:52 -07004975 return targetUid;
4976 }
4977
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004978 public int checkGrantUriPermission(int callingUid, String targetPkg,
4979 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004980 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004981 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004982 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004983 }
4984 }
4985
Dianne Hackborn39792d22010-08-19 18:01:52 -07004986 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4987 Uri uri, int modeFlags, UriPermissionOwner owner) {
4988 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4989 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4990 if (modeFlags == 0) {
4991 return;
4992 }
4993
4994 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 // to the uri, and the target doesn't. Let's now give this to
4996 // the target.
4997
Joe Onorato8a9b2202010-02-26 18:56:32 -08004998 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004999 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005001 HashMap<Uri, UriPermission> targetUris
5002 = mGrantedUriPermissions.get(targetUid);
5003 if (targetUris == null) {
5004 targetUris = new HashMap<Uri, UriPermission>();
5005 mGrantedUriPermissions.put(targetUid, targetUris);
5006 }
5007
5008 UriPermission perm = targetUris.get(uri);
5009 if (perm == null) {
5010 perm = new UriPermission(targetUid, uri);
5011 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005012 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005014 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005015 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005016 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005017 } else {
5018 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5019 perm.readOwners.add(owner);
5020 owner.addReadPermission(perm);
5021 }
5022 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5023 perm.writeOwners.add(owner);
5024 owner.addWritePermission(perm);
5025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
5027 }
5028
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005029 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5030 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005031 if (targetPkg == null) {
5032 throw new NullPointerException("targetPkg");
5033 }
5034
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005035 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005036 if (targetUid < 0) {
5037 return;
5038 }
5039
5040 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5041 }
5042
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005043 static class NeededUriGrants extends ArrayList<Uri> {
5044 final String targetPkg;
5045 final int targetUid;
5046 final int flags;
5047
5048 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5049 targetPkg = _targetPkg;
5050 targetUid = _targetUid;
5051 flags = _flags;
5052 }
5053 }
5054
Dianne Hackborn39792d22010-08-19 18:01:52 -07005055 /**
5056 * Like checkGrantUriPermissionLocked, but takes an Intent.
5057 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005058 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5059 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005060 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005061 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5062 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005063 + " from " + intent + "; flags=0x"
5064 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5065
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005066 if (targetPkg == null) {
5067 throw new NullPointerException("targetPkg");
5068 }
5069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005071 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005072 }
5073 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005074 ClipData clip = intent.getClipData();
5075 if (data == null && clip == null) {
5076 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005077 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005078 if (data != null) {
5079 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5080 mode, needed != null ? needed.targetUid : -1);
5081 if (target > 0) {
5082 if (needed == null) {
5083 needed = new NeededUriGrants(targetPkg, target, mode);
5084 }
5085 needed.add(data);
5086 }
5087 }
5088 if (clip != null) {
5089 for (int i=0; i<clip.getItemCount(); i++) {
5090 Uri uri = clip.getItemAt(i).getUri();
5091 if (uri != null) {
5092 int target = -1;
5093 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5094 mode, needed != null ? needed.targetUid : -1);
5095 if (target > 0) {
5096 if (needed == null) {
5097 needed = new NeededUriGrants(targetPkg, target, mode);
5098 }
5099 needed.add(uri);
5100 }
5101 } else {
5102 Intent clipIntent = clip.getItemAt(i).getIntent();
5103 if (clipIntent != null) {
5104 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5105 callingUid, targetPkg, clipIntent, mode, needed);
5106 if (newNeeded != null) {
5107 needed = newNeeded;
5108 }
5109 }
5110 }
5111 }
5112 }
5113
5114 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005115 }
5116
5117 /**
5118 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5119 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005120 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5121 UriPermissionOwner owner) {
5122 if (needed != null) {
5123 for (int i=0; i<needed.size(); i++) {
5124 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5125 needed.get(i), needed.flags, owner);
5126 }
5127 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005128 }
5129
5130 void grantUriPermissionFromIntentLocked(int callingUid,
5131 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005132 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005133 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005134 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 return;
5136 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005137
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005138 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005139 }
5140
5141 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5142 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005143 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 synchronized(this) {
5145 final ProcessRecord r = getRecordForAppLocked(caller);
5146 if (r == null) {
5147 throw new SecurityException("Unable to find app for caller "
5148 + caller
5149 + " when granting permission to uri " + uri);
5150 }
5151 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005152 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005153 }
5154 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005155 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005156 }
5157
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005158 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 null);
5160 }
5161 }
5162
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005163 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5165 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5166 HashMap<Uri, UriPermission> perms
5167 = mGrantedUriPermissions.get(perm.uid);
5168 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005169 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005170 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005171 perms.remove(perm.uri);
5172 if (perms.size() == 0) {
5173 mGrantedUriPermissions.remove(perm.uid);
5174 }
5175 }
5176 }
5177 }
5178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5180 int modeFlags) {
5181 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5182 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5183 if (modeFlags == 0) {
5184 return;
5185 }
5186
Joe Onorato8a9b2202010-02-26 18:56:32 -08005187 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005188 "Revoking all granted permissions to " + uri);
5189
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005190 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005191
5192 final String authority = uri.getAuthority();
5193 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005194 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005195 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196 if (cpr != null) {
5197 pi = cpr.info;
5198 } else {
5199 try {
5200 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005201 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 } catch (RemoteException ex) {
5203 }
5204 }
5205 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005206 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 return;
5208 }
5209
5210 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005211 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 // Right now, if you are not the original owner of the permission,
5213 // you are not allowed to revoke it.
5214 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5215 throw new SecurityException("Uid " + callingUid
5216 + " does not have permission to uri " + uri);
5217 //}
5218 }
5219
5220 // Go through all of the permissions and remove any that match.
5221 final List<String> SEGMENTS = uri.getPathSegments();
5222 if (SEGMENTS != null) {
5223 final int NS = SEGMENTS.size();
5224 int N = mGrantedUriPermissions.size();
5225 for (int i=0; i<N; i++) {
5226 HashMap<Uri, UriPermission> perms
5227 = mGrantedUriPermissions.valueAt(i);
5228 Iterator<UriPermission> it = perms.values().iterator();
5229 toploop:
5230 while (it.hasNext()) {
5231 UriPermission perm = it.next();
5232 Uri targetUri = perm.uri;
5233 if (!authority.equals(targetUri.getAuthority())) {
5234 continue;
5235 }
5236 List<String> targetSegments = targetUri.getPathSegments();
5237 if (targetSegments == null) {
5238 continue;
5239 }
5240 if (targetSegments.size() < NS) {
5241 continue;
5242 }
5243 for (int j=0; j<NS; j++) {
5244 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5245 continue toploop;
5246 }
5247 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005248 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005249 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005250 perm.clearModes(modeFlags);
5251 if (perm.modeFlags == 0) {
5252 it.remove();
5253 }
5254 }
5255 if (perms.size() == 0) {
5256 mGrantedUriPermissions.remove(
5257 mGrantedUriPermissions.keyAt(i));
5258 N--;
5259 i--;
5260 }
5261 }
5262 }
5263 }
5264
5265 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5266 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005267 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 synchronized(this) {
5269 final ProcessRecord r = getRecordForAppLocked(caller);
5270 if (r == null) {
5271 throw new SecurityException("Unable to find app for caller "
5272 + caller
5273 + " when revoking permission to uri " + uri);
5274 }
5275 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005276 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 return;
5278 }
5279
5280 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5281 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5282 if (modeFlags == 0) {
5283 return;
5284 }
5285
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005286 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287
5288 final String authority = uri.getAuthority();
5289 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005290 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 if (cpr != null) {
5292 pi = cpr.info;
5293 } else {
5294 try {
5295 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005296 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005297 } catch (RemoteException ex) {
5298 }
5299 }
5300 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005301 Slog.w(TAG, "No content provider found for permission revoke: "
5302 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 return;
5304 }
5305
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005306 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005307 }
5308 }
5309
Dianne Hackborn7e269642010-08-25 19:50:20 -07005310 @Override
5311 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005312 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005313 synchronized(this) {
5314 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5315 return owner.getExternalTokenLocked();
5316 }
5317 }
5318
5319 @Override
5320 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5321 Uri uri, int modeFlags) {
5322 synchronized(this) {
5323 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5324 if (owner == null) {
5325 throw new IllegalArgumentException("Unknown owner: " + token);
5326 }
5327 if (fromUid != Binder.getCallingUid()) {
5328 if (Binder.getCallingUid() != Process.myUid()) {
5329 // Only system code can grant URI permissions on behalf
5330 // of other users.
5331 throw new SecurityException("nice try");
5332 }
5333 }
5334 if (targetPkg == null) {
5335 throw new IllegalArgumentException("null target");
5336 }
5337 if (uri == null) {
5338 throw new IllegalArgumentException("null uri");
5339 }
5340
5341 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5342 }
5343 }
5344
5345 @Override
5346 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5347 synchronized(this) {
5348 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5349 if (owner == null) {
5350 throw new IllegalArgumentException("Unknown owner: " + token);
5351 }
5352
5353 if (uri == null) {
5354 owner.removeUriPermissionsLocked(mode);
5355 } else {
5356 owner.removeUriPermissionLocked(uri, mode);
5357 }
5358 }
5359 }
5360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005361 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5362 synchronized (this) {
5363 ProcessRecord app =
5364 who != null ? getRecordForAppLocked(who) : null;
5365 if (app == null) return;
5366
5367 Message msg = Message.obtain();
5368 msg.what = WAIT_FOR_DEBUGGER_MSG;
5369 msg.obj = app;
5370 msg.arg1 = waiting ? 1 : 0;
5371 mHandler.sendMessage(msg);
5372 }
5373 }
5374
5375 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005376 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5377 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005379 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005380 outInfo.threshold = homeAppMem;
5381 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5382 outInfo.hiddenAppThreshold = hiddenAppMem;
5383 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005384 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005385 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5386 ProcessList.VISIBLE_APP_ADJ);
5387 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5388 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005389 }
5390
5391 // =========================================================
5392 // TASK MANAGEMENT
5393 // =========================================================
5394
5395 public List getTasks(int maxNum, int flags,
5396 IThumbnailReceiver receiver) {
5397 ArrayList list = new ArrayList();
5398
5399 PendingThumbnailsRecord pending = null;
5400 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005401 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402
5403 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005404 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005405 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5406 + ", receiver=" + receiver);
5407
5408 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5409 != PackageManager.PERMISSION_GRANTED) {
5410 if (receiver != null) {
5411 // If the caller wants to wait for pending thumbnails,
5412 // it ain't gonna get them.
5413 try {
5414 receiver.finished();
5415 } catch (RemoteException ex) {
5416 }
5417 }
5418 String msg = "Permission Denial: getTasks() from pid="
5419 + Binder.getCallingPid()
5420 + ", uid=" + Binder.getCallingUid()
5421 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005422 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 throw new SecurityException(msg);
5424 }
5425
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005426 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005427 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005428 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005429 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005430 TaskRecord curTask = null;
5431 int numActivities = 0;
5432 int numRunning = 0;
5433 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005434 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005436 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437
5438 // Initialize state for next task if needed.
5439 if (top == null ||
5440 (top.state == ActivityState.INITIALIZING
5441 && top.task == r.task)) {
5442 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 curTask = r.task;
5444 numActivities = numRunning = 0;
5445 }
5446
5447 // Add 'r' into the current task.
5448 numActivities++;
5449 if (r.app != null && r.app.thread != null) {
5450 numRunning++;
5451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452
Joe Onorato8a9b2202010-02-26 18:56:32 -08005453 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 TAG, r.intent.getComponent().flattenToShortString()
5455 + ": task=" + r.task);
5456
5457 // If the next one is a different task, generate a new
5458 // TaskInfo entry for what we have.
5459 if (next == null || next.task != curTask) {
5460 ActivityManager.RunningTaskInfo ci
5461 = new ActivityManager.RunningTaskInfo();
5462 ci.id = curTask.taskId;
5463 ci.baseActivity = r.intent.getComponent();
5464 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005465 if (top.thumbHolder != null) {
5466 ci.description = top.thumbHolder.lastDescription;
5467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 ci.numActivities = numActivities;
5469 ci.numRunning = numRunning;
5470 //System.out.println(
5471 // "#" + maxNum + ": " + " descr=" + ci.description);
5472 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005473 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 TAG, "State=" + top.state + "Idle=" + top.idle
5475 + " app=" + top.app
5476 + " thr=" + (top.app != null ? top.app.thread : null));
5477 if (top.state == ActivityState.RESUMED
5478 || top.state == ActivityState.PAUSING) {
5479 if (top.idle && top.app != null
5480 && top.app.thread != null) {
5481 topRecord = top;
5482 topThumbnail = top.app.thread;
5483 } else {
5484 top.thumbnailNeeded = true;
5485 }
5486 }
5487 if (pending == null) {
5488 pending = new PendingThumbnailsRecord(receiver);
5489 }
5490 pending.pendingRecords.add(top);
5491 }
5492 list.add(ci);
5493 maxNum--;
5494 top = null;
5495 }
5496 }
5497
5498 if (pending != null) {
5499 mPendingThumbnails.add(pending);
5500 }
5501 }
5502
Joe Onorato8a9b2202010-02-26 18:56:32 -08005503 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504
5505 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005506 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005508 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005510 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005511 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 }
5513 }
5514
5515 if (pending == null && receiver != null) {
5516 // In this case all thumbnails were available and the client
5517 // is being asked to be told when the remaining ones come in...
5518 // which is unusually, since the top-most currently running
5519 // activity should never have a canned thumbnail! Oh well.
5520 try {
5521 receiver.finished();
5522 } catch (RemoteException ex) {
5523 }
5524 }
5525
5526 return list;
5527 }
5528
5529 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005530 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005531 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005532 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005533 // Check if the caller is holding permissions for cross-user requests.
5534 if (checkComponentPermission(
5535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5536 Binder.getCallingPid(), callingUid, -1, true)
5537 != PackageManager.PERMISSION_GRANTED) {
5538 String msg = "Permission Denial: "
5539 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005540 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005541 + "; this requires "
5542 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5543 Slog.w(TAG, msg);
5544 throw new SecurityException(msg);
5545 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005546 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005547 userId = mCurrentUserId;
5548 }
5549 }
5550 }
5551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 synchronized (this) {
5553 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5554 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005555 final boolean detailed = checkCallingPermission(
5556 android.Manifest.permission.GET_DETAILED_TASKS)
5557 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005559 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 final int N = mRecentTasks.size();
5562 ArrayList<ActivityManager.RecentTaskInfo> res
5563 = new ArrayList<ActivityManager.RecentTaskInfo>(
5564 maxNum < N ? maxNum : N);
5565 for (int i=0; i<N && maxNum > 0; i++) {
5566 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005567 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005568 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005569 // Return the entry if desired by the caller. We always return
5570 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005571 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005572 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5573 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005574
Dianne Hackborn905577f2011-09-07 18:31:28 -07005575 if (i == 0
5576 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 || (tr.intent == null)
5578 || ((tr.intent.getFlags()
5579 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5580 ActivityManager.RecentTaskInfo rti
5581 = new ActivityManager.RecentTaskInfo();
5582 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005583 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 rti.baseIntent = new Intent(
5585 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005586 if (!detailed) {
5587 rti.baseIntent.replaceExtras((Bundle)null);
5588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005590 rti.description = tr.lastDescription;
5591
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005592 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5593 // Check whether this activity is currently available.
5594 try {
5595 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005596 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005597 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005598 continue;
5599 }
5600 } else if (rti.baseIntent != null) {
5601 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005602 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005603 continue;
5604 }
5605 }
5606 } catch (RemoteException e) {
5607 // Will never happen.
5608 }
5609 }
5610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 res.add(rti);
5612 maxNum--;
5613 }
5614 }
5615 return res;
5616 }
5617 }
5618
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619 private TaskRecord taskForIdLocked(int id) {
5620 final int N = mRecentTasks.size();
5621 for (int i=0; i<N; i++) {
5622 TaskRecord tr = mRecentTasks.get(i);
5623 if (tr.taskId == id) {
5624 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005625 }
5626 }
5627 return null;
5628 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005629
5630 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5631 synchronized (this) {
5632 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5633 "getTaskThumbnails()");
5634 TaskRecord tr = taskForIdLocked(id);
5635 if (tr != null) {
5636 return mMainStack.getTaskThumbnailsLocked(tr);
5637 }
5638 }
5639 return null;
5640 }
5641
5642 public boolean removeSubTask(int taskId, int subTaskIndex) {
5643 synchronized (this) {
5644 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5645 "removeSubTask()");
5646 long ident = Binder.clearCallingIdentity();
5647 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005648 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5649 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005650 } finally {
5651 Binder.restoreCallingIdentity(ident);
5652 }
5653 }
5654 }
5655
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005656 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5657 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005658 Intent baseIntent = new Intent(
5659 tr.intent != null ? tr.intent : tr.affinityIntent);
5660 ComponentName component = baseIntent.getComponent();
5661 if (component == null) {
5662 Slog.w(TAG, "Now component for base intent of task: " + tr);
5663 return;
5664 }
5665
5666 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005667 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005668
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005669 if (killProcesses) {
5670 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005671 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005672 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005673 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5674 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5675 for (int i=0; i<uids.size(); i++) {
5676 ProcessRecord proc = uids.valueAt(i);
5677 if (proc.userId != tr.userId) {
5678 continue;
5679 }
5680 if (!proc.pkgList.contains(pkg)) {
5681 continue;
5682 }
5683 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005684 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005685 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005686
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005687 // Kill the running processes.
5688 for (int i=0; i<procs.size(); i++) {
5689 ProcessRecord pr = procs.get(i);
5690 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5691 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5692 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5693 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005694 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005695 Process.killProcessQuiet(pr.pid);
5696 } else {
5697 pr.waitingToKill = "remove task";
5698 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005699 }
5700 }
5701 }
5702
5703 public boolean removeTask(int taskId, int flags) {
5704 synchronized (this) {
5705 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5706 "removeTask()");
5707 long ident = Binder.clearCallingIdentity();
5708 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005709 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5710 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005711 if (r != null) {
5712 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005713 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005714 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005715 } else {
5716 TaskRecord tr = null;
5717 int i=0;
5718 while (i < mRecentTasks.size()) {
5719 TaskRecord t = mRecentTasks.get(i);
5720 if (t.taskId == taskId) {
5721 tr = t;
5722 break;
5723 }
5724 i++;
5725 }
5726 if (tr != null) {
5727 if (tr.numActivities <= 0) {
5728 // Caller is just removing a recent task that is
5729 // not actively running. That is easy!
5730 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005731 cleanUpRemovedTaskLocked(tr, flags);
5732 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005733 } else {
5734 Slog.w(TAG, "removeTask: task " + taskId
5735 + " does not have activities to remove, "
5736 + " but numActivities=" + tr.numActivities
5737 + ": " + tr);
5738 }
5739 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005740 }
5741 } finally {
5742 Binder.restoreCallingIdentity(ident);
5743 }
5744 }
5745 return false;
5746 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5749 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005750 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 TaskRecord jt = startTask;
5752
5753 // First look backwards
5754 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005755 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 if (r.task != jt) {
5757 jt = r.task;
5758 if (affinity.equals(jt.affinity)) {
5759 return j;
5760 }
5761 }
5762 }
5763
5764 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005765 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766 jt = startTask;
5767 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005768 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 if (r.task != jt) {
5770 if (affinity.equals(jt.affinity)) {
5771 return j;
5772 }
5773 jt = r.task;
5774 }
5775 }
5776
5777 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005778 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 return N-1;
5780 }
5781
5782 return -1;
5783 }
5784
5785 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005786 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005788 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5790 "moveTaskToFront()");
5791
5792 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005793 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5794 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005795 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005796 return;
5797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 final long origId = Binder.clearCallingIdentity();
5799 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005800 TaskRecord tr = taskForIdLocked(task);
5801 if (tr != null) {
5802 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5803 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005805 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5806 // Caller wants the home activity moved with it. To accomplish this,
5807 // we'll just move the home task to the top first.
5808 mMainStack.moveHomeToFrontLocked();
5809 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005810 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005811 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005813 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5814 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005816 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5817 mMainStack.mUserLeaving = true;
5818 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005819 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5820 // Caller wants the home activity moved with it. To accomplish this,
5821 // we'll just move the home task to the top first.
5822 mMainStack.moveHomeToFrontLocked();
5823 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005824 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005825 return;
5826 }
5827 }
5828 } finally {
5829 Binder.restoreCallingIdentity(origId);
5830 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005831 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 }
5833 }
5834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 public void moveTaskToBack(int task) {
5836 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5837 "moveTaskToBack()");
5838
5839 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005840 if (mMainStack.mResumedActivity != null
5841 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005842 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5843 Binder.getCallingUid(), "Task to back")) {
5844 return;
5845 }
5846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005848 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 Binder.restoreCallingIdentity(origId);
5850 }
5851 }
5852
5853 /**
5854 * Moves an activity, and all of the other activities within the same task, to the bottom
5855 * of the history stack. The activity's order within the task is unchanged.
5856 *
5857 * @param token A reference to the activity we wish to move
5858 * @param nonRoot If false then this only works if the activity is the root
5859 * of a task; if true it will work for any activity in a task.
5860 * @return Returns true if the move completed, false if not.
5861 */
5862 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005863 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 synchronized(this) {
5865 final long origId = Binder.clearCallingIdentity();
5866 int taskId = getTaskForActivityLocked(token, !nonRoot);
5867 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005868 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 }
5870 Binder.restoreCallingIdentity(origId);
5871 }
5872 return false;
5873 }
5874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 public void moveTaskBackwards(int task) {
5876 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5877 "moveTaskBackwards()");
5878
5879 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005880 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5881 Binder.getCallingUid(), "Task backwards")) {
5882 return;
5883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 final long origId = Binder.clearCallingIdentity();
5885 moveTaskBackwardsLocked(task);
5886 Binder.restoreCallingIdentity(origId);
5887 }
5888 }
5889
5890 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005891 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
5893
5894 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5895 synchronized(this) {
5896 return getTaskForActivityLocked(token, onlyRoot);
5897 }
5898 }
5899
5900 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005901 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 TaskRecord lastTask = null;
5903 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005904 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005905 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 if (!onlyRoot || lastTask != r.task) {
5907 return r.task.taskId;
5908 }
5909 return -1;
5910 }
5911 lastTask = r.task;
5912 }
5913
5914 return -1;
5915 }
5916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 // =========================================================
5918 // THUMBNAILS
5919 // =========================================================
5920
5921 public void reportThumbnail(IBinder token,
5922 Bitmap thumbnail, CharSequence description) {
5923 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5924 final long origId = Binder.clearCallingIdentity();
5925 sendPendingThumbnail(null, token, thumbnail, description, true);
5926 Binder.restoreCallingIdentity(origId);
5927 }
5928
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005929 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 Bitmap thumbnail, CharSequence description, boolean always) {
5931 TaskRecord task = null;
5932 ArrayList receivers = null;
5933
5934 //System.out.println("Send pending thumbnail: " + r);
5935
5936 synchronized(this) {
5937 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005938 r = mMainStack.isInStackLocked(token);
5939 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 return;
5941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005943 if (thumbnail == null && r.thumbHolder != null) {
5944 thumbnail = r.thumbHolder.lastThumbnail;
5945 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
5947 if (thumbnail == null && !always) {
5948 // If there is no thumbnail, and this entry is not actually
5949 // going away, then abort for now and pick up the next
5950 // thumbnail we get.
5951 return;
5952 }
5953 task = r.task;
5954
5955 int N = mPendingThumbnails.size();
5956 int i=0;
5957 while (i<N) {
5958 PendingThumbnailsRecord pr =
5959 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5960 //System.out.println("Looking in " + pr.pendingRecords);
5961 if (pr.pendingRecords.remove(r)) {
5962 if (receivers == null) {
5963 receivers = new ArrayList();
5964 }
5965 receivers.add(pr);
5966 if (pr.pendingRecords.size() == 0) {
5967 pr.finished = true;
5968 mPendingThumbnails.remove(i);
5969 N--;
5970 continue;
5971 }
5972 }
5973 i++;
5974 }
5975 }
5976
5977 if (receivers != null) {
5978 final int N = receivers.size();
5979 for (int i=0; i<N; i++) {
5980 try {
5981 PendingThumbnailsRecord pr =
5982 (PendingThumbnailsRecord)receivers.get(i);
5983 pr.receiver.newThumbnail(
5984 task != null ? task.taskId : -1, thumbnail, description);
5985 if (pr.finished) {
5986 pr.receiver.finished();
5987 }
5988 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005989 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005990 }
5991 }
5992 }
5993 }
5994
5995 // =========================================================
5996 // CONTENT PROVIDERS
5997 // =========================================================
5998
Jeff Brown10e89712011-07-08 18:52:57 -07005999 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6000 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006002 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006003 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006004 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 } catch (RemoteException ex) {
6006 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006007 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006008 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6009 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006011 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 for (int i=0; i<N; i++) {
6013 ProviderInfo cpi =
6014 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006015 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6016 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006017 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006018 // This is a singleton provider, but a user besides the
6019 // default user is asking to initialize a process it runs
6020 // in... well, no, it doesn't actually run in this process,
6021 // it runs in the process of the default user. Get rid of it.
6022 providers.remove(i);
6023 N--;
6024 continue;
6025 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006026
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006027 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006028 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006030 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006031 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006033 if (DEBUG_MU)
6034 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 app.pubProviders.put(cpi.name, cpr);
6036 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006037 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 }
6039 }
6040 return providers;
6041 }
6042
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006043 /**
6044 * Check if {@link ProcessRecord} has a possible chance at accessing the
6045 * given {@link ProviderInfo}. Final permission checking is always done
6046 * in {@link ContentProvider}.
6047 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006049 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006051 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006053 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006054 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 return null;
6056 }
6057 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006058 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 == PackageManager.PERMISSION_GRANTED) {
6060 return null;
6061 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006062
6063 PathPermission[] pps = cpi.pathPermissions;
6064 if (pps != null) {
6065 int i = pps.length;
6066 while (i > 0) {
6067 i--;
6068 PathPermission pp = pps[i];
6069 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006070 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006071 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006072 return null;
6073 }
6074 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006075 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006076 == PackageManager.PERMISSION_GRANTED) {
6077 return null;
6078 }
6079 }
6080 }
6081
Dianne Hackbornb424b632010-08-18 15:59:05 -07006082 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6083 if (perms != null) {
6084 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6085 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6086 return null;
6087 }
6088 }
6089 }
6090
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006091 String msg;
6092 if (!cpi.exported) {
6093 msg = "Permission Denial: opening provider " + cpi.name
6094 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6095 + ", uid=" + callingUid + ") that is not exported from uid "
6096 + cpi.applicationInfo.uid;
6097 } else {
6098 msg = "Permission Denial: opening provider " + cpi.name
6099 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6100 + ", uid=" + callingUid + ") requires "
6101 + cpi.readPermission + " or " + cpi.writePermission;
6102 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006103 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 return msg;
6105 }
6106
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006107 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6108 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006109 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006110 for (int i=0; i<r.conProviders.size(); i++) {
6111 ContentProviderConnection conn = r.conProviders.get(i);
6112 if (conn.provider == cpr) {
6113 if (DEBUG_PROVIDER) Slog.v(TAG,
6114 "Adding provider requested by "
6115 + r.processName + " from process "
6116 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6117 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6118 if (stable) {
6119 conn.stableCount++;
6120 conn.numStableIncs++;
6121 } else {
6122 conn.unstableCount++;
6123 conn.numUnstableIncs++;
6124 }
6125 return conn;
6126 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006127 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006128 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6129 if (stable) {
6130 conn.stableCount = 1;
6131 conn.numStableIncs = 1;
6132 } else {
6133 conn.unstableCount = 1;
6134 conn.numUnstableIncs = 1;
6135 }
6136 cpr.connections.add(conn);
6137 r.conProviders.add(conn);
6138 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006139 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006140 cpr.addExternalProcessHandleLocked(externalProcessToken);
6141 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006142 }
6143
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006144 boolean decProviderCountLocked(ContentProviderConnection conn,
6145 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6146 if (conn != null) {
6147 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 if (DEBUG_PROVIDER) Slog.v(TAG,
6149 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006150 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006151 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006152 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6153 if (stable) {
6154 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006155 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006156 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006157 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006158 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6159 cpr.connections.remove(conn);
6160 conn.client.conProviders.remove(conn);
6161 return true;
6162 }
6163 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006164 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006166 return false;
6167 }
6168
Amith Yamasani742a6712011-05-04 14:49:28 -07006169 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006170 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006172 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 ProviderInfo cpi = null;
6174
6175 synchronized(this) {
6176 ProcessRecord r = null;
6177 if (caller != null) {
6178 r = getRecordForAppLocked(caller);
6179 if (r == null) {
6180 throw new SecurityException(
6181 "Unable to find app for caller " + caller
6182 + " (pid=" + Binder.getCallingPid()
6183 + ") when getting content provider " + name);
6184 }
6185 }
6186
6187 // First check if this content provider has been published...
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006188 int userId = UserHandle.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006189 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006190 boolean providerRunning = cpr != null;
6191 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006193 String msg;
6194 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6195 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197
6198 if (r != null && cpr.canRunHere(r)) {
6199 // This provider has been published or is in the process
6200 // of being published... but it is also allowed to run
6201 // in the caller's process, so don't make a connection
6202 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006203 ContentProviderHolder holder = cpr.newHolder(null);
6204 // don't give caller the provider object, it needs
6205 // to make its own.
6206 holder.provider = null;
6207 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
6209
6210 final long origId = Binder.clearCallingIdentity();
6211
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006212 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006214 conn = incProviderCountLocked(r, cpr, token, stable);
6215 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006216 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006217 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006218 // make sure to count it as being accessed and thus
6219 // back up on the LRU list. This is good because
6220 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006221 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006222 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006223 }
6224
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006225 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006226 if (false) {
6227 if (cpr.name.flattenToShortString().equals(
6228 "com.android.providers.calendar/.CalendarProvider2")) {
6229 Slog.v(TAG, "****************** KILLING "
6230 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006231 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006232 }
6233 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006234 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006235 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6236 // NOTE: there is still a race here where a signal could be
6237 // pending on the process even though we managed to update its
6238 // adj level. Not sure what to do about this, but at least
6239 // the race is now smaller.
6240 if (!success) {
6241 // Uh oh... it looks like the provider's process
6242 // has been killed on us. We need to wait for a new
6243 // process to be started, and make sure its death
6244 // doesn't kill our process.
6245 Slog.i(TAG,
6246 "Existing provider " + cpr.name.flattenToShortString()
6247 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006248 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006249 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006250 if (!lastRef) {
6251 // This wasn't the last ref our process had on
6252 // the provider... we have now been killed, bail.
6253 return null;
6254 }
6255 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006256 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 }
6259
6260 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006263 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006264 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006266 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006267 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006268 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 } catch (RemoteException ex) {
6270 }
6271 if (cpi == null) {
6272 return null;
6273 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006274 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6275 cpi.name, cpi.flags);
6276 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006277 userId = 0;
6278 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006279 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006280
Dianne Hackbornb424b632010-08-18 15:59:05 -07006281 String msg;
6282 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6283 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 }
6285
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006286 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006287 && !cpi.processName.equals("system")) {
6288 // If this content provider does not run in the system
6289 // process, and the system is not yet ready to run other
6290 // processes, then fail fast instead of hanging.
6291 throw new IllegalArgumentException(
6292 "Attempt to launch content provider before system ready");
6293 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006294
6295 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006296 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 final boolean firstClass = cpr == null;
6298 if (firstClass) {
6299 try {
6300 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006301 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 getApplicationInfo(
6303 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006304 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006306 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 + cpi.name);
6308 return null;
6309 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006310 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006311 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006312 } catch (RemoteException ex) {
6313 // pm is in same process, this will never happen.
6314 }
6315 }
6316
6317 if (r != null && cpr.canRunHere(r)) {
6318 // If this is a multiprocess provider, then just return its
6319 // info and allow the caller to instantiate it. Only do
6320 // this if the provider is the same user as the caller's
6321 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
6324
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006325 if (DEBUG_PROVIDER) {
6326 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006327 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006328 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 }
6330
6331 // This is single process, and our app is now connecting to it.
6332 // See if we are already in the process of launching this
6333 // provider.
6334 final int N = mLaunchingProviders.size();
6335 int i;
6336 for (i=0; i<N; i++) {
6337 if (mLaunchingProviders.get(i) == cpr) {
6338 break;
6339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 }
6341
6342 // If the provider is not already being launched, then get it
6343 // started.
6344 if (i >= N) {
6345 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006346
6347 try {
6348 // Content provider is now in use, its package can't be stopped.
6349 try {
6350 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006351 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006352 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006353 } catch (IllegalArgumentException e) {
6354 Slog.w(TAG, "Failed trying to unstop package "
6355 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006356 }
6357
6358 ProcessRecord proc = startProcessLocked(cpi.processName,
6359 cpr.appInfo, false, 0, "content provider",
6360 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006361 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006362 if (proc == null) {
6363 Slog.w(TAG, "Unable to launch app "
6364 + cpi.applicationInfo.packageName + "/"
6365 + cpi.applicationInfo.uid + " for provider "
6366 + name + ": process is bad");
6367 return null;
6368 }
6369 cpr.launchingApp = proc;
6370 mLaunchingProviders.add(cpr);
6371 } finally {
6372 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 }
6375
6376 // Make sure the provider is published (the same provider class
6377 // may be published under multiple names).
6378 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006379 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006381
Amith Yamasani742a6712011-05-04 14:49:28 -07006382 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006383 conn = incProviderCountLocked(r, cpr, token, stable);
6384 if (conn != null) {
6385 conn.waiting = true;
6386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 }
6388 }
6389
6390 // Wait for the provider to be published...
6391 synchronized (cpr) {
6392 while (cpr.provider == null) {
6393 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006394 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 + cpi.applicationInfo.packageName + "/"
6396 + cpi.applicationInfo.uid + " for provider "
6397 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006398 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 cpi.applicationInfo.packageName,
6400 cpi.applicationInfo.uid, name);
6401 return null;
6402 }
6403 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006404 if (DEBUG_MU) {
6405 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6406 + cpr.launchingApp);
6407 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006408 if (conn != null) {
6409 conn.waiting = true;
6410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 cpr.wait();
6412 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006413 } finally {
6414 if (conn != null) {
6415 conn.waiting = false;
6416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 }
6418 }
6419 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006420 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 }
6422
6423 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006424 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006425 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 if (caller == null) {
6427 String msg = "null IApplicationThread when getting content provider "
6428 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006429 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 throw new SecurityException(msg);
6431 }
6432
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006433 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006436 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6437 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6438 "Do not have permission in call getContentProviderExternal()");
6439 return getContentProviderExternalUnchecked(name, token);
6440 }
6441
6442 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006443 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445
6446 /**
6447 * Drop a content provider from a ProcessRecord's bookkeeping
6448 * @param cpr
6449 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006450 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006451 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006453 ContentProviderConnection conn;
6454 try {
6455 conn = (ContentProviderConnection)connection;
6456 } catch (ClassCastException e) {
6457 String msg ="removeContentProvider: " + connection
6458 + " not a ContentProviderConnection";
6459 Slog.w(TAG, msg);
6460 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006462 if (conn == null) {
6463 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006465 if (decProviderCountLocked(conn, null, null, stable)) {
6466 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 }
6469 }
6470
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006471 public void removeContentProviderExternal(String name, IBinder token) {
6472 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6473 "Do not have permission in call removeContentProviderExternal()");
6474 removeContentProviderExternalUnchecked(name, token);
6475 }
6476
6477 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006479 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6480 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 if(cpr == null) {
6482 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006483 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 return;
6485 }
6486
6487 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006488 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006489 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6490 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006491 if (localCpr.hasExternalProcessHandles()) {
6492 if (localCpr.removeExternalProcessHandleLocked(token)) {
6493 updateOomAdjLocked();
6494 } else {
6495 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6496 + " with no external reference for token: "
6497 + token + ".");
6498 }
6499 } else {
6500 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6501 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 }
6504 }
6505
6506 public final void publishContentProviders(IApplicationThread caller,
6507 List<ContentProviderHolder> providers) {
6508 if (providers == null) {
6509 return;
6510 }
6511
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006512 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006513 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006515 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006516 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006517 if (r == null) {
6518 throw new SecurityException(
6519 "Unable to find app for caller " + caller
6520 + " (pid=" + Binder.getCallingPid()
6521 + ") when publishing content providers");
6522 }
6523
6524 final long origId = Binder.clearCallingIdentity();
6525
6526 final int N = providers.size();
6527 for (int i=0; i<N; i++) {
6528 ContentProviderHolder src = providers.get(i);
6529 if (src == null || src.info == null || src.provider == null) {
6530 continue;
6531 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006532 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006533 if (DEBUG_MU)
6534 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006536 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006537 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006538 String names[] = dst.info.authority.split(";");
6539 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006540 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
6542
6543 int NL = mLaunchingProviders.size();
6544 int j;
6545 for (j=0; j<NL; j++) {
6546 if (mLaunchingProviders.get(j) == dst) {
6547 mLaunchingProviders.remove(j);
6548 j--;
6549 NL--;
6550 }
6551 }
6552 synchronized (dst) {
6553 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006554 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 dst.notifyAll();
6556 }
6557 updateOomAdjLocked(r);
6558 }
6559 }
6560
6561 Binder.restoreCallingIdentity(origId);
6562 }
6563 }
6564
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006565 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6566 ContentProviderConnection conn;
6567 try {
6568 conn = (ContentProviderConnection)connection;
6569 } catch (ClassCastException e) {
6570 String msg ="refContentProvider: " + connection
6571 + " not a ContentProviderConnection";
6572 Slog.w(TAG, msg);
6573 throw new IllegalArgumentException(msg);
6574 }
6575 if (conn == null) {
6576 throw new NullPointerException("connection is null");
6577 }
6578
6579 synchronized (this) {
6580 if (stable > 0) {
6581 conn.numStableIncs += stable;
6582 }
6583 stable = conn.stableCount + stable;
6584 if (stable < 0) {
6585 throw new IllegalStateException("stableCount < 0: " + stable);
6586 }
6587
6588 if (unstable > 0) {
6589 conn.numUnstableIncs += unstable;
6590 }
6591 unstable = conn.unstableCount + unstable;
6592 if (unstable < 0) {
6593 throw new IllegalStateException("unstableCount < 0: " + unstable);
6594 }
6595
6596 if ((stable+unstable) <= 0) {
6597 throw new IllegalStateException("ref counts can't go to zero here: stable="
6598 + stable + " unstable=" + unstable);
6599 }
6600 conn.stableCount = stable;
6601 conn.unstableCount = unstable;
6602 return !conn.dead;
6603 }
6604 }
6605
6606 public void unstableProviderDied(IBinder connection) {
6607 ContentProviderConnection conn;
6608 try {
6609 conn = (ContentProviderConnection)connection;
6610 } catch (ClassCastException e) {
6611 String msg ="refContentProvider: " + connection
6612 + " not a ContentProviderConnection";
6613 Slog.w(TAG, msg);
6614 throw new IllegalArgumentException(msg);
6615 }
6616 if (conn == null) {
6617 throw new NullPointerException("connection is null");
6618 }
6619
6620 // Safely retrieve the content provider associated with the connection.
6621 IContentProvider provider;
6622 synchronized (this) {
6623 provider = conn.provider.provider;
6624 }
6625
6626 if (provider == null) {
6627 // Um, yeah, we're way ahead of you.
6628 return;
6629 }
6630
6631 // Make sure the caller is being honest with us.
6632 if (provider.asBinder().pingBinder()) {
6633 // Er, no, still looks good to us.
6634 synchronized (this) {
6635 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6636 + " says " + conn + " died, but we don't agree");
6637 return;
6638 }
6639 }
6640
6641 // Well look at that! It's dead!
6642 synchronized (this) {
6643 if (conn.provider.provider != provider) {
6644 // But something changed... good enough.
6645 return;
6646 }
6647
6648 ProcessRecord proc = conn.provider.proc;
6649 if (proc == null || proc.thread == null) {
6650 // Seems like the process is already cleaned up.
6651 return;
6652 }
6653
6654 // As far as we're concerned, this is just like receiving a
6655 // death notification... just a bit prematurely.
6656 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6657 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006658 final long ident = Binder.clearCallingIdentity();
6659 try {
6660 appDiedLocked(proc, proc.pid, proc.thread);
6661 } finally {
6662 Binder.restoreCallingIdentity(ident);
6663 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006664 }
6665 }
6666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006668 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006669 synchronized (mSelf) {
6670 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6671 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006672 if (providers != null) {
6673 for (int i=providers.size()-1; i>=0; i--) {
6674 ProviderInfo pi = (ProviderInfo)providers.get(i);
6675 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6676 Slog.w(TAG, "Not installing system proc provider " + pi.name
6677 + ": not system .apk");
6678 providers.remove(i);
6679 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006680 }
6681 }
6682 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006683 if (providers != null) {
6684 mSystemThread.installSystemProviders(providers);
6685 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006686
6687 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006688
6689 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 }
6691
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006692 /**
6693 * Allows app to retrieve the MIME type of a URI without having permission
6694 * to access its content provider.
6695 *
6696 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6697 *
6698 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6699 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6700 */
6701 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006702 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006703 final String name = uri.getAuthority();
6704 final long ident = Binder.clearCallingIdentity();
6705 ContentProviderHolder holder = null;
6706
6707 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006708 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006709 if (holder != null) {
6710 return holder.provider.getType(uri);
6711 }
6712 } catch (RemoteException e) {
6713 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6714 return null;
6715 } finally {
6716 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006717 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006718 }
6719 Binder.restoreCallingIdentity(ident);
6720 }
6721
6722 return null;
6723 }
6724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 // =========================================================
6726 // GLOBAL MANAGEMENT
6727 // =========================================================
6728
6729 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006730 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 String proc = customProcess != null ? customProcess : info.processName;
6732 BatteryStatsImpl.Uid.Proc ps = null;
6733 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006734 int uid = info.uid;
6735 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006736 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006737 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6738 uid = 0;
6739 while (true) {
6740 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6741 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6742 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6743 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006744 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006745 mNextIsolatedProcessUid++;
6746 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6747 // No process for this uid, use it.
6748 break;
6749 }
6750 stepsLeft--;
6751 if (stepsLeft <= 0) {
6752 return null;
6753 }
6754 }
6755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 synchronized (stats) {
6757 ps = stats.getProcessStatsLocked(info.uid, proc);
6758 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006759 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 }
6761
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006762 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6763 ProcessRecord app;
6764 if (!isolated) {
6765 app = getProcessRecordLocked(info.processName, info.uid);
6766 } else {
6767 app = null;
6768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769
6770 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006771 app = newProcessRecordLocked(null, info, null, isolated);
6772 mProcessNames.put(info.processName, app.uid, app);
6773 if (isolated) {
6774 mIsolatedProcesses.put(app.uid, app);
6775 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006776 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006777 }
6778
Dianne Hackborne7f97212011-02-24 14:40:20 -08006779 // This package really, really can not be stopped.
6780 try {
6781 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006782 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006783 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006784 } catch (IllegalArgumentException e) {
6785 Slog.w(TAG, "Failed trying to unstop package "
6786 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006787 }
6788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6790 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6791 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006792 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006793 }
6794 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6795 mPersistentStartingProcesses.add(app);
6796 startProcessLocked(app, "added application", app.processName);
6797 }
6798
6799 return app;
6800 }
6801
6802 public void unhandledBack() {
6803 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6804 "unhandledBack()");
6805
6806 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006807 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006808 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006809 TAG, "Performing unhandledBack(): stack size = " + count);
6810 if (count > 1) {
6811 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006812 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6814 Binder.restoreCallingIdentity(origId);
6815 }
6816 }
6817 }
6818
6819 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006820 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006822 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 ParcelFileDescriptor pfd = null;
6824 if (cph != null) {
6825 // We record the binder invoker's uid in thread-local storage before
6826 // going to the content provider to open the file. Later, in the code
6827 // that handles all permissions checks, we look for this uid and use
6828 // that rather than the Activity Manager's own uid. The effect is that
6829 // we do the check against the caller's permissions even though it looks
6830 // to the content provider like the Activity Manager itself is making
6831 // the request.
6832 sCallerIdentity.set(new Identity(
6833 Binder.getCallingPid(), Binder.getCallingUid()));
6834 try {
6835 pfd = cph.provider.openFile(uri, "r");
6836 } catch (FileNotFoundException e) {
6837 // do nothing; pfd will be returned null
6838 } finally {
6839 // Ensure that whatever happens, we clean up the identity state
6840 sCallerIdentity.remove();
6841 }
6842
6843 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006844 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006846 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 }
6848 return pfd;
6849 }
6850
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006851 // Actually is sleeping or shutting down or whatever else in the future
6852 // is an inactive state.
6853 public boolean isSleeping() {
6854 return mSleeping || mShuttingDown;
6855 }
6856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006858 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6859 != PackageManager.PERMISSION_GRANTED) {
6860 throw new SecurityException("Requires permission "
6861 + android.Manifest.permission.DEVICE_POWER);
6862 }
6863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006865 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006866 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006868 if (!mSleeping) {
6869 mSleeping = true;
6870 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006871
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006872 // Initialize the wake times of all processes.
6873 checkExcessivePowerUsageLocked(false);
6874 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6875 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6876 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006878 }
6879 }
6880
Dianne Hackborn55280a92009-05-07 15:53:46 -07006881 public boolean shutdown(int timeout) {
6882 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6883 != PackageManager.PERMISSION_GRANTED) {
6884 throw new SecurityException("Requires permission "
6885 + android.Manifest.permission.SHUTDOWN);
6886 }
6887
6888 boolean timedout = false;
6889
6890 synchronized(this) {
6891 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006892 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006893
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006894 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006895 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006896 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006897 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006898 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006899 long delay = endTime - System.currentTimeMillis();
6900 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006901 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006902 timedout = true;
6903 break;
6904 }
6905 try {
6906 this.wait();
6907 } catch (InterruptedException e) {
6908 }
6909 }
6910 }
6911 }
6912
6913 mUsageStatsService.shutdown();
6914 mBatteryStatsService.shutdown();
6915
6916 return timedout;
6917 }
6918
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006919 public final void activitySlept(IBinder token) {
6920 if (localLOGV) Slog.v(
6921 TAG, "Activity slept: token=" + token);
6922
6923 ActivityRecord r = null;
6924
6925 final long origId = Binder.clearCallingIdentity();
6926
6927 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006928 r = mMainStack.isInStackLocked(token);
6929 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006930 mMainStack.activitySleptLocked(r);
6931 }
6932 }
6933
6934 Binder.restoreCallingIdentity(origId);
6935 }
6936
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006937 private void comeOutOfSleepIfNeededLocked() {
6938 if (!mWentToSleep && !mLockScreenShown) {
6939 if (mSleeping) {
6940 mSleeping = false;
6941 mMainStack.awakeFromSleepingLocked();
6942 mMainStack.resumeTopActivityLocked(null);
6943 }
6944 }
6945 }
6946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006948 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6949 != PackageManager.PERMISSION_GRANTED) {
6950 throw new SecurityException("Requires permission "
6951 + android.Manifest.permission.DEVICE_POWER);
6952 }
6953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006955 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006956 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006957 comeOutOfSleepIfNeededLocked();
6958 }
6959 }
6960
Jeff Brownc042ee22012-05-08 13:03:42 -07006961 private void updateEventDispatchingLocked() {
6962 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6963 }
6964
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006965 public void setLockScreenShown(boolean shown) {
6966 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6967 != PackageManager.PERMISSION_GRANTED) {
6968 throw new SecurityException("Requires permission "
6969 + android.Manifest.permission.DEVICE_POWER);
6970 }
6971
6972 synchronized(this) {
6973 mLockScreenShown = shown;
6974 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 }
6976 }
6977
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006978 public void stopAppSwitches() {
6979 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6980 != PackageManager.PERMISSION_GRANTED) {
6981 throw new SecurityException("Requires permission "
6982 + android.Manifest.permission.STOP_APP_SWITCHES);
6983 }
6984
6985 synchronized(this) {
6986 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6987 + APP_SWITCH_DELAY_TIME;
6988 mDidAppSwitch = false;
6989 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6990 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6991 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6992 }
6993 }
6994
6995 public void resumeAppSwitches() {
6996 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6997 != PackageManager.PERMISSION_GRANTED) {
6998 throw new SecurityException("Requires permission "
6999 + android.Manifest.permission.STOP_APP_SWITCHES);
7000 }
7001
7002 synchronized(this) {
7003 // Note that we don't execute any pending app switches... we will
7004 // let those wait until either the timeout, or the next start
7005 // activity request.
7006 mAppSwitchesAllowedTime = 0;
7007 }
7008 }
7009
7010 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7011 String name) {
7012 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7013 return true;
7014 }
7015
7016 final int perm = checkComponentPermission(
7017 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007018 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007019 if (perm == PackageManager.PERMISSION_GRANTED) {
7020 return true;
7021 }
7022
Joe Onorato8a9b2202010-02-26 18:56:32 -08007023 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007024 return false;
7025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 public void setDebugApp(String packageName, boolean waitForDebugger,
7028 boolean persistent) {
7029 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7030 "setDebugApp()");
7031
7032 // Note that this is not really thread safe if there are multiple
7033 // callers into it at the same time, but that's not a situation we
7034 // care about.
7035 if (persistent) {
7036 final ContentResolver resolver = mContext.getContentResolver();
7037 Settings.System.putString(
7038 resolver, Settings.System.DEBUG_APP,
7039 packageName);
7040 Settings.System.putInt(
7041 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7042 waitForDebugger ? 1 : 0);
7043 }
7044
7045 synchronized (this) {
7046 if (!persistent) {
7047 mOrigDebugApp = mDebugApp;
7048 mOrigWaitForDebugger = mWaitForDebugger;
7049 }
7050 mDebugApp = packageName;
7051 mWaitForDebugger = waitForDebugger;
7052 mDebugTransient = !persistent;
7053 if (packageName != null) {
7054 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007055 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 Binder.restoreCallingIdentity(origId);
7057 }
7058 }
7059 }
7060
Siva Velusamy92a8b222012-03-09 16:24:04 -08007061 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7062 synchronized (this) {
7063 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7064 if (!isDebuggable) {
7065 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7066 throw new SecurityException("Process not debuggable: " + app.packageName);
7067 }
7068 }
7069
7070 mOpenGlTraceApp = processName;
7071 }
7072 }
7073
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007074 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7075 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7076 synchronized (this) {
7077 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7078 if (!isDebuggable) {
7079 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7080 throw new SecurityException("Process not debuggable: " + app.packageName);
7081 }
7082 }
7083 mProfileApp = processName;
7084 mProfileFile = profileFile;
7085 if (mProfileFd != null) {
7086 try {
7087 mProfileFd.close();
7088 } catch (IOException e) {
7089 }
7090 mProfileFd = null;
7091 }
7092 mProfileFd = profileFd;
7093 mProfileType = 0;
7094 mAutoStopProfiler = autoStopProfiler;
7095 }
7096 }
7097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007098 public void setAlwaysFinish(boolean enabled) {
7099 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7100 "setAlwaysFinish()");
7101
7102 Settings.System.putInt(
7103 mContext.getContentResolver(),
7104 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7105
7106 synchronized (this) {
7107 mAlwaysFinishActivities = enabled;
7108 }
7109 }
7110
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007111 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007112 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007113 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007114 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007115 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 }
7117 }
7118
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007119 public boolean isUserAMonkey() {
7120 // For now the fact that there is a controller implies
7121 // we have a monkey.
7122 synchronized (this) {
7123 return mController != null;
7124 }
7125 }
7126
Jeff Sharkeya4620792011-05-20 15:29:23 -07007127 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007128 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7129 "registerProcessObserver()");
7130 synchronized (this) {
7131 mProcessObservers.register(observer);
7132 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007133 }
7134
7135 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007136 synchronized (this) {
7137 mProcessObservers.unregister(observer);
7138 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007139 }
7140
Daniel Sandler69a48172010-06-23 16:29:36 -04007141 public void setImmersive(IBinder token, boolean immersive) {
7142 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007143 ActivityRecord r = mMainStack.isInStackLocked(token);
7144 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007145 throw new IllegalArgumentException();
7146 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007147 r.immersive = immersive;
7148 }
7149 }
7150
7151 public boolean isImmersive(IBinder token) {
7152 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007153 ActivityRecord r = mMainStack.isInStackLocked(token);
7154 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007155 throw new IllegalArgumentException();
7156 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007157 return r.immersive;
7158 }
7159 }
7160
7161 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007162 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007163 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007164 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007165 return (r != null) ? r.immersive : false;
7166 }
7167 }
7168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007169 public final void enterSafeMode() {
7170 synchronized(this) {
7171 // It only makes sense to do this before the system is ready
7172 // and started launching other packages.
7173 if (!mSystemReady) {
7174 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007175 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007176 } catch (RemoteException e) {
7177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 }
7179 }
7180 }
7181
Jeff Brownb09abc12011-01-13 21:08:27 -08007182 public final void showSafeModeOverlay() {
7183 View v = LayoutInflater.from(mContext).inflate(
7184 com.android.internal.R.layout.safe_mode, null);
7185 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7186 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7187 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7188 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007189 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007190 lp.format = v.getBackground().getOpacity();
7191 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7192 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7193 ((WindowManager)mContext.getSystemService(
7194 Context.WINDOW_SERVICE)).addView(v, lp);
7195 }
7196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 public void noteWakeupAlarm(IIntentSender sender) {
7198 if (!(sender instanceof PendingIntentRecord)) {
7199 return;
7200 }
7201 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7202 synchronized (stats) {
7203 if (mBatteryStatsService.isOnBattery()) {
7204 mBatteryStatsService.enforceCallingPermission();
7205 PendingIntentRecord rec = (PendingIntentRecord)sender;
7206 int MY_UID = Binder.getCallingUid();
7207 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7208 BatteryStatsImpl.Uid.Pkg pkg =
7209 stats.getPackageStatsLocked(uid, rec.key.packageName);
7210 pkg.incWakeupsLocked();
7211 }
7212 }
7213 }
7214
Dianne Hackborn64825172011-03-02 21:32:58 -08007215 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007216 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007217 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007219 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 // XXX Note: don't acquire main activity lock here, because the window
7221 // manager calls in with its locks held.
7222
7223 boolean killed = false;
7224 synchronized (mPidsSelfLocked) {
7225 int[] types = new int[pids.length];
7226 int worstType = 0;
7227 for (int i=0; i<pids.length; i++) {
7228 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7229 if (proc != null) {
7230 int type = proc.setAdj;
7231 types[i] = type;
7232 if (type > worstType) {
7233 worstType = type;
7234 }
7235 }
7236 }
7237
Dianne Hackborn64825172011-03-02 21:32:58 -08007238 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007240 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7241 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007242 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007244
7245 // If this is not a secure call, don't let it kill processes that
7246 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007247 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7248 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007249 }
7250
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007251 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 for (int i=0; i<pids.length; i++) {
7253 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7254 if (proc == null) {
7255 continue;
7256 }
7257 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007258 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007259 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007260 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7261 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007263 proc.killedBackground = true;
7264 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 }
7266 }
7267 }
7268 return killed;
7269 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007270
7271 @Override
7272 public boolean killProcessesBelowForeground(String reason) {
7273 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7274 throw new SecurityException("killProcessesBelowForeground() only available to system");
7275 }
7276
7277 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7278 }
7279
7280 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7281 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7282 throw new SecurityException("killProcessesBelowAdj() only available to system");
7283 }
7284
7285 boolean killed = false;
7286 synchronized (mPidsSelfLocked) {
7287 final int size = mPidsSelfLocked.size();
7288 for (int i = 0; i < size; i++) {
7289 final int pid = mPidsSelfLocked.keyAt(i);
7290 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7291 if (proc == null) continue;
7292
7293 final int adj = proc.setAdj;
7294 if (adj > belowAdj && !proc.killedBackground) {
7295 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7296 EventLog.writeEvent(
7297 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7298 killed = true;
7299 proc.killedBackground = true;
7300 Process.killProcessQuiet(pid);
7301 }
7302 }
7303 }
7304 return killed;
7305 }
7306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 public final void startRunning(String pkg, String cls, String action,
7308 String data) {
7309 synchronized(this) {
7310 if (mStartRunning) {
7311 return;
7312 }
7313 mStartRunning = true;
7314 mTopComponent = pkg != null && cls != null
7315 ? new ComponentName(pkg, cls) : null;
7316 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7317 mTopData = data;
7318 if (!mSystemReady) {
7319 return;
7320 }
7321 }
7322
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007323 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 }
7325
7326 private void retrieveSettings() {
7327 final ContentResolver resolver = mContext.getContentResolver();
7328 String debugApp = Settings.System.getString(
7329 resolver, Settings.System.DEBUG_APP);
7330 boolean waitForDebugger = Settings.System.getInt(
7331 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7332 boolean alwaysFinishActivities = Settings.System.getInt(
7333 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7334
7335 Configuration configuration = new Configuration();
7336 Settings.System.getConfiguration(resolver, configuration);
7337
7338 synchronized (this) {
7339 mDebugApp = mOrigDebugApp = debugApp;
7340 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7341 mAlwaysFinishActivities = alwaysFinishActivities;
7342 // This happens before any activities are started, so we can
7343 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007344 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007345 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 }
7347 }
7348
7349 public boolean testIsSystemReady() {
7350 // no need to synchronize(this) just to read & return the value
7351 return mSystemReady;
7352 }
7353
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007354 private static File getCalledPreBootReceiversFile() {
7355 File dataDir = Environment.getDataDirectory();
7356 File systemDir = new File(dataDir, "system");
7357 File fname = new File(systemDir, "called_pre_boots.dat");
7358 return fname;
7359 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007360
7361 static final int LAST_DONE_VERSION = 10000;
7362
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007363 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7364 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7365 File file = getCalledPreBootReceiversFile();
7366 FileInputStream fis = null;
7367 try {
7368 fis = new FileInputStream(file);
7369 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007370 int fvers = dis.readInt();
7371 if (fvers == LAST_DONE_VERSION) {
7372 String vers = dis.readUTF();
7373 String codename = dis.readUTF();
7374 String build = dis.readUTF();
7375 if (android.os.Build.VERSION.RELEASE.equals(vers)
7376 && android.os.Build.VERSION.CODENAME.equals(codename)
7377 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7378 int num = dis.readInt();
7379 while (num > 0) {
7380 num--;
7381 String pkg = dis.readUTF();
7382 String cls = dis.readUTF();
7383 lastDoneReceivers.add(new ComponentName(pkg, cls));
7384 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007385 }
7386 }
7387 } catch (FileNotFoundException e) {
7388 } catch (IOException e) {
7389 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7390 } finally {
7391 if (fis != null) {
7392 try {
7393 fis.close();
7394 } catch (IOException e) {
7395 }
7396 }
7397 }
7398 return lastDoneReceivers;
7399 }
7400
7401 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7402 File file = getCalledPreBootReceiversFile();
7403 FileOutputStream fos = null;
7404 DataOutputStream dos = null;
7405 try {
7406 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7407 fos = new FileOutputStream(file);
7408 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007409 dos.writeInt(LAST_DONE_VERSION);
7410 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007411 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007412 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007413 dos.writeInt(list.size());
7414 for (int i=0; i<list.size(); i++) {
7415 dos.writeUTF(list.get(i).getPackageName());
7416 dos.writeUTF(list.get(i).getClassName());
7417 }
7418 } catch (IOException e) {
7419 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7420 file.delete();
7421 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007422 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007423 if (dos != null) {
7424 try {
7425 dos.close();
7426 } catch (IOException e) {
7427 // TODO Auto-generated catch block
7428 e.printStackTrace();
7429 }
7430 }
7431 }
7432 }
7433
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007434 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007435 synchronized(this) {
7436 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007437 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007438 return;
7439 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007440
7441 // Check to see if there are any update receivers to run.
7442 if (!mDidUpdate) {
7443 if (mWaitingUpdate) {
7444 return;
7445 }
7446 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7447 List<ResolveInfo> ris = null;
7448 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007449 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007450 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007451 } catch (RemoteException e) {
7452 }
7453 if (ris != null) {
7454 for (int i=ris.size()-1; i>=0; i--) {
7455 if ((ris.get(i).activityInfo.applicationInfo.flags
7456 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7457 ris.remove(i);
7458 }
7459 }
7460 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007461
7462 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7463
7464 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007465 for (int i=0; i<ris.size(); i++) {
7466 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007467 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7468 if (lastDoneReceivers.contains(comp)) {
7469 ris.remove(i);
7470 i--;
7471 }
7472 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007473
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007474 for (int i=0; i<ris.size(); i++) {
7475 ActivityInfo ai = ris.get(i).activityInfo;
7476 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7477 doneReceivers.add(comp);
7478 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007479 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007480 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007481 finisher = new IIntentReceiver.Stub() {
7482 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007483 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007484 boolean sticky) {
7485 // The raw IIntentReceiver interface is called
7486 // with the AM lock held, so redispatch to
7487 // execute our code without the lock.
7488 mHandler.post(new Runnable() {
7489 public void run() {
7490 synchronized (ActivityManagerService.this) {
7491 mDidUpdate = true;
7492 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007493 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007494 showBootMessage(mContext.getText(
7495 R.string.android_upgrading_complete),
7496 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007497 systemReady(goingCallback);
7498 }
7499 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007500 }
7501 };
7502 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007503 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007504 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007505 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007506 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007507 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007508 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007509 mWaitingUpdate = true;
7510 }
7511 }
7512 }
7513 if (mWaitingUpdate) {
7514 return;
7515 }
7516 mDidUpdate = true;
7517 }
7518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007519 mSystemReady = true;
7520 if (!mStartRunning) {
7521 return;
7522 }
7523 }
7524
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007525 ArrayList<ProcessRecord> procsToKill = null;
7526 synchronized(mPidsSelfLocked) {
7527 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7528 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7529 if (!isAllowedWhileBooting(proc.info)){
7530 if (procsToKill == null) {
7531 procsToKill = new ArrayList<ProcessRecord>();
7532 }
7533 procsToKill.add(proc);
7534 }
7535 }
7536 }
7537
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007538 synchronized(this) {
7539 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007540 for (int i=procsToKill.size()-1; i>=0; i--) {
7541 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007542 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007543 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007544 }
7545 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007546
7547 // Now that we have cleaned up any update processes, we
7548 // are ready to start launching real processes and know that
7549 // we won't trample on them any more.
7550 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007551 }
7552
Joe Onorato8a9b2202010-02-26 18:56:32 -08007553 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007554 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 SystemClock.uptimeMillis());
7556
7557 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007558 // Make sure we have no pre-ready processes sitting around.
7559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7561 ResolveInfo ri = mContext.getPackageManager()
7562 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007563 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 CharSequence errorMsg = null;
7565 if (ri != null) {
7566 ActivityInfo ai = ri.activityInfo;
7567 ApplicationInfo app = ai.applicationInfo;
7568 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7569 mTopAction = Intent.ACTION_FACTORY_TEST;
7570 mTopData = null;
7571 mTopComponent = new ComponentName(app.packageName,
7572 ai.name);
7573 } else {
7574 errorMsg = mContext.getResources().getText(
7575 com.android.internal.R.string.factorytest_not_system);
7576 }
7577 } else {
7578 errorMsg = mContext.getResources().getText(
7579 com.android.internal.R.string.factorytest_no_action);
7580 }
7581 if (errorMsg != null) {
7582 mTopAction = null;
7583 mTopData = null;
7584 mTopComponent = null;
7585 Message msg = Message.obtain();
7586 msg.what = SHOW_FACTORY_ERROR_MSG;
7587 msg.getData().putCharSequence("msg", errorMsg);
7588 mHandler.sendMessage(msg);
7589 }
7590 }
7591 }
7592
7593 retrieveSettings();
7594
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007595 if (goingCallback != null) goingCallback.run();
7596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 synchronized (this) {
7598 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7599 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007600 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007601 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 if (apps != null) {
7603 int N = apps.size();
7604 int i;
7605 for (i=0; i<N; i++) {
7606 ApplicationInfo info
7607 = (ApplicationInfo)apps.get(i);
7608 if (info != null &&
7609 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007610 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007611 }
7612 }
7613 }
7614 } catch (RemoteException ex) {
7615 // pm is in same process, this will never happen.
7616 }
7617 }
7618
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007619 // Start up initial activity.
7620 mBooting = true;
7621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007623 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 Message msg = Message.obtain();
7625 msg.what = SHOW_UID_ERROR_MSG;
7626 mHandler.sendMessage(msg);
7627 }
7628 } catch (RemoteException e) {
7629 }
7630
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007631 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 }
7633 }
7634
Dan Egnorb7f03672009-12-09 16:22:32 -08007635 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007636 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007638 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007639 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 startAppProblemLocked(app);
7641 app.stopFreezingAllLocked();
7642 return handleAppCrashLocked(app);
7643 }
7644
Dan Egnorb7f03672009-12-09 16:22:32 -08007645 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007646 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007648 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007649 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7650 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 startAppProblemLocked(app);
7652 app.stopFreezingAllLocked();
7653 }
7654
7655 /**
7656 * Generate a process error record, suitable for attachment to a ProcessRecord.
7657 *
7658 * @param app The ProcessRecord in which the error occurred.
7659 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7660 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007661 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 * @param shortMsg Short message describing the crash.
7663 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007664 * @param stackTrace Full crash stack trace, may be null.
7665 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 * @return Returns a fully-formed AppErrorStateInfo record.
7667 */
7668 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007669 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 report.condition = condition;
7673 report.processName = app.processName;
7674 report.pid = app.pid;
7675 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007676 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 report.shortMsg = shortMsg;
7678 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007679 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680
7681 return report;
7682 }
7683
Dan Egnor42471dd2010-01-07 17:25:22 -08007684 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685 synchronized (this) {
7686 app.crashing = false;
7687 app.crashingReport = null;
7688 app.notResponding = false;
7689 app.notRespondingReport = null;
7690 if (app.anrDialog == fromDialog) {
7691 app.anrDialog = null;
7692 }
7693 if (app.waitDialog == fromDialog) {
7694 app.waitDialog = null;
7695 }
7696 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007697 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007698 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007699 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7700 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007701 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 }
7704 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007705
Dan Egnorb7f03672009-12-09 16:22:32 -08007706 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007707 if (mHeadless) {
7708 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7709 return false;
7710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 long now = SystemClock.uptimeMillis();
7712
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007713 Long crashTime;
7714 if (!app.isolated) {
7715 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7716 } else {
7717 crashTime = null;
7718 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007719 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007721 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007722 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007723 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007724 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007725 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7726 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007728 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007730 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 }
7732 }
7733 if (!app.persistent) {
7734 // We don't want to start this process again until the user
7735 // explicitly does so... but for persistent process, we really
7736 // need to keep it running. If a persistent process is actually
7737 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007738 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007740 if (!app.isolated) {
7741 // XXX We don't have a way to mark isolated processes
7742 // as bad, since they don't have a peristent identity.
7743 mBadProcesses.put(app.info.processName, app.uid, now);
7744 mProcessCrashTimes.remove(app.info.processName, app.uid);
7745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007748 // Don't let services in this process be restarted and potentially
7749 // annoy the user repeatedly. Unless it is persistent, since those
7750 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007751 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007752 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 return false;
7754 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007755 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007756 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007757 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007758 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007759 // If the top running activity is from this crashing
7760 // process, then terminate it to avoid getting in a loop.
7761 Slog.w(TAG, " Force finishing activity "
7762 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007763 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007764 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007765 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007766 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007767 // stopped, to avoid a situation where one will get
7768 // re-start our crashing activity once it gets resumed again.
7769 index--;
7770 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007771 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007772 if (r.state == ActivityState.RESUMED
7773 || r.state == ActivityState.PAUSING
7774 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007775 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007776 Slog.w(TAG, " Force finishing activity "
7777 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007778 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007779 Activity.RESULT_CANCELED, null, "crashed");
7780 }
7781 }
7782 }
7783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 }
7785
7786 // Bump up the crash count of any services currently running in the proc.
7787 if (app.services.size() != 0) {
7788 // Any services running in the application need to be placed
7789 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007790 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007792 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 sr.crashCount++;
7794 }
7795 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007796
7797 // If the crashing process is what we consider to be the "home process" and it has been
7798 // replaced by a third-party app, clear the package preferred activities from packages
7799 // with a home activity running in the process to prevent a repeatedly crashing app
7800 // from blocking the user to manually clear the list.
7801 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7802 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7803 Iterator it = mHomeProcess.activities.iterator();
7804 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007805 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007806 if (r.isHomeActivity) {
7807 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7808 try {
7809 ActivityThread.getPackageManager()
7810 .clearPackagePreferredActivities(r.packageName);
7811 } catch (RemoteException c) {
7812 // pm is in same process, this will never happen.
7813 }
7814 }
7815 }
7816 }
7817
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007818 if (!app.isolated) {
7819 // XXX Can't keep track of crash times for isolated processes,
7820 // because they don't have a perisistent identity.
7821 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7822 }
7823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 return true;
7825 }
7826
7827 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007828 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7829 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 skipCurrentReceiverLocked(app);
7831 }
7832
7833 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007834 for (BroadcastQueue queue : mBroadcastQueues) {
7835 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 }
7837 }
7838
Dan Egnor60d87622009-12-16 16:32:58 -08007839 /**
7840 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7841 * The application process will exit immediately after this call returns.
7842 * @param app object of the crashing app, null for the system server
7843 * @param crashInfo describing the exception
7844 */
7845 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007846 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007847 final String processName = app == null ? "system_server"
7848 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007849
7850 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007851 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007852 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007853 crashInfo.exceptionClassName,
7854 crashInfo.exceptionMessage,
7855 crashInfo.throwFileName,
7856 crashInfo.throwLineNumber);
7857
Jeff Sharkeya353d262011-10-28 11:12:06 -07007858 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007859
7860 crashApplication(r, crashInfo);
7861 }
7862
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007863 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007864 IBinder app,
7865 int violationMask,
7866 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007867 ProcessRecord r = findAppProcess(app, "StrictMode");
7868 if (r == null) {
7869 return;
7870 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007871
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007872 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007873 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007874 boolean logIt = true;
7875 synchronized (mAlreadyLoggedViolatedStacks) {
7876 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7877 logIt = false;
7878 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007879 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007880 // the relative pain numbers, without logging all
7881 // the stack traces repeatedly. We'd want to do
7882 // likewise in the client code, which also does
7883 // dup suppression, before the Binder call.
7884 } else {
7885 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7886 mAlreadyLoggedViolatedStacks.clear();
7887 }
7888 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7889 }
7890 }
7891 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007892 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007893 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007894 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007895
7896 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7897 AppErrorResult result = new AppErrorResult();
7898 synchronized (this) {
7899 final long origId = Binder.clearCallingIdentity();
7900
7901 Message msg = Message.obtain();
7902 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7903 HashMap<String, Object> data = new HashMap<String, Object>();
7904 data.put("result", result);
7905 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007906 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007907 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007908 msg.obj = data;
7909 mHandler.sendMessage(msg);
7910
7911 Binder.restoreCallingIdentity(origId);
7912 }
7913 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007914 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007915 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007916 }
7917
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007918 // Depending on the policy in effect, there could be a bunch of
7919 // these in quick succession so we try to batch these together to
7920 // minimize disk writes, number of dropbox entries, and maximize
7921 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007922 private void logStrictModeViolationToDropBox(
7923 ProcessRecord process,
7924 StrictMode.ViolationInfo info) {
7925 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007926 return;
7927 }
7928 final boolean isSystemApp = process == null ||
7929 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7930 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007931 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007932 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7933 final DropBoxManager dbox = (DropBoxManager)
7934 mContext.getSystemService(Context.DROPBOX_SERVICE);
7935
7936 // Exit early if the dropbox isn't configured to accept this report type.
7937 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7938
7939 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007940 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007941 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7942 synchronized (sb) {
7943 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007944 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007945 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7946 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007947 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7948 if (info.violationNumThisLoop != 0) {
7949 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7950 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007951 if (info.numAnimationsRunning != 0) {
7952 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7953 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007954 if (info.broadcastIntentAction != null) {
7955 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7956 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007957 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007958 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007959 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007960 if (info.numInstances != -1) {
7961 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7962 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007963 if (info.tags != null) {
7964 for (String tag : info.tags) {
7965 sb.append("Span-Tag: ").append(tag).append("\n");
7966 }
7967 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007968 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007969 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7970 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007971 }
7972 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007973
7974 // Only buffer up to ~64k. Various logging bits truncate
7975 // things at 128k.
7976 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007977 }
7978
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007979 // Flush immediately if the buffer's grown too large, or this
7980 // is a non-system app. Non-system apps are isolated with a
7981 // different tag & policy and not batched.
7982 //
7983 // Batching is useful during internal testing with
7984 // StrictMode settings turned up high. Without batching,
7985 // thousands of separate files could be created on boot.
7986 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007987 new Thread("Error dump: " + dropboxTag) {
7988 @Override
7989 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007990 String report;
7991 synchronized (sb) {
7992 report = sb.toString();
7993 sb.delete(0, sb.length());
7994 sb.trimToSize();
7995 }
7996 if (report.length() != 0) {
7997 dbox.addText(dropboxTag, report);
7998 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007999 }
8000 }.start();
8001 return;
8002 }
8003
8004 // System app batching:
8005 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008006 // An existing dropbox-writing thread is outstanding, so
8007 // we don't need to start it up. The existing thread will
8008 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008009 return;
8010 }
8011
8012 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8013 // (After this point, we shouldn't access AMS internal data structures.)
8014 new Thread("Error dump: " + dropboxTag) {
8015 @Override
8016 public void run() {
8017 // 5 second sleep to let stacks arrive and be batched together
8018 try {
8019 Thread.sleep(5000); // 5 seconds
8020 } catch (InterruptedException e) {}
8021
8022 String errorReport;
8023 synchronized (mStrictModeBuffer) {
8024 errorReport = mStrictModeBuffer.toString();
8025 if (errorReport.length() == 0) {
8026 return;
8027 }
8028 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8029 mStrictModeBuffer.trimToSize();
8030 }
8031 dbox.addText(dropboxTag, errorReport);
8032 }
8033 }.start();
8034 }
8035
Dan Egnor60d87622009-12-16 16:32:58 -08008036 /**
8037 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8038 * @param app object of the crashing app, null for the system server
8039 * @param tag reported by the caller
8040 * @param crashInfo describing the context of the error
8041 * @return true if the process should exit immediately (WTF is fatal)
8042 */
8043 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008044 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008045 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008046 final String processName = app == null ? "system_server"
8047 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008048
8049 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008050 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008051 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008052 tag, crashInfo.exceptionMessage);
8053
Jeff Sharkeya353d262011-10-28 11:12:06 -07008054 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008055
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008056 if (r != null && r.pid != Process.myPid() &&
8057 Settings.Secure.getInt(mContext.getContentResolver(),
8058 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008059 crashApplication(r, crashInfo);
8060 return true;
8061 } else {
8062 return false;
8063 }
8064 }
8065
8066 /**
8067 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8068 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8069 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008070 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008071 if (app == null) {
8072 return null;
8073 }
8074
8075 synchronized (this) {
8076 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8077 final int NA = apps.size();
8078 for (int ia=0; ia<NA; ia++) {
8079 ProcessRecord p = apps.valueAt(ia);
8080 if (p.thread != null && p.thread.asBinder() == app) {
8081 return p;
8082 }
8083 }
8084 }
8085
Dianne Hackborncb44d962011-03-10 17:02:27 -08008086 Slog.w(TAG, "Can't find mystery application for " + reason
8087 + " from pid=" + Binder.getCallingPid()
8088 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008089 return null;
8090 }
8091 }
8092
8093 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008094 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8095 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008096 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008097 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8098 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008099 // Watchdog thread ends up invoking this function (with
8100 // a null ProcessRecord) to add the stack file to dropbox.
8101 // Do not acquire a lock on this (am) in such cases, as it
8102 // could cause a potential deadlock, if and when watchdog
8103 // is invoked due to unavailability of lock on am and it
8104 // would prevent watchdog from killing system_server.
8105 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008106 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008107 return;
8108 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008109 // Note: ProcessRecord 'process' is guarded by the service
8110 // instance. (notably process.pkgList, which could otherwise change
8111 // concurrently during execution of this method)
8112 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008113 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008114 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008115 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008116 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8117 for (String pkg : process.pkgList) {
8118 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008119 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008120 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008121 if (pi != null) {
8122 sb.append(" v").append(pi.versionCode);
8123 if (pi.versionName != null) {
8124 sb.append(" (").append(pi.versionName).append(")");
8125 }
8126 }
8127 } catch (RemoteException e) {
8128 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008129 }
Dan Egnora455d192010-03-12 08:52:28 -08008130 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008131 }
Dan Egnora455d192010-03-12 08:52:28 -08008132 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008133 }
8134
8135 private static String processClass(ProcessRecord process) {
8136 if (process == null || process.pid == MY_PID) {
8137 return "system_server";
8138 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8139 return "system_app";
8140 } else {
8141 return "data_app";
8142 }
8143 }
8144
8145 /**
8146 * Write a description of an error (crash, WTF, ANR) to the drop box.
8147 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8148 * @param process which caused the error, null means the system server
8149 * @param activity which triggered the error, null if unknown
8150 * @param parent activity related to the error, null if unknown
8151 * @param subject line related to the error, null if absent
8152 * @param report in long form describing the error, null if absent
8153 * @param logFile to include in the report, null if none
8154 * @param crashInfo giving an application stack trace, null if absent
8155 */
8156 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008157 ProcessRecord process, String processName, ActivityRecord activity,
8158 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008159 final String report, final File logFile,
8160 final ApplicationErrorReport.CrashInfo crashInfo) {
8161 // NOTE -- this must never acquire the ActivityManagerService lock,
8162 // otherwise the watchdog may be prevented from resetting the system.
8163
8164 final String dropboxTag = processClass(process) + "_" + eventType;
8165 final DropBoxManager dbox = (DropBoxManager)
8166 mContext.getSystemService(Context.DROPBOX_SERVICE);
8167
8168 // Exit early if the dropbox isn't configured to accept this report type.
8169 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8170
8171 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008172 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008173 if (activity != null) {
8174 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8175 }
8176 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8177 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8178 }
8179 if (parent != null && parent != activity) {
8180 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8181 }
8182 if (subject != null) {
8183 sb.append("Subject: ").append(subject).append("\n");
8184 }
8185 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008186 if (Debug.isDebuggerConnected()) {
8187 sb.append("Debugger: Connected\n");
8188 }
Dan Egnora455d192010-03-12 08:52:28 -08008189 sb.append("\n");
8190
8191 // Do the rest in a worker thread to avoid blocking the caller on I/O
8192 // (After this point, we shouldn't access AMS internal data structures.)
8193 Thread worker = new Thread("Error dump: " + dropboxTag) {
8194 @Override
8195 public void run() {
8196 if (report != null) {
8197 sb.append(report);
8198 }
8199 if (logFile != null) {
8200 try {
8201 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8202 } catch (IOException e) {
8203 Slog.e(TAG, "Error reading " + logFile, e);
8204 }
8205 }
8206 if (crashInfo != null && crashInfo.stackTrace != null) {
8207 sb.append(crashInfo.stackTrace);
8208 }
8209
8210 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8211 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8212 if (lines > 0) {
8213 sb.append("\n");
8214
8215 // Merge several logcat streams, and take the last N lines
8216 InputStreamReader input = null;
8217 try {
8218 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8219 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8220 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8221
8222 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8223 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8224 input = new InputStreamReader(logcat.getInputStream());
8225
8226 int num;
8227 char[] buf = new char[8192];
8228 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8229 } catch (IOException e) {
8230 Slog.e(TAG, "Error running logcat", e);
8231 } finally {
8232 if (input != null) try { input.close(); } catch (IOException e) {}
8233 }
8234 }
8235
8236 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008237 }
Dan Egnora455d192010-03-12 08:52:28 -08008238 };
8239
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008240 if (process == null) {
8241 // If process is null, we are being called from some internal code
8242 // and may be about to die -- run this synchronously.
8243 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008244 } else {
8245 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008246 }
8247 }
8248
8249 /**
8250 * Bring up the "unexpected error" dialog box for a crashing app.
8251 * Deal with edge cases (intercepts from instrumented applications,
8252 * ActivityController, error intent receivers, that sort of thing).
8253 * @param r the application crashing
8254 * @param crashInfo describing the failure
8255 */
8256 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008257 long timeMillis = System.currentTimeMillis();
8258 String shortMsg = crashInfo.exceptionClassName;
8259 String longMsg = crashInfo.exceptionMessage;
8260 String stackTrace = crashInfo.stackTrace;
8261 if (shortMsg != null && longMsg != null) {
8262 longMsg = shortMsg + ": " + longMsg;
8263 } else if (shortMsg != null) {
8264 longMsg = shortMsg;
8265 }
8266
Dan Egnor60d87622009-12-16 16:32:58 -08008267 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008268 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008269 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008270 try {
8271 String name = r != null ? r.processName : null;
8272 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008273 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008274 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008275 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 + " at watcher's request");
8277 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008278 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008279 }
8280 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008281 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008282 }
8283 }
8284
8285 final long origId = Binder.clearCallingIdentity();
8286
8287 // If this process is running instrumentation, finish it.
8288 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008289 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008290 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008291 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8292 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 Bundle info = new Bundle();
8294 info.putString("shortMsg", shortMsg);
8295 info.putString("longMsg", longMsg);
8296 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8297 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008298 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 }
8300
Dan Egnor60d87622009-12-16 16:32:58 -08008301 // If we can't identify the process or it's already exceeded its crash quota,
8302 // quit right away without showing a crash dialog.
8303 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008305 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 }
8307
8308 Message msg = Message.obtain();
8309 msg.what = SHOW_ERROR_MSG;
8310 HashMap data = new HashMap();
8311 data.put("result", result);
8312 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008313 msg.obj = data;
8314 mHandler.sendMessage(msg);
8315
8316 Binder.restoreCallingIdentity(origId);
8317 }
8318
8319 int res = result.get();
8320
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008321 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008323 if (r != null && !r.isolated) {
8324 // XXX Can't keep track of crash time for isolated processes,
8325 // since they don't have a persistent identity.
8326 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008327 SystemClock.uptimeMillis());
8328 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008329 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008330 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008331 }
8332 }
8333
8334 if (appErrorIntent != null) {
8335 try {
8336 mContext.startActivity(appErrorIntent);
8337 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008338 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008341 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008342
8343 Intent createAppErrorIntentLocked(ProcessRecord r,
8344 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8345 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008346 if (report == null) {
8347 return null;
8348 }
8349 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8350 result.setComponent(r.errorReportReceiver);
8351 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8352 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8353 return result;
8354 }
8355
Dan Egnorb7f03672009-12-09 16:22:32 -08008356 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8357 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008358 if (r.errorReportReceiver == null) {
8359 return null;
8360 }
8361
8362 if (!r.crashing && !r.notResponding) {
8363 return null;
8364 }
8365
Dan Egnorb7f03672009-12-09 16:22:32 -08008366 ApplicationErrorReport report = new ApplicationErrorReport();
8367 report.packageName = r.info.packageName;
8368 report.installerPackageName = r.errorReportReceiver.getPackageName();
8369 report.processName = r.processName;
8370 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008371 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008372
Dan Egnorb7f03672009-12-09 16:22:32 -08008373 if (r.crashing) {
8374 report.type = ApplicationErrorReport.TYPE_CRASH;
8375 report.crashInfo = crashInfo;
8376 } else if (r.notResponding) {
8377 report.type = ApplicationErrorReport.TYPE_ANR;
8378 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008379
Dan Egnorb7f03672009-12-09 16:22:32 -08008380 report.anrInfo.activity = r.notRespondingReport.tag;
8381 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8382 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008383 }
8384
Dan Egnorb7f03672009-12-09 16:22:32 -08008385 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008386 }
8387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008389 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 // assume our apps are happy - lazy create the list
8391 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8392
Dianne Hackborn0c380492012-08-20 17:23:30 -07008393 final boolean allUsers = ActivityManager.checkUidPermission(
8394 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8395 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8396 int userId = UserHandle.getUserId(Binder.getCallingUid());
8397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 synchronized (this) {
8399
8400 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008401 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8402 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008403 if (!allUsers && app.userId != userId) {
8404 continue;
8405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8407 // This one's in trouble, so we'll generate a report for it
8408 // crashes are higher priority (in case there's a crash *and* an anr)
8409 ActivityManager.ProcessErrorStateInfo report = null;
8410 if (app.crashing) {
8411 report = app.crashingReport;
8412 } else if (app.notResponding) {
8413 report = app.notRespondingReport;
8414 }
8415
8416 if (report != null) {
8417 if (errList == null) {
8418 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8419 }
8420 errList.add(report);
8421 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008422 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008423 " crashing = " + app.crashing +
8424 " notResponding = " + app.notResponding);
8425 }
8426 }
8427 }
8428 }
8429
8430 return errList;
8431 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008432
8433 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008434 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008435 if (currApp != null) {
8436 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8437 }
8438 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008439 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8440 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008441 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8442 if (currApp != null) {
8443 currApp.lru = 0;
8444 }
8445 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008446 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008447 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8448 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8449 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8450 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8451 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8452 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8453 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8454 } else {
8455 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8456 }
8457 }
8458
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008459 private void fillInProcMemInfo(ProcessRecord app,
8460 ActivityManager.RunningAppProcessInfo outInfo) {
8461 outInfo.pid = app.pid;
8462 outInfo.uid = app.info.uid;
8463 if (mHeavyWeightProcess == app) {
8464 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8465 }
8466 if (app.persistent) {
8467 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8468 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008469 if (app.hasActivities) {
8470 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8471 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008472 outInfo.lastTrimLevel = app.trimMemoryLevel;
8473 int adj = app.curAdj;
8474 outInfo.importance = oomAdjToImportance(adj, outInfo);
8475 outInfo.importanceReasonCode = app.adjTypeCode;
8476 }
8477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008479 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 // Lazy instantiation of list
8481 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008482 final boolean allUsers = ActivityManager.checkUidPermission(
8483 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8484 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8485 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 synchronized (this) {
8487 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008488 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8489 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008490 if (!allUsers && app.userId != userId) {
8491 continue;
8492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8494 // Generate process state info for running application
8495 ActivityManager.RunningAppProcessInfo currApp =
8496 new ActivityManager.RunningAppProcessInfo(app.processName,
8497 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008498 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008499 if (app.adjSource instanceof ProcessRecord) {
8500 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008501 currApp.importanceReasonImportance = oomAdjToImportance(
8502 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008503 } else if (app.adjSource instanceof ActivityRecord) {
8504 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008505 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8506 }
8507 if (app.adjTarget instanceof ComponentName) {
8508 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8509 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008510 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 // + " lru=" + currApp.lru);
8512 if (runList == null) {
8513 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8514 }
8515 runList.add(currApp);
8516 }
8517 }
8518 }
8519 return runList;
8520 }
8521
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008522 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008523 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008524 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8525 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8526 if (runningApps != null && runningApps.size() > 0) {
8527 Set<String> extList = new HashSet<String>();
8528 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8529 if (app.pkgList != null) {
8530 for (String pkg : app.pkgList) {
8531 extList.add(pkg);
8532 }
8533 }
8534 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008535 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008536 for (String pkg : extList) {
8537 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008538 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008539 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8540 retList.add(info);
8541 }
8542 } catch (RemoteException e) {
8543 }
8544 }
8545 }
8546 return retList;
8547 }
8548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008550 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8551 enforceNotIsolatedCaller("getMyMemoryState");
8552 synchronized (this) {
8553 ProcessRecord proc;
8554 synchronized (mPidsSelfLocked) {
8555 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8556 }
8557 fillInProcMemInfo(proc, outInfo);
8558 }
8559 }
8560
8561 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008563 if (checkCallingPermission(android.Manifest.permission.DUMP)
8564 != PackageManager.PERMISSION_GRANTED) {
8565 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8566 + Binder.getCallingPid()
8567 + ", uid=" + Binder.getCallingUid()
8568 + " without permission "
8569 + android.Manifest.permission.DUMP);
8570 return;
8571 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008572
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008574 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008575 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008576
8577 int opti = 0;
8578 while (opti < args.length) {
8579 String opt = args[opti];
8580 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8581 break;
8582 }
8583 opti++;
8584 if ("-a".equals(opt)) {
8585 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008586 } else if ("-c".equals(opt)) {
8587 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 } else if ("-h".equals(opt)) {
8589 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008590 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008591 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008592 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008593 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8594 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8595 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008596 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008597 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008598 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008599 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008600 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008601 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008602 pw.println(" all: dump all activities");
8603 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008604 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008605 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8606 pw.println(" a partial substring in a component name, a");
8607 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008608 pw.println(" -a: include all available server state.");
8609 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 } else {
8612 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008615
8616 long origId = Binder.clearCallingIdentity();
8617 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008618 // Is the caller requesting to dump a particular piece of data?
8619 if (opti < args.length) {
8620 String cmd = args[opti];
8621 opti++;
8622 if ("activities".equals(cmd) || "a".equals(cmd)) {
8623 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008624 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008626 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008627 String[] newArgs;
8628 String name;
8629 if (opti >= args.length) {
8630 name = null;
8631 newArgs = EMPTY_STRING_ARRAY;
8632 } else {
8633 name = args[opti];
8634 opti++;
8635 newArgs = new String[args.length - opti];
8636 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8637 args.length - opti);
8638 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008640 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008642 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008643 String[] newArgs;
8644 String name;
8645 if (opti >= args.length) {
8646 name = null;
8647 newArgs = EMPTY_STRING_ARRAY;
8648 } else {
8649 name = args[opti];
8650 opti++;
8651 newArgs = new String[args.length - opti];
8652 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8653 args.length - opti);
8654 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008655 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008656 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008657 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008658 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008659 String[] newArgs;
8660 String name;
8661 if (opti >= args.length) {
8662 name = null;
8663 newArgs = EMPTY_STRING_ARRAY;
8664 } else {
8665 name = args[opti];
8666 opti++;
8667 newArgs = new String[args.length - opti];
8668 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8669 args.length - opti);
8670 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008671 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008672 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008673 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008674 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8675 synchronized (this) {
8676 dumpOomLocked(fd, pw, args, opti, true);
8677 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008678 } else if ("provider".equals(cmd)) {
8679 String[] newArgs;
8680 String name;
8681 if (opti >= args.length) {
8682 name = null;
8683 newArgs = EMPTY_STRING_ARRAY;
8684 } else {
8685 name = args[opti];
8686 opti++;
8687 newArgs = new String[args.length - opti];
8688 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8689 }
8690 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8691 pw.println("No providers match: " + name);
8692 pw.println("Use -h for help.");
8693 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008694 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8695 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008696 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008699 String[] newArgs;
8700 String name;
8701 if (opti >= args.length) {
8702 name = null;
8703 newArgs = EMPTY_STRING_ARRAY;
8704 } else {
8705 name = args[opti];
8706 opti++;
8707 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008708 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8709 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008710 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008711 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008712 pw.println("No services match: " + name);
8713 pw.println("Use -h for help.");
8714 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 } else if ("package".equals(cmd)) {
8716 String[] newArgs;
8717 if (opti >= args.length) {
8718 pw.println("package: no package name specified");
8719 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008720 } else {
8721 dumpPackage = args[opti];
8722 opti++;
8723 newArgs = new String[args.length - opti];
8724 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8725 args.length - opti);
8726 args = newArgs;
8727 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008728 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8731 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008732 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008733 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008734 } else {
8735 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008736 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8737 pw.println("Bad activity command, or no activities match: " + cmd);
8738 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008739 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008740 }
8741 if (!more) {
8742 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008743 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008744 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008745 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008746
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 // No piece of data specified, dump everything.
8748 synchronized (this) {
8749 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008750 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 if (needSep) {
8752 pw.println(" ");
8753 }
8754 if (dumpAll) {
8755 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008756 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008757 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008758 if (needSep) {
8759 pw.println(" ");
8760 }
8761 if (dumpAll) {
8762 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 if (needSep) {
8766 pw.println(" ");
8767 }
8768 if (dumpAll) {
8769 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008770 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008771 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 if (needSep) {
8773 pw.println(" ");
8774 }
8775 if (dumpAll) {
8776 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008778 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 if (needSep) {
8780 pw.println(" ");
8781 }
8782 if (dumpAll) {
8783 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008784 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008785 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008787 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008789
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008790 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008792 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8793 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8795 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008796 pw.println(" ");
8797 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008798 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8799 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008800 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008802 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008803 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008804 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008806 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008809 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008810 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008811 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008812 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8813 pw.println(" ");
8814 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008815 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008816 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008817 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008818 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 pw.println(" ");
8820 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008821 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008822 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008826 if (mMainStack.mPausingActivity != null) {
8827 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008828 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008829 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008831 if (dumpAll) {
8832 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8833 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008834 pw.println(" mDismissKeyguardOnNextActivity: "
8835 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008838 if (mRecentTasks.size() > 0) {
8839 pw.println();
8840 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841
8842 final int N = mRecentTasks.size();
8843 for (int i=0; i<N; i++) {
8844 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008845 if (dumpPackage != null) {
8846 if (tr.realActivity == null ||
8847 !dumpPackage.equals(tr.realActivity)) {
8848 continue;
8849 }
8850 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8852 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008853 if (dumpAll) {
8854 mRecentTasks.get(i).dump(pw, " ");
8855 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 }
8857 }
8858
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008859 if (dumpAll) {
8860 pw.println(" ");
8861 pw.println(" mCurTask: " + mCurTask);
8862 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008863
8864 return true;
8865 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008866
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008867 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008868 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008869 boolean needSep = false;
8870 int numPers = 0;
8871
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008872 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8873
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008874 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8876 final int NA = procs.size();
8877 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008878 ProcessRecord r = procs.valueAt(ia);
8879 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8880 continue;
8881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882 if (!needSep) {
8883 pw.println(" All known processes:");
8884 needSep = true;
8885 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008886 pw.print(r.persistent ? " *PERS*" : " *APP*");
8887 pw.print(" UID "); pw.print(procs.keyAt(ia));
8888 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 r.dump(pw, " ");
8890 if (r.persistent) {
8891 numPers++;
8892 }
8893 }
8894 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008896
8897 if (mIsolatedProcesses.size() > 0) {
8898 if (needSep) pw.println(" ");
8899 needSep = true;
8900 pw.println(" Isolated process list (sorted by uid):");
8901 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8902 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8903 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8904 continue;
8905 }
8906 pw.println(String.format("%sIsolated #%2d: %s",
8907 " ", i, r.toString()));
8908 }
8909 }
8910
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008911 if (mLruProcesses.size() > 0) {
8912 if (needSep) pw.println(" ");
8913 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008914 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008915 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008916 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008917 needSep = true;
8918 }
8919
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008920 if (dumpAll) {
8921 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008922 boolean printed = false;
8923 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8924 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8925 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8926 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008928 if (!printed) {
8929 if (needSep) pw.println(" ");
8930 needSep = true;
8931 pw.println(" PID mappings:");
8932 printed = true;
8933 }
8934 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8935 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 }
8937 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008938 }
8939
8940 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008941 synchronized (mPidsSelfLocked) {
8942 boolean printed = false;
8943 for (int i=0; i<mForegroundProcesses.size(); i++) {
8944 ProcessRecord r = mPidsSelfLocked.get(
8945 mForegroundProcesses.valueAt(i).pid);
8946 if (dumpPackage != null && (r == null
8947 || !dumpPackage.equals(r.info.packageName))) {
8948 continue;
8949 }
8950 if (!printed) {
8951 if (needSep) pw.println(" ");
8952 needSep = true;
8953 pw.println(" Foreground Processes:");
8954 printed = true;
8955 }
8956 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8957 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 }
8961
8962 if (mPersistentStartingProcesses.size() > 0) {
8963 if (needSep) pw.println(" ");
8964 needSep = true;
8965 pw.println(" Persisent processes that are starting:");
8966 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008967 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008970 if (mRemovedProcesses.size() > 0) {
8971 if (needSep) pw.println(" ");
8972 needSep = true;
8973 pw.println(" Processes that are being removed:");
8974 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008975 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008976 }
8977
8978 if (mProcessesOnHold.size() > 0) {
8979 if (needSep) pw.println(" ");
8980 needSep = true;
8981 pw.println(" Processes that are on old until the system is ready:");
8982 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008983 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008986 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987
8988 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008989 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 long now = SystemClock.uptimeMillis();
8991 for (Map.Entry<String, SparseArray<Long>> procs
8992 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 SparseArray<Long> uids = procs.getValue();
8995 final int N = uids.size();
8996 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008997 int puid = uids.keyAt(i);
8998 ProcessRecord r = mProcessNames.get(pname, puid);
8999 if (dumpPackage != null && (r == null
9000 || !dumpPackage.equals(r.info.packageName))) {
9001 continue;
9002 }
9003 if (!printed) {
9004 if (needSep) pw.println(" ");
9005 needSep = true;
9006 pw.println(" Time since processes crashed:");
9007 printed = true;
9008 }
9009 pw.print(" Process "); pw.print(pname);
9010 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009012 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9013 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009014 }
9015 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009017
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 for (Map.Entry<String, SparseArray<Long>> procs
9021 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009022 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009023 SparseArray<Long> uids = procs.getValue();
9024 final int N = uids.size();
9025 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009026 int puid = uids.keyAt(i);
9027 ProcessRecord r = mProcessNames.get(pname, puid);
9028 if (dumpPackage != null && (r == null
9029 || !dumpPackage.equals(r.info.packageName))) {
9030 continue;
9031 }
9032 if (!printed) {
9033 if (needSep) pw.println(" ");
9034 needSep = true;
9035 pw.println(" Bad processes:");
9036 }
9037 pw.print(" Bad process "); pw.print(pname);
9038 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009039 pw.print(": crashed at time ");
9040 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 }
9042 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009045 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009047 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009048 if (dumpAll) {
9049 StringBuilder sb = new StringBuilder(128);
9050 sb.append(" mPreviousProcessVisibleTime: ");
9051 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9052 pw.println(sb);
9053 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009054 if (mHeavyWeightProcess != null) {
9055 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9056 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009058 if (dumpAll) {
9059 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009060 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009061 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009062 for (Map.Entry<String, Integer> entry
9063 : mCompatModePackages.getPackages().entrySet()) {
9064 String pkg = entry.getKey();
9065 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009066 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9067 continue;
9068 }
9069 if (!printed) {
9070 pw.println(" mScreenCompatPackages:");
9071 printed = true;
9072 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009073 pw.print(" "); pw.print(pkg); pw.print(": ");
9074 pw.print(mode); pw.println();
9075 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009076 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009077 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009078 if (mSleeping || mWentToSleep || mLockScreenShown) {
9079 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9080 + " mLockScreenShown " + mLockScreenShown);
9081 }
9082 if (mShuttingDown) {
9083 pw.println(" mShuttingDown=" + mShuttingDown);
9084 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009085 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9086 || mOrigWaitForDebugger) {
9087 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9088 + " mDebugTransient=" + mDebugTransient
9089 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9090 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009091 if (mOpenGlTraceApp != null) {
9092 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9093 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009094 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9095 || mProfileFd != null) {
9096 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9097 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9098 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9099 + mAutoStopProfiler);
9100 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009101 if (mAlwaysFinishActivities || mController != null) {
9102 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9103 + " mController=" + mController);
9104 }
9105 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009108 + " mProcessesReady=" + mProcessesReady
9109 + " mSystemReady=" + mSystemReady);
9110 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 + " mBooted=" + mBooted
9112 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009113 pw.print(" mLastPowerCheckRealtime=");
9114 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9115 pw.println("");
9116 pw.print(" mLastPowerCheckUptime=");
9117 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9118 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009119 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9120 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009121 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009122 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9123 + " mNumHiddenProcs=" + mNumHiddenProcs
9124 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009125 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009126 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127
9128 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 }
9130
Dianne Hackborn287952c2010-09-22 22:34:31 -07009131 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009132 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009133 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009134 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009135 long now = SystemClock.uptimeMillis();
9136 for (int i=0; i<mProcessesToGc.size(); i++) {
9137 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009138 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9139 continue;
9140 }
9141 if (!printed) {
9142 if (needSep) pw.println(" ");
9143 needSep = true;
9144 pw.println(" Processes that are waiting to GC:");
9145 printed = true;
9146 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009147 pw.print(" Process "); pw.println(proc);
9148 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9149 pw.print(", last gced=");
9150 pw.print(now-proc.lastRequestedGc);
9151 pw.print(" ms ago, last lowMem=");
9152 pw.print(now-proc.lastLowMemory);
9153 pw.println(" ms ago");
9154
9155 }
9156 }
9157 return needSep;
9158 }
9159
9160 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9161 int opti, boolean dumpAll) {
9162 boolean needSep = false;
9163
9164 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009165 if (needSep) pw.println(" ");
9166 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009167 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009168 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009169 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009170 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9171 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9172 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9173 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9174 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009175 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009176 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009177 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009178 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009179 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009180 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009181
9182 if (needSep) pw.println(" ");
9183 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009184 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009185 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009187 needSep = true;
9188 }
9189
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009191
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009192 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009193 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009194 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009195 if (mHeavyWeightProcess != null) {
9196 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9197 }
9198
9199 return true;
9200 }
9201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009202 /**
9203 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009204 * - no provider specified: dump all the providers
9205 * - a flattened component name that matched an existing provider was specified as the
9206 * first arg: dump that one provider
9207 * - the first arg isn't the flattened component name of an existing provider:
9208 * dump all providers whose component contains the first arg as a substring
9209 */
9210 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9211 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009212 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009213 }
9214
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009215 static class ItemMatcher {
9216 ArrayList<ComponentName> components;
9217 ArrayList<String> strings;
9218 ArrayList<Integer> objects;
9219 boolean all;
9220
9221 ItemMatcher() {
9222 all = true;
9223 }
9224
9225 void build(String name) {
9226 ComponentName componentName = ComponentName.unflattenFromString(name);
9227 if (componentName != null) {
9228 if (components == null) {
9229 components = new ArrayList<ComponentName>();
9230 }
9231 components.add(componentName);
9232 all = false;
9233 } else {
9234 int objectId = 0;
9235 // Not a '/' separated full component name; maybe an object ID?
9236 try {
9237 objectId = Integer.parseInt(name, 16);
9238 if (objects == null) {
9239 objects = new ArrayList<Integer>();
9240 }
9241 objects.add(objectId);
9242 all = false;
9243 } catch (RuntimeException e) {
9244 // Not an integer; just do string match.
9245 if (strings == null) {
9246 strings = new ArrayList<String>();
9247 }
9248 strings.add(name);
9249 all = false;
9250 }
9251 }
9252 }
9253
9254 int build(String[] args, int opti) {
9255 for (; opti<args.length; opti++) {
9256 String name = args[opti];
9257 if ("--".equals(name)) {
9258 return opti+1;
9259 }
9260 build(name);
9261 }
9262 return opti;
9263 }
9264
9265 boolean match(Object object, ComponentName comp) {
9266 if (all) {
9267 return true;
9268 }
9269 if (components != null) {
9270 for (int i=0; i<components.size(); i++) {
9271 if (components.get(i).equals(comp)) {
9272 return true;
9273 }
9274 }
9275 }
9276 if (objects != null) {
9277 for (int i=0; i<objects.size(); i++) {
9278 if (System.identityHashCode(object) == objects.get(i)) {
9279 return true;
9280 }
9281 }
9282 }
9283 if (strings != null) {
9284 String flat = comp.flattenToString();
9285 for (int i=0; i<strings.size(); i++) {
9286 if (flat.contains(strings.get(i))) {
9287 return true;
9288 }
9289 }
9290 }
9291 return false;
9292 }
9293 }
9294
Dianne Hackborn625ac272010-09-17 18:29:22 -07009295 /**
9296 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009297 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009298 * - the cmd arg isn't the flattened component name of an existing activity:
9299 * dump all activity whose component contains the cmd as a substring
9300 * - A hex number of the ActivityRecord object instance.
9301 */
9302 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9303 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009304 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009305
9306 if ("all".equals(name)) {
9307 synchronized (this) {
9308 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009309 activities.add(r1);
9310 }
9311 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009312 } else if ("top".equals(name)) {
9313 synchronized (this) {
9314 final int N = mMainStack.mHistory.size();
9315 if (N > 0) {
9316 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9317 }
9318 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009319 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009320 ItemMatcher matcher = new ItemMatcher();
9321 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009322
9323 synchronized (this) {
9324 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009325 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009326 activities.add(r1);
9327 }
9328 }
9329 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009330 }
9331
9332 if (activities.size() <= 0) {
9333 return false;
9334 }
9335
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009336 String[] newArgs = new String[args.length - opti];
9337 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9338
Dianne Hackborn30d71892010-12-11 10:37:55 -08009339 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009340 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009341 for (int i=activities.size()-1; i>=0; i--) {
9342 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009343 if (needSep) {
9344 pw.println();
9345 }
9346 needSep = true;
9347 synchronized (this) {
9348 if (lastTask != r.task) {
9349 lastTask = r.task;
9350 pw.print("TASK "); pw.print(lastTask.affinity);
9351 pw.print(" id="); pw.println(lastTask.taskId);
9352 if (dumpAll) {
9353 lastTask.dump(pw, " ");
9354 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009355 }
9356 }
9357 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009358 }
9359 return true;
9360 }
9361
9362 /**
9363 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9364 * there is a thread associated with the activity.
9365 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009366 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009367 final ActivityRecord r, String[] args, boolean dumpAll) {
9368 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009369 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009370 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9371 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9372 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009373 if (r.app != null) pw.println(r.app.pid);
9374 else pw.println("(not running)");
9375 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009376 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009377 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009378 }
9379 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009380 // flush anything that is already in the PrintWriter since the thread is going
9381 // to write to the file descriptor directly
9382 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009383 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009384 TransferPipe tp = new TransferPipe();
9385 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009386 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9387 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009388 tp.go(fd);
9389 } finally {
9390 tp.kill();
9391 }
9392 } catch (IOException e) {
9393 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009394 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009395 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009396 }
9397 }
9398 }
9399
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009400 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009401 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 boolean needSep = false;
9403
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009404 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009406 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009407 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009408 Iterator it = mRegisteredReceivers.values().iterator();
9409 while (it.hasNext()) {
9410 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009411 if (dumpPackage != null && (r.app == null ||
9412 !dumpPackage.equals(r.app.info.packageName))) {
9413 continue;
9414 }
9415 if (!printed) {
9416 pw.println(" Registered Receivers:");
9417 needSep = true;
9418 printed = true;
9419 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009420 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009421 r.dump(pw, " ");
9422 }
9423 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009424
9425 if (mReceiverResolver.dump(pw, needSep ?
9426 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9427 " ", dumpPackage, false)) {
9428 needSep = true;
9429 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009430 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009431
9432 for (BroadcastQueue q : mBroadcastQueues) {
9433 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009435
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009436 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009437
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009438 if (mStickyBroadcasts != null && dumpPackage == null) {
9439 if (needSep) {
9440 pw.println();
9441 }
9442 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009443 pw.println(" Sticky broadcasts:");
9444 StringBuilder sb = new StringBuilder(128);
9445 for (Map.Entry<String, ArrayList<Intent>> ent
9446 : mStickyBroadcasts.entrySet()) {
9447 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009448 if (dumpAll) {
9449 pw.println(":");
9450 ArrayList<Intent> intents = ent.getValue();
9451 final int N = intents.size();
9452 for (int i=0; i<N; i++) {
9453 sb.setLength(0);
9454 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009455 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009456 pw.println(sb.toString());
9457 Bundle bundle = intents.get(i).getExtras();
9458 if (bundle != null) {
9459 pw.print(" ");
9460 pw.println(bundle.toString());
9461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009462 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 } else {
9464 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009465 }
9466 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009467 needSep = true;
9468 }
9469
9470 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009471 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009472 for (BroadcastQueue queue : mBroadcastQueues) {
9473 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9474 + queue.mBroadcastsScheduled);
9475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009476 pw.println(" mHandler:");
9477 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009478 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009479 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009480
9481 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009482 }
9483
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009485 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009486 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009488 ItemMatcher matcher = new ItemMatcher();
9489 matcher.build(args, opti);
9490
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009491 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009492
9493 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009494
9495 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009496 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009497 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009498 ContentProviderRecord r = mLaunchingProviders.get(i);
9499 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9500 continue;
9501 }
9502 if (!printed) {
9503 if (needSep) pw.println(" ");
9504 needSep = true;
9505 pw.println(" Launching content providers:");
9506 printed = true;
9507 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009508 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009509 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511 }
9512
9513 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009514 if (needSep) pw.println();
9515 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009516 pw.println("Granted Uri Permissions:");
9517 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9518 int uid = mGrantedUriPermissions.keyAt(i);
9519 HashMap<Uri, UriPermission> perms
9520 = mGrantedUriPermissions.valueAt(i);
9521 pw.print(" * UID "); pw.print(uid);
9522 pw.println(" holds:");
9523 for (UriPermission perm : perms.values()) {
9524 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 if (dumpAll) {
9526 perm.dump(pw, " ");
9527 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009528 }
9529 }
9530 needSep = true;
9531 }
9532
9533 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009534 }
9535
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009536 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009537 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009538 boolean needSep = false;
9539
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009540 if (mIntentSenderRecords.size() > 0) {
9541 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 Iterator<WeakReference<PendingIntentRecord>> it
9543 = mIntentSenderRecords.values().iterator();
9544 while (it.hasNext()) {
9545 WeakReference<PendingIntentRecord> ref = it.next();
9546 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009547 if (dumpPackage != null && (rec == null
9548 || !dumpPackage.equals(rec.key.packageName))) {
9549 continue;
9550 }
9551 if (!printed) {
9552 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9553 printed = true;
9554 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009555 needSep = true;
9556 if (rec != null) {
9557 pw.print(" * "); pw.println(rec);
9558 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009561 } else {
9562 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 }
9564 }
9565 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566
9567 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009568 }
9569
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009570 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009571 String prefix, String label, boolean complete, boolean brief, boolean client,
9572 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009574 boolean needNL = false;
9575 final String innerPrefix = prefix + " ";
9576 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009579 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9580 continue;
9581 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009582 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009583 if (needNL) {
9584 pw.println(" ");
9585 needNL = false;
9586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009587 if (lastTask != r.task) {
9588 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009589 pw.print(prefix);
9590 pw.print(full ? "* " : " ");
9591 pw.println(lastTask);
9592 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009593 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009594 } else if (complete) {
9595 // Complete + brief == give a summary. Isn't that obvious?!?
9596 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009597 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009598 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009599 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009601 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009602 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9603 pw.print(" #"); pw.print(i); pw.print(": ");
9604 pw.println(r);
9605 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009606 r.dump(pw, innerPrefix);
9607 } else if (complete) {
9608 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009609 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009610 if (r.app != null) {
9611 pw.print(innerPrefix); pw.println(r.app);
9612 }
9613 }
9614 if (client && r.app != null && r.app.thread != null) {
9615 // flush anything that is already in the PrintWriter since the thread is going
9616 // to write to the file descriptor directly
9617 pw.flush();
9618 try {
9619 TransferPipe tp = new TransferPipe();
9620 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009621 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9622 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009623 // Short timeout, since blocking here can
9624 // deadlock with the application.
9625 tp.go(fd, 2000);
9626 } finally {
9627 tp.kill();
9628 }
9629 } catch (IOException e) {
9630 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9631 } catch (RemoteException e) {
9632 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9633 }
9634 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 }
9637 }
9638
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009639 private static String buildOomTag(String prefix, String space, int val, int base) {
9640 if (val == base) {
9641 if (space == null) return prefix;
9642 return prefix + " ";
9643 }
9644 return prefix + "+" + Integer.toString(val-base);
9645 }
9646
9647 private static final int dumpProcessList(PrintWriter pw,
9648 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009649 String prefix, String normalLabel, String persistentLabel,
9650 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009652 final int N = list.size()-1;
9653 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009655 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9656 continue;
9657 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009658 pw.println(String.format("%s%s #%2d: %s",
9659 prefix, (r.persistent ? persistentLabel : normalLabel),
9660 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661 if (r.persistent) {
9662 numPers++;
9663 }
9664 }
9665 return numPers;
9666 }
9667
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009668 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009669 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009670 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009671 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009672
Dianne Hackborn905577f2011-09-07 18:31:28 -07009673 ArrayList<Pair<ProcessRecord, Integer>> list
9674 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9675 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009676 ProcessRecord r = origList.get(i);
9677 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9678 continue;
9679 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009680 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9681 }
9682
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009683 if (list.size() <= 0) {
9684 return false;
9685 }
9686
Dianne Hackborn905577f2011-09-07 18:31:28 -07009687 Comparator<Pair<ProcessRecord, Integer>> comparator
9688 = new Comparator<Pair<ProcessRecord, Integer>>() {
9689 @Override
9690 public int compare(Pair<ProcessRecord, Integer> object1,
9691 Pair<ProcessRecord, Integer> object2) {
9692 if (object1.first.setAdj != object2.first.setAdj) {
9693 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9694 }
9695 if (object1.second.intValue() != object2.second.intValue()) {
9696 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9697 }
9698 return 0;
9699 }
9700 };
9701
9702 Collections.sort(list, comparator);
9703
Dianne Hackborn287952c2010-09-22 22:34:31 -07009704 final long curRealtime = SystemClock.elapsedRealtime();
9705 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9706 final long curUptime = SystemClock.uptimeMillis();
9707 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9708
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009709 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009710 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009711 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009712 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009713 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009714 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9715 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009716 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9717 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009718 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9719 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009720 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9721 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009722 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009723 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009724 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9725 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9726 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9727 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9728 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9729 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9730 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9731 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009732 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9733 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009734 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9735 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009736 } else {
9737 oomAdj = Integer.toString(r.setAdj);
9738 }
9739 String schedGroup;
9740 switch (r.setSchedGroup) {
9741 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9742 schedGroup = "B";
9743 break;
9744 case Process.THREAD_GROUP_DEFAULT:
9745 schedGroup = "F";
9746 break;
9747 default:
9748 schedGroup = Integer.toString(r.setSchedGroup);
9749 break;
9750 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009751 String foreground;
9752 if (r.foregroundActivities) {
9753 foreground = "A";
9754 } else if (r.foregroundServices) {
9755 foreground = "S";
9756 } else {
9757 foreground = " ";
9758 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009759 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009760 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009761 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9762 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009763 if (r.adjSource != null || r.adjTarget != null) {
9764 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009766 if (r.adjTarget instanceof ComponentName) {
9767 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9768 } else if (r.adjTarget != null) {
9769 pw.print(r.adjTarget.toString());
9770 } else {
9771 pw.print("{null}");
9772 }
9773 pw.print("<=");
9774 if (r.adjSource instanceof ProcessRecord) {
9775 pw.print("Proc{");
9776 pw.print(((ProcessRecord)r.adjSource).toShortString());
9777 pw.println("}");
9778 } else if (r.adjSource != null) {
9779 pw.println(r.adjSource.toString());
9780 } else {
9781 pw.println("{null}");
9782 }
9783 }
9784 if (inclDetails) {
9785 pw.print(prefix);
9786 pw.print(" ");
9787 pw.print("oom: max="); pw.print(r.maxAdj);
9788 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009789 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009790 pw.print(" curRaw="); pw.print(r.curRawAdj);
9791 pw.print(" setRaw="); pw.print(r.setRawAdj);
9792 pw.print(" cur="); pw.print(r.curAdj);
9793 pw.print(" set="); pw.println(r.setAdj);
9794 pw.print(prefix);
9795 pw.print(" ");
9796 pw.print("keeping="); pw.print(r.keeping);
9797 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009798 pw.print(" empty="); pw.print(r.empty);
9799 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009800
9801 if (!r.keeping) {
9802 if (r.lastWakeTime != 0) {
9803 long wtime;
9804 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9805 synchronized (stats) {
9806 wtime = stats.getProcessWakeTime(r.info.uid,
9807 r.pid, curRealtime);
9808 }
9809 long timeUsed = wtime - r.lastWakeTime;
9810 pw.print(prefix);
9811 pw.print(" ");
9812 pw.print("keep awake over ");
9813 TimeUtils.formatDuration(realtimeSince, pw);
9814 pw.print(" used ");
9815 TimeUtils.formatDuration(timeUsed, pw);
9816 pw.print(" (");
9817 pw.print((timeUsed*100)/realtimeSince);
9818 pw.println("%)");
9819 }
9820 if (r.lastCpuTime != 0) {
9821 long timeUsed = r.curCpuTime - r.lastCpuTime;
9822 pw.print(prefix);
9823 pw.print(" ");
9824 pw.print("run cpu over ");
9825 TimeUtils.formatDuration(uptimeSince, pw);
9826 pw.print(" used ");
9827 TimeUtils.formatDuration(timeUsed, pw);
9828 pw.print(" (");
9829 pw.print((timeUsed*100)/uptimeSince);
9830 pw.println("%)");
9831 }
9832 }
9833 }
9834 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009835 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009836 }
9837
Dianne Hackbornb437e092011-08-05 17:50:29 -07009838 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009839 ArrayList<ProcessRecord> procs;
9840 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009841 if (args != null && args.length > start
9842 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009843 procs = new ArrayList<ProcessRecord>();
9844 int pid = -1;
9845 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009846 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 } catch (NumberFormatException e) {
9848
9849 }
9850 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9851 ProcessRecord proc = mLruProcesses.get(i);
9852 if (proc.pid == pid) {
9853 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009854 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009855 procs.add(proc);
9856 }
9857 }
9858 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009859 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 return null;
9861 }
9862 } else {
9863 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9864 }
9865 }
9866 return procs;
9867 }
9868
9869 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9870 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009872 if (procs == null) {
9873 return;
9874 }
9875
9876 long uptime = SystemClock.uptimeMillis();
9877 long realtime = SystemClock.elapsedRealtime();
9878 pw.println("Applications Graphics Acceleration Info:");
9879 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9880
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009881 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9882 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009883 if (r.thread != null) {
9884 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9885 pw.flush();
9886 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009887 TransferPipe tp = new TransferPipe();
9888 try {
9889 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9890 tp.go(fd);
9891 } finally {
9892 tp.kill();
9893 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009894 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009895 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009896 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009897 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009898 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009899 pw.flush();
9900 }
9901 }
9902 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009903 }
9904
Jeff Brown6754ba22011-12-14 20:20:01 -08009905 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9906 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9907 if (procs == null) {
9908 return;
9909 }
9910
9911 pw.println("Applications Database Info:");
9912
9913 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9914 ProcessRecord r = procs.get(i);
9915 if (r.thread != null) {
9916 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9917 pw.flush();
9918 try {
9919 TransferPipe tp = new TransferPipe();
9920 try {
9921 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9922 tp.go(fd);
9923 } finally {
9924 tp.kill();
9925 }
9926 } catch (IOException e) {
9927 pw.println("Failure while dumping the app: " + r);
9928 pw.flush();
9929 } catch (RemoteException e) {
9930 pw.println("Got a RemoteException while dumping the app " + r);
9931 pw.flush();
9932 }
9933 }
9934 }
9935 }
9936
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009937 final static class MemItem {
9938 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009939 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009940 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009941 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009942 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009943
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009944 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009945 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009946 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009947 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009948 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009949 }
9950 }
9951
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009952 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009953 boolean sort) {
9954 if (sort) {
9955 Collections.sort(items, new Comparator<MemItem>() {
9956 @Override
9957 public int compare(MemItem lhs, MemItem rhs) {
9958 if (lhs.pss < rhs.pss) {
9959 return 1;
9960 } else if (lhs.pss > rhs.pss) {
9961 return -1;
9962 }
9963 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009964 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009965 });
9966 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009967
9968 for (int i=0; i<items.size(); i++) {
9969 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009970 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009971 if (mi.subitems != null) {
9972 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9973 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009974 }
9975 }
9976
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009977 // These are in KB.
9978 static final long[] DUMP_MEM_BUCKETS = new long[] {
9979 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9980 120*1024, 160*1024, 200*1024,
9981 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9982 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9983 };
9984
Dianne Hackborn672342c2011-11-29 11:29:02 -08009985 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9986 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009987 int start = label.lastIndexOf('.');
9988 if (start >= 0) start++;
9989 else start = 0;
9990 int end = label.length();
9991 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9992 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9993 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9994 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009995 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009996 out.append(label, start, end);
9997 return;
9998 }
9999 }
10000 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010001 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010002 out.append(label, start, end);
10003 }
10004
10005 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10006 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10007 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10008 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10009 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10010 };
10011 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10012 "System", "Persistent", "Foreground",
10013 "Visible", "Perceptible", "Heavy Weight",
10014 "Backup", "A Services", "Home", "Previous",
10015 "B Services", "Background"
10016 };
10017
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010018 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010019 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010020 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010021 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010022 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010023
10024 int opti = 0;
10025 while (opti < args.length) {
10026 String opt = args[opti];
10027 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10028 break;
10029 }
10030 opti++;
10031 if ("-a".equals(opt)) {
10032 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010033 } else if ("--oom".equals(opt)) {
10034 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010035 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010036 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010037 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010038 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010039 pw.println("If [process] is specified it can be the name or ");
10040 pw.println("pid of a specific process to dump.");
10041 return;
10042 } else {
10043 pw.println("Unknown argument: " + opt + "; use -h for help");
10044 }
10045 }
10046
10047 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 if (procs == null) {
10049 return;
10050 }
10051
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010052 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010053 long uptime = SystemClock.uptimeMillis();
10054 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010055
10056 if (procs.size() == 1 || isCheckinRequest) {
10057 dumpAll = true;
10058 }
10059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010060 if (isCheckinRequest) {
10061 // short checkin version
10062 pw.println(uptime + "," + realtime);
10063 pw.flush();
10064 } else {
10065 pw.println("Applications Memory Usage (kB):");
10066 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10067 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010068
Dianne Hackbornb437e092011-08-05 17:50:29 -070010069 String[] innerArgs = new String[args.length-opti];
10070 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10071
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010072 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10073 long nativePss=0, dalvikPss=0, otherPss=0;
10074 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10075
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010076 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10077 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10078 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010079
10080 long totalPss = 0;
10081
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010082 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10083 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010084 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010085 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010086 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10087 pw.flush();
10088 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010089 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010090 if (dumpAll) {
10091 try {
10092 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10093 } catch (RemoteException e) {
10094 if (!isCheckinRequest) {
10095 pw.println("Got RemoteException!");
10096 pw.flush();
10097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010098 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010099 } else {
10100 mi = new Debug.MemoryInfo();
10101 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010102 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010103
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010104 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010105 long myTotalPss = mi.getTotalPss();
10106 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010107 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010108 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010109 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010110
10111 nativePss += mi.nativePss;
10112 dalvikPss += mi.dalvikPss;
10113 otherPss += mi.otherPss;
10114 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10115 long mem = mi.getOtherPss(j);
10116 miscPss[j] += mem;
10117 otherPss -= mem;
10118 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010119
10120 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010121 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10122 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010123 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010124 if (oomProcs[oomIndex] == null) {
10125 oomProcs[oomIndex] = new ArrayList<MemItem>();
10126 }
10127 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128 break;
10129 }
10130 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010132 }
10133 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010134
10135 if (!isCheckinRequest && procs.size() > 1) {
10136 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10137
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010138 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10139 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10140 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010141 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010142 String label = Debug.MemoryInfo.getOtherLabel(j);
10143 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010144 }
10145
Dianne Hackbornb437e092011-08-05 17:50:29 -070010146 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10147 for (int j=0; j<oomPss.length; j++) {
10148 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010149 String label = DUMP_MEM_OOM_LABEL[j];
10150 MemItem item = new MemItem(label, label, oomPss[j],
10151 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010152 item.subitems = oomProcs[j];
10153 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010154 }
10155 }
10156
Dianne Hackborn672342c2011-11-29 11:29:02 -080010157 if (outTag != null || outStack != null) {
10158 if (outTag != null) {
10159 appendMemBucket(outTag, totalPss, "total", false);
10160 }
10161 if (outStack != null) {
10162 appendMemBucket(outStack, totalPss, "total", true);
10163 }
10164 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010165 for (int i=0; i<oomMems.size(); i++) {
10166 MemItem miCat = oomMems.get(i);
10167 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10168 continue;
10169 }
10170 if (miCat.id < ProcessList.SERVICE_ADJ
10171 || miCat.id == ProcessList.HOME_APP_ADJ
10172 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010173 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10174 outTag.append(" / ");
10175 }
10176 if (outStack != null) {
10177 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10178 if (firstLine) {
10179 outStack.append(":");
10180 firstLine = false;
10181 }
10182 outStack.append("\n\t at ");
10183 } else {
10184 outStack.append("$");
10185 }
10186 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010187 for (int j=0; j<miCat.subitems.size(); j++) {
10188 MemItem mi = miCat.subitems.get(j);
10189 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010190 if (outTag != null) {
10191 outTag.append(" ");
10192 }
10193 if (outStack != null) {
10194 outStack.append("$");
10195 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010196 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010197 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10198 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10199 }
10200 if (outStack != null) {
10201 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10202 }
10203 }
10204 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10205 outStack.append("(");
10206 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10207 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10208 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10209 outStack.append(":");
10210 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10211 }
10212 }
10213 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010214 }
10215 }
10216 }
10217 }
10218
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010219 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010220 pw.println();
10221 pw.println("Total PSS by process:");
10222 dumpMemItems(pw, " ", procMems, true);
10223 pw.println();
10224 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010225 pw.println("Total PSS by OOM adjustment:");
10226 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010227 if (!oomOnly) {
10228 PrintWriter out = categoryPw != null ? categoryPw : pw;
10229 out.println();
10230 out.println("Total PSS by category:");
10231 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010232 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010233 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010234 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010235 final int[] SINGLE_LONG_FORMAT = new int[] {
10236 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10237 };
10238 long[] longOut = new long[1];
10239 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10240 SINGLE_LONG_FORMAT, null, longOut, null);
10241 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10242 longOut[0] = 0;
10243 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10244 SINGLE_LONG_FORMAT, null, longOut, null);
10245 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10246 longOut[0] = 0;
10247 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10248 SINGLE_LONG_FORMAT, null, longOut, null);
10249 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10250 longOut[0] = 0;
10251 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10252 SINGLE_LONG_FORMAT, null, longOut, null);
10253 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10254 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10255 pw.print(shared); pw.println(" kB");
10256 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10257 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010259 }
10260
10261 /**
10262 * Searches array of arguments for the specified string
10263 * @param args array of argument strings
10264 * @param value value to search for
10265 * @return true if the value is contained in the array
10266 */
10267 private static boolean scanArgs(String[] args, String value) {
10268 if (args != null) {
10269 for (String arg : args) {
10270 if (value.equals(arg)) {
10271 return true;
10272 }
10273 }
10274 }
10275 return false;
10276 }
10277
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010278 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10279 ContentProviderRecord cpr, boolean always) {
10280 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10281
10282 if (!inLaunching || always) {
10283 synchronized (cpr) {
10284 cpr.launchingApp = null;
10285 cpr.notifyAll();
10286 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010287 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010288 String names[] = cpr.info.authority.split(";");
10289 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010290 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010291 }
10292 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010293
10294 for (int i=0; i<cpr.connections.size(); i++) {
10295 ContentProviderConnection conn = cpr.connections.get(i);
10296 if (conn.waiting) {
10297 // If this connection is waiting for the provider, then we don't
10298 // need to mess with its process unless we are always removing
10299 // or for some reason the provider is not currently launching.
10300 if (inLaunching && !always) {
10301 continue;
10302 }
10303 }
10304 ProcessRecord capp = conn.client;
10305 conn.dead = true;
10306 if (conn.stableCount > 0) {
10307 if (!capp.persistent && capp.thread != null
10308 && capp.pid != 0
10309 && capp.pid != MY_PID) {
10310 Slog.i(TAG, "Kill " + capp.processName
10311 + " (pid " + capp.pid + "): provider " + cpr.info.name
10312 + " in dying process " + (proc != null ? proc.processName : "??"));
10313 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10314 capp.processName, capp.setAdj, "dying provider "
10315 + cpr.name.toShortString());
10316 Process.killProcessQuiet(capp.pid);
10317 }
10318 } else if (capp.thread != null && conn.provider.provider != null) {
10319 try {
10320 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10321 } catch (RemoteException e) {
10322 }
10323 // In the protocol here, we don't expect the client to correctly
10324 // clean up this connection, we'll just remove it.
10325 cpr.connections.remove(i);
10326 conn.client.conProviders.remove(conn);
10327 }
10328 }
10329
10330 if (inLaunching && always) {
10331 mLaunchingProviders.remove(cpr);
10332 }
10333 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 }
10335
10336 /**
10337 * Main code for cleaning up a process when it has gone away. This is
10338 * called both as a result of the process dying, or directly when stopping
10339 * a process when running in single process mode.
10340 */
10341 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010342 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010343 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010344 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010345 }
10346
Dianne Hackborn36124872009-10-08 16:22:03 -070010347 mProcessesToGc.remove(app);
10348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010349 // Dismiss any open dialogs.
10350 if (app.crashDialog != null) {
10351 app.crashDialog.dismiss();
10352 app.crashDialog = null;
10353 }
10354 if (app.anrDialog != null) {
10355 app.anrDialog.dismiss();
10356 app.anrDialog = null;
10357 }
10358 if (app.waitDialog != null) {
10359 app.waitDialog.dismiss();
10360 app.waitDialog = null;
10361 }
10362
10363 app.crashing = false;
10364 app.notResponding = false;
10365
10366 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010367 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010368 app.thread = null;
10369 app.forcingToForeground = null;
10370 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010371 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010372 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010373 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010375 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010376
10377 boolean restart = false;
10378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010379 // Remove published content providers.
10380 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010381 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010383 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010384
10385 final boolean always = app.bad || !allowRestart;
10386 if (removeDyingProviderLocked(app, cpr, always) || always) {
10387 // We left the provider in the launching list, need to
10388 // restart it.
10389 restart = true;
10390 }
10391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010392 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010393 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 }
10395 app.pubProviders.clear();
10396 }
10397
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010398 // Take care of any launching providers waiting for this process.
10399 if (checkAppInLaunchingProvidersLocked(app, false)) {
10400 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010403 // Unregister from connected content providers.
10404 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010405 for (int i=0; i<app.conProviders.size(); i++) {
10406 ContentProviderConnection conn = app.conProviders.get(i);
10407 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010408 }
10409 app.conProviders.clear();
10410 }
10411
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010412 // At this point there may be remaining entries in mLaunchingProviders
10413 // where we were the only one waiting, so they are no longer of use.
10414 // Look for these and clean up if found.
10415 // XXX Commented out for now. Trying to figure out a way to reproduce
10416 // the actual situation to identify what is actually going on.
10417 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010418 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010419 ContentProviderRecord cpr = (ContentProviderRecord)
10420 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010421 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010422 synchronized (cpr) {
10423 cpr.launchingApp = null;
10424 cpr.notifyAll();
10425 }
10426 }
10427 }
10428 }
10429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 skipCurrentReceiverLocked(app);
10431
10432 // Unregister any receivers.
10433 if (app.receivers.size() > 0) {
10434 Iterator<ReceiverList> it = app.receivers.iterator();
10435 while (it.hasNext()) {
10436 removeReceiverLocked(it.next());
10437 }
10438 app.receivers.clear();
10439 }
10440
Christopher Tate181fafa2009-05-14 11:12:14 -070010441 // If the app is undergoing backup, tell the backup manager about it
10442 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010443 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010444 try {
10445 IBackupManager bm = IBackupManager.Stub.asInterface(
10446 ServiceManager.getService(Context.BACKUP_SERVICE));
10447 bm.agentDisconnected(app.info.packageName);
10448 } catch (RemoteException e) {
10449 // can't happen; backup manager is local
10450 }
10451 }
10452
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010453 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10454 ProcessChangeItem item = mPendingProcessChanges.get(i);
10455 if (item.pid == app.pid) {
10456 mPendingProcessChanges.remove(i);
10457 mAvailProcessChanges.add(item);
10458 }
10459 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010460 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 // If the caller is restarting this app, then leave it in its
10463 // current lists and let the caller take care of it.
10464 if (restarting) {
10465 return;
10466 }
10467
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010468 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010469 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010470 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010471 mProcessNames.remove(app.processName, app.uid);
10472 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010473 if (mHeavyWeightProcess == app) {
10474 mHeavyWeightProcess = null;
10475 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 } else if (!app.removed) {
10478 // This app is persistent, so we need to keep its record around.
10479 // If it is not already on the pending app list, add it there
10480 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010481 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10482 mPersistentStartingProcesses.add(app);
10483 restart = true;
10484 }
10485 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010486 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10487 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488 mProcessesOnHold.remove(app);
10489
The Android Open Source Project4df24232009-03-05 14:34:35 -080010490 if (app == mHomeProcess) {
10491 mHomeProcess = null;
10492 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010493 if (app == mPreviousProcess) {
10494 mPreviousProcess = null;
10495 }
10496
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010497 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 // We have components that still need to be running in the
10499 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010500 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010501 startProcessLocked(app, "restart", app.processName);
10502 } else if (app.pid > 0 && app.pid != MY_PID) {
10503 // Goodbye!
10504 synchronized (mPidsSelfLocked) {
10505 mPidsSelfLocked.remove(app.pid);
10506 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10507 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010508 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 }
10510 }
10511
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010512 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10513 // Look through the content providers we are waiting to have launched,
10514 // and if any run in this process then either schedule a restart of
10515 // the process or kill the client waiting for it if this process has
10516 // gone bad.
10517 int NL = mLaunchingProviders.size();
10518 boolean restart = false;
10519 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010520 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010521 if (cpr.launchingApp == app) {
10522 if (!alwaysBad && !app.bad) {
10523 restart = true;
10524 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010525 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010526 NL = mLaunchingProviders.size();
10527 }
10528 }
10529 }
10530 return restart;
10531 }
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 // =========================================================
10534 // SERVICES
10535 // =========================================================
10536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10538 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010539 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010541 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 }
10543 }
10544
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010545 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010546 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010547 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010548 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010549 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010550 }
10551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 public ComponentName startService(IApplicationThread caller, Intent service,
10553 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010554 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010555 // Refuse possible leaked file descriptors
10556 if (service != null && service.hasFileDescriptors() == true) {
10557 throw new IllegalArgumentException("File descriptors passed in Intent");
10558 }
10559
Amith Yamasani742a6712011-05-04 14:49:28 -070010560 if (DEBUG_SERVICE)
10561 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 synchronized(this) {
10563 final int callingPid = Binder.getCallingPid();
10564 final int callingUid = Binder.getCallingUid();
10565 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010566 ComponentName res = mServices.startServiceLocked(caller, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 resolvedType, callingPid, callingUid);
10568 Binder.restoreCallingIdentity(origId);
10569 return res;
10570 }
10571 }
10572
10573 ComponentName startServiceInPackage(int uid,
10574 Intent service, String resolvedType) {
10575 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010576 if (DEBUG_SERVICE)
10577 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010579 ComponentName res = mServices.startServiceLocked(null, service,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 resolvedType, -1, uid);
10581 Binder.restoreCallingIdentity(origId);
10582 return res;
10583 }
10584 }
10585
10586 public int stopService(IApplicationThread caller, Intent service,
10587 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010588 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 // Refuse possible leaked file descriptors
10590 if (service != null && service.hasFileDescriptors() == true) {
10591 throw new IllegalArgumentException("File descriptors passed in Intent");
10592 }
10593
10594 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010595 return mServices.stopServiceLocked(caller, service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 }
10598
10599 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010600 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 // Refuse possible leaked file descriptors
10602 if (service != null && service.hasFileDescriptors() == true) {
10603 throw new IllegalArgumentException("File descriptors passed in Intent");
10604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010606 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 }
10609
10610 public boolean stopServiceToken(ComponentName className, IBinder token,
10611 int startId) {
10612 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010613 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010615 }
10616
10617 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010618 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010619 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010620 mServices.setServiceForegroundLocked(className, token, id, notification,
10621 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010622 }
10623 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010624
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010625 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10626 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010627 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010628 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010629 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10630 if (ActivityManager.checkUidPermission(
10631 android.Manifest.permission.INTERACT_ACROSS_USERS,
10632 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10633 ComponentName comp = new ComponentName(aInfo.packageName, className);
10634 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10635 + " requests FLAG_SINGLE_USER, but app does not hold "
10636 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10637 Slog.w(TAG, msg);
10638 throw new SecurityException(msg);
10639 }
10640 result = true;
10641 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010642 } else if (componentProcessName == aInfo.packageName) {
10643 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10644 } else if ("system".equals(componentProcessName)) {
10645 result = true;
10646 }
10647 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010648 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10649 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010650 }
10651 return result;
10652 }
10653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010654 public int bindService(IApplicationThread caller, IBinder token,
10655 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010656 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010657 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 // Refuse possible leaked file descriptors
10659 if (service != null && service.hasFileDescriptors() == true) {
10660 throw new IllegalArgumentException("File descriptors passed in Intent");
10661 }
10662
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010663 checkValidCaller(Binder.getCallingUid(), userId);
10664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010666 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10667 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010668 }
10669 }
10670
10671 public boolean unbindService(IServiceConnection connection) {
10672 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010673 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 }
10676
10677 public void publishService(IBinder token, Intent intent, IBinder service) {
10678 // Refuse possible leaked file descriptors
10679 if (intent != null && intent.hasFileDescriptors() == true) {
10680 throw new IllegalArgumentException("File descriptors passed in Intent");
10681 }
10682
10683 synchronized(this) {
10684 if (!(token instanceof ServiceRecord)) {
10685 throw new IllegalArgumentException("Invalid service token");
10686 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010687 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
10689 }
10690
10691 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10692 // Refuse possible leaked file descriptors
10693 if (intent != null && intent.hasFileDescriptors() == true) {
10694 throw new IllegalArgumentException("File descriptors passed in Intent");
10695 }
10696
10697 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010698 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 }
10700 }
10701
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010702 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010703 synchronized(this) {
10704 if (!(token instanceof ServiceRecord)) {
10705 throw new IllegalArgumentException("Invalid service token");
10706 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010707 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 }
10710
10711 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010712 // BACKUP AND RESTORE
10713 // =========================================================
10714
10715 // Cause the target app to be launched if necessary and its backup agent
10716 // instantiated. The backup agent will invoke backupAgentCreated() on the
10717 // activity manager to announce its creation.
10718 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010719 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010720 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10721
10722 synchronized(this) {
10723 // !!! TODO: currently no check here that we're already bound
10724 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10725 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10726 synchronized (stats) {
10727 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10728 }
10729
Dianne Hackborne7f97212011-02-24 14:40:20 -080010730 // Backup agent is now in use, its package can't be stopped.
10731 try {
10732 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010733 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010734 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010735 } catch (IllegalArgumentException e) {
10736 Slog.w(TAG, "Failed trying to unstop package "
10737 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010738 }
10739
Christopher Tate181fafa2009-05-14 11:12:14 -070010740 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010741 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10742 ? new ComponentName(app.packageName, app.backupAgentName)
10743 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010744 // startProcessLocked() returns existing proc's record if it's already running
10745 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010746 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010747 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010748 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010749 return false;
10750 }
10751
10752 r.app = proc;
10753 mBackupTarget = r;
10754 mBackupAppName = app.packageName;
10755
Christopher Tate6fa95972009-06-05 18:43:55 -070010756 // Try not to kill the process during backup
10757 updateOomAdjLocked(proc);
10758
Christopher Tate181fafa2009-05-14 11:12:14 -070010759 // If the process is already attached, schedule the creation of the backup agent now.
10760 // If it is not yet live, this will be done when it attaches to the framework.
10761 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010762 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010763 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010764 proc.thread.scheduleCreateBackupAgent(app,
10765 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010766 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010767 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010768 }
10769 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010770 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010771 }
10772 // Invariants: at this point, the target app process exists and the application
10773 // is either already running or in the process of coming up. mBackupTarget and
10774 // mBackupAppName describe the app, so that when it binds back to the AM we
10775 // know that it's scheduled for a backup-agent operation.
10776 }
10777
10778 return true;
10779 }
10780
10781 // A backup agent has just come up
10782 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010783 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010784 + " = " + agent);
10785
10786 synchronized(this) {
10787 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010788 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010789 return;
10790 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010791 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010792
Dianne Hackborn06740692010-09-22 22:46:21 -070010793 long oldIdent = Binder.clearCallingIdentity();
10794 try {
10795 IBackupManager bm = IBackupManager.Stub.asInterface(
10796 ServiceManager.getService(Context.BACKUP_SERVICE));
10797 bm.agentConnected(agentPackageName, agent);
10798 } catch (RemoteException e) {
10799 // can't happen; the backup manager service is local
10800 } catch (Exception e) {
10801 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10802 e.printStackTrace();
10803 } finally {
10804 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010805 }
10806 }
10807
10808 // done with this agent
10809 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010810 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010811 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010812 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010813 return;
10814 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010815
10816 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010817 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010818 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010819 return;
10820 }
10821
Christopher Tate181fafa2009-05-14 11:12:14 -070010822 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010823 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010824 return;
10825 }
10826
Christopher Tate6fa95972009-06-05 18:43:55 -070010827 ProcessRecord proc = mBackupTarget.app;
10828 mBackupTarget = null;
10829 mBackupAppName = null;
10830
10831 // Not backing this app up any more; reset its OOM adjustment
10832 updateOomAdjLocked(proc);
10833
Christopher Tatec7b31e32009-06-10 15:49:30 -070010834 // If the app crashed during backup, 'thread' will be null here
10835 if (proc.thread != null) {
10836 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010837 proc.thread.scheduleDestroyBackupAgent(appInfo,
10838 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010839 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010840 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010841 e.printStackTrace();
10842 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010843 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010844 }
10845 }
10846 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 // BROADCASTS
10848 // =========================================================
10849
Josh Bartel7f208742010-02-25 11:01:44 -060010850 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 List cur) {
10852 final ContentResolver resolver = mContext.getContentResolver();
10853 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
10854 if (list == null) {
10855 return cur;
10856 }
10857 int N = list.size();
10858 for (int i=0; i<N; i++) {
10859 Intent intent = list.get(i);
10860 if (filter.match(resolver, intent, true, TAG) >= 0) {
10861 if (cur == null) {
10862 cur = new ArrayList<Intent>();
10863 }
10864 cur.add(intent);
10865 }
10866 }
10867 return cur;
10868 }
10869
Christopher Tatef46723b2012-01-26 14:19:24 -080010870 boolean isPendingBroadcastProcessLocked(int pid) {
10871 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
10872 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
10873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010874
Christopher Tatef46723b2012-01-26 14:19:24 -080010875 void skipPendingBroadcastLocked(int pid) {
10876 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
10877 for (BroadcastQueue queue : mBroadcastQueues) {
10878 queue.skipPendingBroadcastLocked(pid);
10879 }
10880 }
10881
10882 // The app just attached; send any pending broadcasts that it should receive
10883 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
10884 boolean didSomething = false;
10885 for (BroadcastQueue queue : mBroadcastQueues) {
10886 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010887 }
Christopher Tatef46723b2012-01-26 14:19:24 -080010888 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010889 }
10890
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010891 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010892 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010893 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010894 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 synchronized(this) {
10896 ProcessRecord callerApp = null;
10897 if (caller != null) {
10898 callerApp = getRecordForAppLocked(caller);
10899 if (callerApp == null) {
10900 throw new SecurityException(
10901 "Unable to find app for caller " + caller
10902 + " (pid=" + Binder.getCallingPid()
10903 + ") when registering receiver " + receiver);
10904 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010905 if (callerApp.info.uid != Process.SYSTEM_UID &&
10906 !callerApp.pkgList.contains(callerPackage)) {
10907 throw new SecurityException("Given caller package " + callerPackage
10908 + " is not running in process " + callerApp);
10909 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010910 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070010911 } else {
10912 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010913 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010914 }
10915
10916 List allSticky = null;
10917
10918 // Look for any matching sticky broadcasts...
10919 Iterator actions = filter.actionsIterator();
10920 if (actions != null) {
10921 while (actions.hasNext()) {
10922 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060010923 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 }
10925 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060010926 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 }
10928
10929 // The first sticky in the list is returned directly back to
10930 // the client.
10931 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
10932
Joe Onorato8a9b2202010-02-26 18:56:32 -080010933 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 + ": " + sticky);
10935
10936 if (receiver == null) {
10937 return sticky;
10938 }
10939
10940 ReceiverList rl
10941 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
10942 if (rl == null) {
10943 rl = new ReceiverList(this, callerApp,
10944 Binder.getCallingPid(),
10945 Binder.getCallingUid(), receiver);
10946 if (rl.app != null) {
10947 rl.app.receivers.add(rl);
10948 } else {
10949 try {
10950 receiver.asBinder().linkToDeath(rl, 0);
10951 } catch (RemoteException e) {
10952 return sticky;
10953 }
10954 rl.linkedToDeath = true;
10955 }
10956 mRegisteredReceivers.put(receiver.asBinder(), rl);
10957 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010958 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
10959 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010960 rl.add(bf);
10961 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010962 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 }
10964 mReceiverResolver.addFilter(bf);
10965
10966 // Enqueue broadcasts for all existing stickies that match
10967 // this filter.
10968 if (allSticky != null) {
10969 ArrayList receivers = new ArrayList();
10970 receivers.add(bf);
10971
10972 int N = allSticky.size();
10973 for (int i=0; i<N; i++) {
10974 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080010975 BroadcastQueue queue = broadcastQueueForIntent(intent);
10976 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070010978 false, true, true, false);
Christopher Tatef46723b2012-01-26 14:19:24 -080010979 queue.enqueueParallelBroadcastLocked(r);
10980 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010981 }
10982 }
10983
10984 return sticky;
10985 }
10986 }
10987
10988 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010989 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010990
Christopher Tatef46723b2012-01-26 14:19:24 -080010991 final long origId = Binder.clearCallingIdentity();
10992 try {
10993 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010994
Christopher Tatef46723b2012-01-26 14:19:24 -080010995 synchronized(this) {
10996 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080010998 if (rl != null) {
10999 if (rl.curBroadcast != null) {
11000 BroadcastRecord r = rl.curBroadcast;
11001 final boolean doNext = finishReceiverLocked(
11002 receiver.asBinder(), r.resultCode, r.resultData,
11003 r.resultExtras, r.resultAbort, true);
11004 if (doNext) {
11005 doTrim = true;
11006 r.queue.processNextBroadcast(false);
11007 }
11008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009
Christopher Tatef46723b2012-01-26 14:19:24 -080011010 if (rl.app != null) {
11011 rl.app.receivers.remove(rl);
11012 }
11013 removeReceiverLocked(rl);
11014 if (rl.linkedToDeath) {
11015 rl.linkedToDeath = false;
11016 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011018 }
11019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011020
Christopher Tatef46723b2012-01-26 14:19:24 -080011021 // If we actually concluded any broadcasts, we might now be able
11022 // to trim the recipients' apps from our working set
11023 if (doTrim) {
11024 trimApplications();
11025 return;
11026 }
11027
11028 } finally {
11029 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011031 }
11032
11033 void removeReceiverLocked(ReceiverList rl) {
11034 mRegisteredReceivers.remove(rl.receiver.asBinder());
11035 int N = rl.size();
11036 for (int i=0; i<N; i++) {
11037 mReceiverResolver.removeFilter(rl.get(i));
11038 }
11039 }
11040
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011041 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
11042 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11043 ProcessRecord r = mLruProcesses.get(i);
11044 if (r.thread != null) {
11045 try {
11046 r.thread.dispatchPackageBroadcast(cmd, packages);
11047 } catch (RemoteException ex) {
11048 }
11049 }
11050 }
11051 }
11052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011053 private final int broadcastIntentLocked(ProcessRecord callerApp,
11054 String callerPackage, Intent intent, String resolvedType,
11055 IIntentReceiver resultTo, int resultCode, String resultData,
11056 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011057 boolean ordered, boolean sticky, int callingPid, int callingUid,
11058 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 intent = new Intent(intent);
11060
Dianne Hackborne7f97212011-02-24 14:40:20 -080011061 // By default broadcasts do not go to stopped apps.
11062 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11063
Joe Onorato8a9b2202010-02-26 18:56:32 -080011064 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011065 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011066 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011067 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011068 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011070
11071 boolean onlySendToCaller = false;
11072
11073 // If the caller is trying to send this broadcast to a different
11074 // user, verify that is allowed.
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011075 if (UserHandle.getUserId(callingUid) != userId) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011076 if (checkComponentPermission(
11077 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11078 callingPid, callingUid, -1, true)
11079 != PackageManager.PERMISSION_GRANTED) {
11080 if (checkComponentPermission(
11081 android.Manifest.permission.INTERACT_ACROSS_USERS,
11082 callingPid, callingUid, -1, true)
11083 == PackageManager.PERMISSION_GRANTED) {
11084 onlySendToCaller = true;
11085 } else {
11086 String msg = "Permission Denial: " + intent.getAction()
11087 + " broadcast from " + callerPackage
11088 + " asks to send as user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011089 + " but is calling from user " + UserHandle.getUserId(callingUid)
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011090 + "; this requires "
11091 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11092 Slog.w(TAG, msg);
11093 throw new SecurityException(msg);
11094 }
11095 }
11096 }
11097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011098 // Handle special intents: if this broadcast is from the package
11099 // manager about a package being removed, we need to remove all of
11100 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011101 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011103 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11104 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011105 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 || uidRemoved) {
11107 if (checkComponentPermission(
11108 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011109 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 == PackageManager.PERMISSION_GRANTED) {
11111 if (uidRemoved) {
11112 final Bundle intentExtras = intent.getExtras();
11113 final int uid = intentExtras != null
11114 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11115 if (uid >= 0) {
11116 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11117 synchronized (bs) {
11118 bs.removeUidStatsLocked(uid);
11119 }
11120 }
11121 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011122 // If resources are unvailble just force stop all
11123 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011124 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011125 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11126 if (list != null && (list.length > 0)) {
11127 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011128 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011129 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011130 sendPackageBroadcastLocked(
11131 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011132 }
11133 } else {
11134 Uri data = intent.getData();
11135 String ssp;
11136 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11137 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11138 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011139 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11140 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011141 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011142 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011143 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
11144 new String[] {ssp});
11145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 }
11147 }
11148 }
11149 } else {
11150 String msg = "Permission Denial: " + intent.getAction()
11151 + " broadcast from " + callerPackage + " (pid=" + callingPid
11152 + ", uid=" + callingUid + ")"
11153 + " requires "
11154 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011155 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011156 throw new SecurityException(msg);
11157 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011158
11159 // Special case for adding a package: by default turn on compatibility
11160 // mode.
11161 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011162 Uri data = intent.getData();
11163 String ssp;
11164 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11165 mCompatModePackages.handlePackageAddedLocked(ssp,
11166 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011168 }
11169
11170 /*
11171 * If this is the time zone changed action, queue up a message that will reset the timezone
11172 * of all currently running processes. This message will get queued up before the broadcast
11173 * happens.
11174 */
11175 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11176 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11177 }
11178
Robert Greenwalt03595d02010-11-02 14:08:23 -070011179 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11180 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11181 }
11182
Robert Greenwalt434203a2010-10-11 16:00:27 -070011183 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11184 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11185 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11186 }
11187
Dianne Hackborn854060af2009-07-09 18:14:31 -070011188 /*
11189 * Prevent non-system code (defined here to be non-persistent
11190 * processes) from sending protected broadcasts.
11191 */
11192 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070011193 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11194 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070011195 // Always okay.
11196 } else if (callerApp == null || !callerApp.persistent) {
11197 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011198 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070011199 intent.getAction())) {
11200 String msg = "Permission Denial: not allowed to send broadcast "
11201 + intent.getAction() + " from pid="
11202 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011203 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070011204 throw new SecurityException(msg);
11205 }
11206 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011207 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011208 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070011209 }
11210 }
11211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011212 // Add to the sticky list if requested.
11213 if (sticky) {
11214 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11215 callingPid, callingUid)
11216 != PackageManager.PERMISSION_GRANTED) {
11217 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11218 + callingPid + ", uid=" + callingUid
11219 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011220 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011221 throw new SecurityException(msg);
11222 }
11223 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011224 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011226 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011227 }
11228 if (intent.getComponent() != null) {
11229 throw new SecurityException(
11230 "Sticky broadcasts can't target a specific component");
11231 }
11232 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11233 if (list == null) {
11234 list = new ArrayList<Intent>();
11235 mStickyBroadcasts.put(intent.getAction(), list);
11236 }
11237 int N = list.size();
11238 int i;
11239 for (i=0; i<N; i++) {
11240 if (intent.filterEquals(list.get(i))) {
11241 // This sticky already exists, replace it.
11242 list.set(i, new Intent(intent));
11243 break;
11244 }
11245 }
11246 if (i >= N) {
11247 list.add(new Intent(intent));
11248 }
11249 }
11250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 // Figure out who all will receive this broadcast.
11252 List receivers = null;
11253 List<BroadcastFilter> registeredReceivers = null;
11254 try {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070011255 // Need to resolve the intent to interested receivers...
11256 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11257 == 0) {
11258 receivers = AppGlobals.getPackageManager().queryIntentReceivers(
11259 intent, resolvedType, STOCK_PM_FLAGS, userId);
11260 }
11261 if (intent.getComponent() == null) {
11262 registeredReceivers = mReceiverResolver.queryIntent(intent,
11263 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 }
11265 } catch (RemoteException ex) {
11266 // pm is in same process, this will never happen.
11267 }
11268
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011269 final boolean replacePending =
11270 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11271
Joe Onorato8a9b2202010-02-26 18:56:32 -080011272 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011273 + " replacePending=" + replacePending);
11274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11276 if (!ordered && NR > 0) {
11277 // If we are not serializing this broadcast, then send the
11278 // registered receivers separately so they don't wait for the
11279 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011280 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11281 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 callerPackage, callingPid, callingUid, requiredPermission,
11283 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011284 ordered, sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011285 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011286 TAG, "Enqueueing parallel broadcast " + r);
11287 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011288 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011289 queue.enqueueParallelBroadcastLocked(r);
11290 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 registeredReceivers = null;
11293 NR = 0;
11294 }
11295
11296 // Merge into one list.
11297 int ir = 0;
11298 if (receivers != null) {
11299 // A special case for PACKAGE_ADDED: do not allow the package
11300 // being added to see this broadcast. This prevents them from
11301 // using this as a back door to get run as soon as they are
11302 // installed. Maybe in the future we want to have a special install
11303 // broadcast or such for apps, but we'd like to deliberately make
11304 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011305 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011306 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11307 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11308 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011309 Uri data = intent.getData();
11310 if (data != null) {
11311 String pkgName = data.getSchemeSpecificPart();
11312 if (pkgName != null) {
11313 skipPackages = new String[] { pkgName };
11314 }
11315 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011316 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011317 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011318 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011319 if (skipPackages != null && (skipPackages.length > 0)) {
11320 for (String skipPackage : skipPackages) {
11321 if (skipPackage != null) {
11322 int NT = receivers.size();
11323 for (int it=0; it<NT; it++) {
11324 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11325 if (curt.activityInfo.packageName.equals(skipPackage)) {
11326 receivers.remove(it);
11327 it--;
11328 NT--;
11329 }
11330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011331 }
11332 }
11333 }
11334
11335 int NT = receivers != null ? receivers.size() : 0;
11336 int it = 0;
11337 ResolveInfo curt = null;
11338 BroadcastFilter curr = null;
11339 while (it < NT && ir < NR) {
11340 if (curt == null) {
11341 curt = (ResolveInfo)receivers.get(it);
11342 }
11343 if (curr == null) {
11344 curr = registeredReceivers.get(ir);
11345 }
11346 if (curr.getPriority() >= curt.priority) {
11347 // Insert this broadcast record into the final list.
11348 receivers.add(it, curr);
11349 ir++;
11350 curr = null;
11351 it++;
11352 NT++;
11353 } else {
11354 // Skip to the next ResolveInfo in the final list.
11355 it++;
11356 curt = null;
11357 }
11358 }
11359 }
11360 while (ir < NR) {
11361 if (receivers == null) {
11362 receivers = new ArrayList();
11363 }
11364 receivers.add(registeredReceivers.get(ir));
11365 ir++;
11366 }
11367
11368 if ((receivers != null && receivers.size() > 0)
11369 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011370 BroadcastQueue queue = broadcastQueueForIntent(intent);
11371 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011372 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011373 receivers, resultTo, resultCode, resultData, map, ordered,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011374 sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011375 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011377 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011378 if (DEBUG_BROADCAST) {
11379 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011380 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011382 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011383 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011384 queue.enqueueOrderedBroadcastLocked(r);
11385 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 }
11388
Dianne Hackborna4972e92012-03-14 10:38:05 -070011389 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 }
11391
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011392 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 // Refuse possible leaked file descriptors
11394 if (intent != null && intent.hasFileDescriptors() == true) {
11395 throw new IllegalArgumentException("File descriptors passed in Intent");
11396 }
11397
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011398 int flags = intent.getFlags();
11399
11400 if (!mProcessesReady) {
11401 // if the caller really truly claims to know what they're doing, go
11402 // ahead and allow the broadcast without launching any receivers
11403 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11404 intent = new Intent(intent);
11405 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11406 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11407 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11408 + " before boot completion");
11409 throw new IllegalStateException("Cannot broadcast before boot completed");
11410 }
11411 }
11412
11413 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11414 throw new IllegalArgumentException(
11415 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11416 }
11417
11418 return intent;
11419 }
11420
11421 public final int broadcastIntent(IApplicationThread caller,
11422 Intent intent, String resolvedType, IIntentReceiver resultTo,
11423 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011424 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011425 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011427 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011429 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11430 final int callingPid = Binder.getCallingPid();
11431 final int callingUid = Binder.getCallingUid();
11432 final long origId = Binder.clearCallingIdentity();
11433 int res = broadcastIntentLocked(callerApp,
11434 callerApp != null ? callerApp.info.packageName : null,
11435 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011436 resultCode, resultData, map, requiredPermission, serialized, sticky,
11437 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 Binder.restoreCallingIdentity(origId);
11439 return res;
11440 }
11441 }
11442
11443 int broadcastIntentInPackage(String packageName, int uid,
11444 Intent intent, String resolvedType, IIntentReceiver resultTo,
11445 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011446 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011447 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011448 intent = verifyBroadcastLocked(intent);
11449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 final long origId = Binder.clearCallingIdentity();
11451 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11452 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011453 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011454 Binder.restoreCallingIdentity(origId);
11455 return res;
11456 }
11457 }
11458
Amith Yamasani742a6712011-05-04 14:49:28 -070011459 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
11460 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011461 // Refuse possible leaked file descriptors
11462 if (intent != null && intent.hasFileDescriptors() == true) {
11463 throw new IllegalArgumentException("File descriptors passed in Intent");
11464 }
11465
11466 synchronized(this) {
11467 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11468 != PackageManager.PERMISSION_GRANTED) {
11469 String msg = "Permission Denial: unbroadcastIntent() from pid="
11470 + Binder.getCallingPid()
11471 + ", uid=" + Binder.getCallingUid()
11472 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011473 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011474 throw new SecurityException(msg);
11475 }
11476 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
11477 if (list != null) {
11478 int N = list.size();
11479 int i;
11480 for (i=0; i<N; i++) {
11481 if (intent.filterEquals(list.get(i))) {
11482 list.remove(i);
11483 break;
11484 }
11485 }
11486 }
11487 }
11488 }
11489
11490 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11491 String resultData, Bundle resultExtras, boolean resultAbort,
11492 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011493 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11494 if (r == null) {
11495 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011496 return false;
11497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498
Christopher Tatef46723b2012-01-26 14:19:24 -080011499 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11500 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011501 }
11502
11503 public void finishReceiver(IBinder who, int resultCode, String resultData,
11504 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011505 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011506
11507 // Refuse possible leaked file descriptors
11508 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11509 throw new IllegalArgumentException("File descriptors passed in Bundle");
11510 }
11511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011512 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011513 try {
11514 boolean doNext = false;
11515 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516
Christopher Tatef46723b2012-01-26 14:19:24 -080011517 synchronized(this) {
11518 r = broadcastRecordForReceiverLocked(who);
11519 if (r != null) {
11520 doNext = r.queue.finishReceiverLocked(r, resultCode,
11521 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011523 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011524
Christopher Tatef46723b2012-01-26 14:19:24 -080011525 if (doNext) {
11526 r.queue.processNextBroadcast(false);
11527 }
11528 trimApplications();
11529 } finally {
11530 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534 // =========================================================
11535 // INSTRUMENTATION
11536 // =========================================================
11537
11538 public boolean startInstrumentation(ComponentName className,
11539 String profileFile, int flags, Bundle arguments,
11540 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011541 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 // Refuse possible leaked file descriptors
11543 if (arguments != null && arguments.hasFileDescriptors()) {
11544 throw new IllegalArgumentException("File descriptors passed in Bundle");
11545 }
11546
11547 synchronized(this) {
11548 InstrumentationInfo ii = null;
11549 ApplicationInfo ai = null;
11550 try {
11551 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011552 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011554 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 } catch (PackageManager.NameNotFoundException e) {
11556 }
11557 if (ii == null) {
11558 reportStartInstrumentationFailure(watcher, className,
11559 "Unable to find instrumentation info for: " + className);
11560 return false;
11561 }
11562 if (ai == null) {
11563 reportStartInstrumentationFailure(watcher, className,
11564 "Unable to find instrumentation target package: " + ii.targetPackage);
11565 return false;
11566 }
11567
11568 int match = mContext.getPackageManager().checkSignatures(
11569 ii.targetPackage, ii.packageName);
11570 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11571 String msg = "Permission Denial: starting instrumentation "
11572 + className + " from pid="
11573 + Binder.getCallingPid()
11574 + ", uid=" + Binder.getCallingPid()
11575 + " not allowed because package " + ii.packageName
11576 + " does not have a signature matching the target "
11577 + ii.targetPackage;
11578 reportStartInstrumentationFailure(watcher, className, msg);
11579 throw new SecurityException(msg);
11580 }
11581
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011582 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011584 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011585 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011586 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011588 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011589 app.instrumentationProfileFile = profileFile;
11590 app.instrumentationArguments = arguments;
11591 app.instrumentationWatcher = watcher;
11592 app.instrumentationResultClass = className;
11593 Binder.restoreCallingIdentity(origId);
11594 }
11595
11596 return true;
11597 }
11598
11599 /**
11600 * Report errors that occur while attempting to start Instrumentation. Always writes the
11601 * error to the logs, but if somebody is watching, send the report there too. This enables
11602 * the "am" command to report errors with more information.
11603 *
11604 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11605 * @param cn The component name of the instrumentation.
11606 * @param report The error report.
11607 */
11608 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11609 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011610 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011611 try {
11612 if (watcher != null) {
11613 Bundle results = new Bundle();
11614 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11615 results.putString("Error", report);
11616 watcher.instrumentationStatus(cn, -1, results);
11617 }
11618 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011619 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 }
11621 }
11622
11623 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11624 if (app.instrumentationWatcher != null) {
11625 try {
11626 // NOTE: IInstrumentationWatcher *must* be oneway here
11627 app.instrumentationWatcher.instrumentationFinished(
11628 app.instrumentationClass,
11629 resultCode,
11630 results);
11631 } catch (RemoteException e) {
11632 }
11633 }
11634 app.instrumentationWatcher = null;
11635 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011636 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011637 app.instrumentationProfileFile = null;
11638 app.instrumentationArguments = null;
11639
Amith Yamasani483f3b02012-03-13 16:08:00 -070011640 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 }
11642
11643 public void finishInstrumentation(IApplicationThread target,
11644 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011645 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 // Refuse possible leaked file descriptors
11647 if (results != null && results.hasFileDescriptors()) {
11648 throw new IllegalArgumentException("File descriptors passed in Intent");
11649 }
11650
11651 synchronized(this) {
11652 ProcessRecord app = getRecordForAppLocked(target);
11653 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011654 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 return;
11656 }
11657 final long origId = Binder.clearCallingIdentity();
11658 finishInstrumentationLocked(app, resultCode, results);
11659 Binder.restoreCallingIdentity(origId);
11660 }
11661 }
11662
11663 // =========================================================
11664 // CONFIGURATION
11665 // =========================================================
11666
11667 public ConfigurationInfo getDeviceConfigurationInfo() {
11668 ConfigurationInfo config = new ConfigurationInfo();
11669 synchronized (this) {
11670 config.reqTouchScreen = mConfiguration.touchscreen;
11671 config.reqKeyboardType = mConfiguration.keyboard;
11672 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011673 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11674 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11676 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011677 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11678 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011679 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11680 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011681 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 }
11683 return config;
11684 }
11685
11686 public Configuration getConfiguration() {
11687 Configuration ci;
11688 synchronized(this) {
11689 ci = new Configuration(mConfiguration);
11690 }
11691 return ci;
11692 }
11693
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011694 public void updatePersistentConfiguration(Configuration values) {
11695 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11696 "updateConfiguration()");
11697 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11698 "updateConfiguration()");
11699 if (values == null) {
11700 throw new NullPointerException("Configuration must not be null");
11701 }
11702
11703 synchronized(this) {
11704 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011705 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011706 Binder.restoreCallingIdentity(origId);
11707 }
11708 }
11709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 public void updateConfiguration(Configuration values) {
11711 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11712 "updateConfiguration()");
11713
11714 synchronized(this) {
11715 if (values == null && mWindowManager != null) {
11716 // sentinel: fetch the current configuration from the window manager
11717 values = mWindowManager.computeNewConfiguration();
11718 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011719
11720 if (mWindowManager != null) {
11721 mProcessList.applyDisplaySize(mWindowManager);
11722 }
11723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011724 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011725 if (values != null) {
11726 Settings.System.clearConfiguration(values);
11727 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011728 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729 Binder.restoreCallingIdentity(origId);
11730 }
11731 }
11732
11733 /**
11734 * Do either or both things: (1) change the current configuration, and (2)
11735 * make sure the given activity is running with the (now) current
11736 * configuration. Returns true if the activity has been left running, or
11737 * false if <var>starting</var> is being destroyed to match the new
11738 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011739 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011741 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011742 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011743 // do nothing if we are headless
11744 if (mHeadless) return true;
11745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 int changes = 0;
11747
11748 boolean kept = true;
11749
11750 if (values != null) {
11751 Configuration newConfig = new Configuration(mConfiguration);
11752 changes = newConfig.updateFrom(values);
11753 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011754 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011755 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 }
11757
Doug Zongker2bec3d42009-12-04 12:52:44 -080011758 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759
Dianne Hackborn813075a62011-11-14 17:45:19 -080011760 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761 saveLocaleLocked(values.locale,
11762 !values.locale.equals(mConfiguration.locale),
11763 values.userSetLocale);
11764 }
11765
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011766 mConfigurationSeq++;
11767 if (mConfigurationSeq <= 0) {
11768 mConfigurationSeq = 1;
11769 }
11770 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011771 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011772 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011773
11774 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070011775
11776 // TODO: If our config changes, should we auto dismiss any currently
11777 // showing dialogs?
11778 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011779
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011780 AttributeCache ac = AttributeCache.instance();
11781 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080011782 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080011783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011785 // Make sure all resources in our process are updated
11786 // right now, so that anyone who is going to retrieve
11787 // resource values after we return will be sure to get
11788 // the new ones. This is especially important during
11789 // boot, where the first config change needs to guarantee
11790 // all resources have that config before following boot
11791 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080011792 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070011793
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011794 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011795 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011796 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080011797 mHandler.sendMessage(msg);
11798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011800 for (int i=mLruProcesses.size()-1; i>=0; i--) {
11801 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011802 try {
11803 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011804 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011805 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080011806 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 }
11808 } catch (Exception e) {
11809 }
11810 }
11811 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
11813 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011815 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011816 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
11817 broadcastIntentLocked(null, null,
11818 new Intent(Intent.ACTION_LOCALE_CHANGED),
11819 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070011820 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080011821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 }
11823 }
11824
11825 if (changes != 0 && starting == null) {
11826 // If the configuration changed, and the caller is not already
11827 // in the process of starting an activity, then find the top
11828 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011829 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 }
11831
11832 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011833 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080011834 // And we need to make sure at this point that all other activities
11835 // are made visible with the correct configuration.
11836 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 }
11838
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011839 if (values != null && mWindowManager != null) {
11840 mWindowManager.setNewConfiguration(mConfiguration);
11841 }
11842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 return kept;
11844 }
Joe Onorato54a4a412011-11-02 20:50:08 -070011845
11846 /**
11847 * Decide based on the configuration whether we should shouw the ANR,
11848 * crash, etc dialogs. The idea is that if there is no affordnace to
11849 * press the on-screen buttons, we shouldn't show the dialog.
11850 *
11851 * A thought: SystemUI might also want to get told about this, the Power
11852 * dialog / global actions also might want different behaviors.
11853 */
11854 private static final boolean shouldShowDialogs(Configuration config) {
11855 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
11856 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
11857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011858
11859 /**
11860 * Save the locale. You must be inside a synchronized (this) block.
11861 */
11862 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
11863 if(isDiff) {
11864 SystemProperties.set("user.language", l.getLanguage());
11865 SystemProperties.set("user.region", l.getCountry());
11866 }
11867
11868 if(isPersist) {
11869 SystemProperties.set("persist.sys.language", l.getLanguage());
11870 SystemProperties.set("persist.sys.country", l.getCountry());
11871 SystemProperties.set("persist.sys.localevar", l.getVariant());
11872 }
11873 }
11874
Adam Powelldd8fab22012-03-22 17:47:27 -070011875 @Override
11876 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
11877 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011878 return srec != null && srec.task.affinity != null &&
11879 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070011880 }
11881
11882 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
11883 Intent resultData) {
11884 ComponentName dest = destIntent.getComponent();
11885
11886 synchronized (this) {
11887 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070011888 if (srec == null) {
11889 return false;
11890 }
Adam Powelldd8fab22012-03-22 17:47:27 -070011891 ArrayList<ActivityRecord> history = srec.stack.mHistory;
11892 final int start = history.indexOf(srec);
11893 if (start < 0) {
11894 // Current activity is not in history stack; do nothing.
11895 return false;
11896 }
11897 int finishTo = start - 1;
11898 ActivityRecord parent = null;
11899 boolean foundParentInTask = false;
11900 if (dest != null) {
11901 TaskRecord tr = srec.task;
11902 for (int i = start - 1; i >= 0; i--) {
11903 ActivityRecord r = history.get(i);
11904 if (tr != r.task) {
11905 // Couldn't find parent in the same task; stop at the one above this.
11906 // (Root of current task; in-app "home" behavior)
11907 // Always at least finish the current activity.
11908 finishTo = Math.min(start - 1, i + 1);
11909 parent = history.get(finishTo);
11910 break;
11911 } else if (r.info.packageName.equals(dest.getPackageName()) &&
11912 r.info.name.equals(dest.getClassName())) {
11913 finishTo = i;
11914 parent = r;
11915 foundParentInTask = true;
11916 break;
11917 }
11918 }
11919 }
11920
11921 if (mController != null) {
11922 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
11923 if (next != null) {
11924 // ask watcher if this is allowed
11925 boolean resumeOK = true;
11926 try {
11927 resumeOK = mController.activityResuming(next.packageName);
11928 } catch (RemoteException e) {
11929 mController = null;
11930 }
11931
11932 if (!resumeOK) {
11933 return false;
11934 }
11935 }
11936 }
11937 final long origId = Binder.clearCallingIdentity();
11938 for (int i = start; i > finishTo; i--) {
11939 ActivityRecord r = history.get(i);
11940 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
11941 "navigate-up");
11942 // Only return the supplied result for the first activity finished
11943 resultCode = Activity.RESULT_CANCELED;
11944 resultData = null;
11945 }
11946
11947 if (parent != null && foundParentInTask) {
11948 final int parentLaunchMode = parent.info.launchMode;
11949 final int destIntentFlags = destIntent.getFlags();
11950 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
11951 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
11952 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
11953 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070011954 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070011955 } else {
11956 try {
11957 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011958 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070011959 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
11960 null, aInfo, parent.appToken, null,
11961 0, -1, parent.launchedFromUid, 0, null, true, null);
11962 foundParentInTask = res == ActivityManager.START_SUCCESS;
11963 } catch (RemoteException e) {
11964 foundParentInTask = false;
11965 }
11966 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
11967 resultData, "navigate-up");
11968 }
11969 }
11970 Binder.restoreCallingIdentity(origId);
11971 return foundParentInTask;
11972 }
11973 }
11974
Dianne Hackborn5320eb82012-05-18 12:05:04 -070011975 public int getLaunchedFromUid(IBinder activityToken) {
11976 ActivityRecord srec = ActivityRecord.forToken(activityToken);
11977 if (srec == null) {
11978 return -1;
11979 }
11980 return srec.launchedFromUid;
11981 }
11982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011983 // =========================================================
11984 // LIFETIME MANAGEMENT
11985 // =========================================================
11986
Christopher Tatef46723b2012-01-26 14:19:24 -080011987 // Returns which broadcast queue the app is the current [or imminent] receiver
11988 // on, or 'null' if the app is not an active broadcast recipient.
11989 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
11990 BroadcastRecord r = app.curReceiver;
11991 if (r != null) {
11992 return r.queue;
11993 }
11994
11995 // It's not the current receiver, but it might be starting up to become one
11996 synchronized (this) {
11997 for (BroadcastQueue queue : mBroadcastQueues) {
11998 r = queue.mPendingBroadcast;
11999 if (r != null && r.curApp == app) {
12000 // found it; report which queue it's in
12001 return queue;
12002 }
12003 }
12004 }
12005
12006 return null;
12007 }
12008
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012009 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012010 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012012 // This adjustment has already been computed. If we are calling
12013 // from the top, we may have already computed our adjustment with
12014 // an earlier hidden adjustment that isn't really for us... if
12015 // so, use the new hidden adjustment.
12016 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012017 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12018 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012019 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012020 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 }
12022
12023 if (app.thread == null) {
12024 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012025 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012026 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 }
12028
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012029 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12030 app.adjSource = null;
12031 app.adjTarget = null;
12032 app.empty = false;
12033 app.hidden = false;
12034
12035 final int activitiesSize = app.activities.size();
12036
Dianne Hackborn7d608422011-08-07 16:24:18 -070012037 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012038 // The max adjustment doesn't allow this app to be anything
12039 // below foreground, so it is not worth doing work for it.
12040 app.adjType = "fixed";
12041 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012042 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012043 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012044 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012045 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012046 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012047 // System process can do UI, and when they do we want to have
12048 // them trim their memory after the user leaves the UI. To
12049 // facilitate this, here we need to determine whether or not it
12050 // is currently showing UI.
12051 app.systemNoUi = true;
12052 if (app == TOP_APP) {
12053 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012054 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012055 } else if (activitiesSize > 0) {
12056 for (int j = 0; j < activitiesSize; j++) {
12057 final ActivityRecord r = app.activities.get(j);
12058 if (r.visible) {
12059 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012060 }
12061 if (r.app == app) {
12062 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012063 }
12064 }
12065 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012066 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012067 }
12068
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012069 app.keeping = false;
12070 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012071 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012072
The Android Open Source Project4df24232009-03-05 14:34:35 -080012073 // Determine the importance of the process, starting with most
12074 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012076 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012077 boolean foregroundActivities = false;
12078 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012079 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012080 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012082 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012083 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012084 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012085 foregroundActivities = true;
12086 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012087 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012088 } else if (app.instrumentationClass != null) {
12089 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012090 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012091 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012092 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012093 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012094 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012096 // counts as being in the foreground for OOM killer purposes.
12097 // It's placed in a sched group based on the nature of the
12098 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012099 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012100 schedGroup = (queue == mFgBroadcastQueue)
12101 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012102 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103 } else if (app.executingServices.size() > 0) {
12104 // An app that is currently executing a service callback also
12105 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012106 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012107 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012108 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012109 } else {
12110 // Assume process is hidden (has activities); we will correct
12111 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012112 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012113 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012114 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012115 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012116 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012117
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012118 boolean hasStoppingActivities = false;
12119
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012120 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012121 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012122 for (int j = 0; j < activitiesSize; j++) {
12123 final ActivityRecord r = app.activities.get(j);
12124 if (r.visible) {
12125 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012126 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12127 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012128 app.adjType = "visible";
12129 }
12130 schedGroup = Process.THREAD_GROUP_DEFAULT;
12131 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012132 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012133 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012134 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012135 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012136 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12137 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012138 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012139 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012140 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012141 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012142 } else if (r.state == ActivityState.STOPPING) {
12143 // We will apply the actual adjustment later, because
12144 // we want to allow this process to immediately go through
12145 // any memory trimming that is in effect.
12146 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012147 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012148 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012149 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012150 if (r.app == app) {
12151 app.hasActivities = true;
12152 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012153 }
12154 }
12155
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012156 if (adj == hiddenAdj && !app.hasActivities) {
12157 // Whoops, this process is completely empty as far as we know
12158 // at this point.
12159 adj = emptyAdj;
12160 app.empty = true;
12161 app.adjType = "bg-empty";
12162 }
12163
Dianne Hackborn7d608422011-08-07 16:24:18 -070012164 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012165 if (app.foregroundServices) {
12166 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012167 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012168 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012169 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012170 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012171 } else if (app.forcingToForeground != null) {
12172 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012173 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012174 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012175 app.adjType = "force-foreground";
12176 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012177 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012178 }
12179 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012180
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012181 if (app.foregroundServices) {
12182 interesting = true;
12183 }
12184
Dianne Hackborn7d608422011-08-07 16:24:18 -070012185 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012186 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012187 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012188 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012189 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012190 app.adjType = "heavy";
12191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192
Dianne Hackborn7d608422011-08-07 16:24:18 -070012193 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012194 // This process is hosting what we currently consider to be the
12195 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012196 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012197 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012198 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012199 app.adjType = "home";
12200 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012201
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012202 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12203 && app.activities.size() > 0) {
12204 // This was the previous process that showed UI to the user.
12205 // We want to try to keep it around more aggressively, to give
12206 // a good experience around switching between two apps.
12207 adj = ProcessList.PREVIOUS_APP_ADJ;
12208 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12209 app.hidden = false;
12210 app.adjType = "previous";
12211 }
12212
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012213 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12214 + " reason=" + app.adjType);
12215
The Android Open Source Project4df24232009-03-05 14:34:35 -080012216 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012217 // there are applications dependent on our services or providers, but
12218 // this gives us a baseline and makes sure we don't get into an
12219 // infinite recursion.
12220 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012221 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012222
Christopher Tate6fa95972009-06-05 18:43:55 -070012223 if (mBackupTarget != null && app == mBackupTarget.app) {
12224 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012225 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012226 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012227 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012228 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012229 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012230 }
12231 }
12232
Dianne Hackborn7d608422011-08-07 16:24:18 -070012233 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012234 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012235 final long now = SystemClock.uptimeMillis();
12236 // This process is more important if the top activity is
12237 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012238 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012239 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012240 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012241 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012242 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012243 // If this process has shown some UI, let it immediately
12244 // go to the LRU list because it may be pretty heavy with
12245 // UI stuff. We'll tag it with a label just to help
12246 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012247 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012248 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012249 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012250 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012251 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012252 // This service has seen some activity within
12253 // recent memory, so we will keep its process ahead
12254 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012255 if (adj > ProcessList.SERVICE_ADJ) {
12256 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012257 app.adjType = "started-services";
12258 app.hidden = false;
12259 }
12260 }
12261 // If we have let the service slide into the background
12262 // state, still have some text describing what it is doing
12263 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012264 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012265 app.adjType = "started-bg-services";
12266 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012267 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012268 // Don't kill this process because it is doing work; it
12269 // has said it is doing work.
12270 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012271 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012272 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012273 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012274 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012275 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012276 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012277 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012278 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012279 // XXX should compute this based on the max of
12280 // all connected clients.
12281 ConnectionRecord cr = clist.get(i);
12282 if (cr.binding.client == app) {
12283 // Binding to ourself is not interesting.
12284 continue;
12285 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012286 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012287 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012288 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012289 int myHiddenAdj = hiddenAdj;
12290 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012291 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012292 myHiddenAdj = client.hiddenAdj;
12293 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012294 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012295 }
12296 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012297 int myEmptyAdj = emptyAdj;
12298 if (myEmptyAdj > client.emptyAdj) {
12299 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12300 myEmptyAdj = client.emptyAdj;
12301 } else {
12302 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12303 }
12304 }
12305 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12306 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012307 String adjType = null;
12308 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12309 // Not doing bind OOM management, so treat
12310 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012311 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012312 // If this process has shown some UI, let it immediately
12313 // go to the LRU list because it may be pretty heavy with
12314 // UI stuff. We'll tag it with a label just to help
12315 // debug and understand what is going on.
12316 if (adj > clientAdj) {
12317 adjType = "bound-bg-ui-services";
12318 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012319 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012320 clientAdj = adj;
12321 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012322 if (now >= (s.lastActivity
12323 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012324 // This service has not seen activity within
12325 // recent memory, so allow it to drop to the
12326 // LRU list if there is no other reason to keep
12327 // it around. We'll also tag it with a label just
12328 // to help debug and undertand what is going on.
12329 if (adj > clientAdj) {
12330 adjType = "bound-bg-services";
12331 }
12332 clientAdj = adj;
12333 }
12334 }
12335 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012336 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012337 // If this process has recently shown UI, and
12338 // the process that is binding to it is less
12339 // important than being visible, then we don't
12340 // care about the binding as much as we care
12341 // about letting this process get into the LRU
12342 // list to be killed and restarted if needed for
12343 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012344 if (app.hasShownUi && app != mHomeProcess
12345 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012346 adjType = "bound-bg-ui-services";
12347 } else {
12348 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12349 |Context.BIND_IMPORTANT)) != 0) {
12350 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012351 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12352 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12353 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12354 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12355 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012356 adj = clientAdj;
12357 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012358 app.pendingUiClean = true;
12359 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12360 adj = ProcessList.VISIBLE_APP_ADJ;
12361 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012362 }
12363 if (!client.hidden) {
12364 app.hidden = false;
12365 }
12366 if (client.keeping) {
12367 app.keeping = true;
12368 }
12369 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012370 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012371 }
12372 if (adjType != null) {
12373 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012374 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12375 .REASON_SERVICE_IN_USE;
12376 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012377 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012378 app.adjTarget = s.name;
12379 }
12380 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12381 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12382 schedGroup = Process.THREAD_GROUP_DEFAULT;
12383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012384 }
12385 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012386 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12387 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012388 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012389 (a.visible || a.state == ActivityState.RESUMED
12390 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012391 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012392 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12393 schedGroup = Process.THREAD_GROUP_DEFAULT;
12394 }
12395 app.hidden = false;
12396 app.adjType = "service";
12397 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12398 .REASON_SERVICE_IN_USE;
12399 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012400 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012401 app.adjTarget = s.name;
12402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012404 }
12405 }
12406 }
12407 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012408
Dianne Hackborn287952c2010-09-22 22:34:31 -070012409 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012410 // would like to avoid killing it unless it would prevent the current
12411 // application from running. By default we put the process in
12412 // with the rest of the background processes; as we scan through
12413 // its services we may bump it up from there.
12414 if (adj > hiddenAdj) {
12415 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012416 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012417 app.adjType = "bg-services";
12418 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419 }
12420
Dianne Hackborn7d608422011-08-07 16:24:18 -070012421 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012422 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012423 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012424 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012425 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012426 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012427 for (int i = cpr.connections.size()-1;
12428 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12429 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12430 i--) {
12431 ContentProviderConnection conn = cpr.connections.get(i);
12432 ProcessRecord client = conn.client;
12433 if (client == app) {
12434 // Being our own client is not interesting.
12435 continue;
12436 }
12437 int myHiddenAdj = hiddenAdj;
12438 if (myHiddenAdj > client.hiddenAdj) {
12439 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12440 myHiddenAdj = client.hiddenAdj;
12441 } else {
12442 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012443 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012444 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012445 int myEmptyAdj = emptyAdj;
12446 if (myEmptyAdj > client.emptyAdj) {
12447 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12448 myEmptyAdj = client.emptyAdj;
12449 } else {
12450 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12451 }
12452 }
12453 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12454 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012455 if (adj > clientAdj) {
12456 if (app.hasShownUi && app != mHomeProcess
12457 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12458 app.adjType = "bg-ui-provider";
12459 } else {
12460 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12461 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12462 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012463 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012464 if (!client.hidden) {
12465 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012467 if (client.keeping) {
12468 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012469 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012470 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12471 .REASON_PROVIDER_IN_USE;
12472 app.adjSource = client;
12473 app.adjSourceOom = clientAdj;
12474 app.adjTarget = cpr.name;
12475 }
12476 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12477 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
12479 }
12480 // If the provider has external (non-framework) process
12481 // dependencies, ensure that its adjustment is at least
12482 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012483 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012484 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12485 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012486 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012487 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012488 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012489 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012490 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 }
12492 }
12493 }
12494 }
12495
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012496 if (adj == ProcessList.SERVICE_ADJ) {
12497 if (doingAll) {
12498 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12499 mNewNumServiceProcs++;
12500 }
12501 if (app.serviceb) {
12502 adj = ProcessList.SERVICE_B_ADJ;
12503 }
12504 } else {
12505 app.serviceb = false;
12506 }
12507
12508 app.nonStoppingAdj = adj;
12509
12510 if (hasStoppingActivities) {
12511 // Only upgrade adjustment.
12512 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12513 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12514 app.adjType = "stopping";
12515 }
12516 }
12517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012518 app.curRawAdj = adj;
12519
Joe Onorato8a9b2202010-02-26 18:56:32 -080012520 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012521 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12522 if (adj > app.maxAdj) {
12523 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012524 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012525 schedGroup = Process.THREAD_GROUP_DEFAULT;
12526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012528 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012529 app.keeping = true;
12530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012532 if (app.hasAboveClient) {
12533 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12534 // then we need to drop its adjustment to be lower than the service's
12535 // in order to honor the request. We want to drop it by one adjustment
12536 // level... but there is special meaning applied to various levels so
12537 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012538 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012539 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012540 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12541 adj = ProcessList.VISIBLE_APP_ADJ;
12542 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12543 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12544 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12545 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012546 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012547 adj++;
12548 }
12549 }
12550
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012551 int importance = app.memImportance;
12552 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12553 app.curAdj = adj;
12554 app.curSchedGroup = schedGroup;
12555 if (!interesting) {
12556 // For this reporting, if there is not something explicitly
12557 // interesting in this process then we will push it to the
12558 // background importance.
12559 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12560 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12561 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12562 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12563 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12564 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12565 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12566 } else if (adj >= ProcessList.SERVICE_ADJ) {
12567 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12568 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12569 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12570 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12571 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12572 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12573 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12574 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12575 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12576 } else {
12577 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12578 }
12579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012580
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012581 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12582 if (foregroundActivities != app.foregroundActivities) {
12583 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12584 }
12585 if (changes != 0) {
12586 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12587 app.memImportance = importance;
12588 app.foregroundActivities = foregroundActivities;
12589 int i = mPendingProcessChanges.size()-1;
12590 ProcessChangeItem item = null;
12591 while (i >= 0) {
12592 item = mPendingProcessChanges.get(i);
12593 if (item.pid == app.pid) {
12594 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12595 break;
12596 }
12597 i--;
12598 }
12599 if (i < 0) {
12600 // No existing item in pending changes; need a new one.
12601 final int NA = mAvailProcessChanges.size();
12602 if (NA > 0) {
12603 item = mAvailProcessChanges.remove(NA-1);
12604 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12605 } else {
12606 item = new ProcessChangeItem();
12607 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12608 }
12609 item.changes = 0;
12610 item.pid = app.pid;
12611 item.uid = app.info.uid;
12612 if (mPendingProcessChanges.size() == 0) {
12613 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12614 "*** Enqueueing dispatch processes changed!");
12615 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12616 }
12617 mPendingProcessChanges.add(item);
12618 }
12619 item.changes |= changes;
12620 item.importance = importance;
12621 item.foregroundActivities = foregroundActivities;
12622 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12623 + Integer.toHexString(System.identityHashCode(item))
12624 + " " + app.toShortString() + ": changes=" + item.changes
12625 + " importance=" + item.importance
12626 + " foreground=" + item.foregroundActivities
12627 + " type=" + app.adjType + " source=" + app.adjSource
12628 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012629 }
12630
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012631 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 }
12633
12634 /**
12635 * Ask a given process to GC right now.
12636 */
12637 final void performAppGcLocked(ProcessRecord app) {
12638 try {
12639 app.lastRequestedGc = SystemClock.uptimeMillis();
12640 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012641 if (app.reportLowMemory) {
12642 app.reportLowMemory = false;
12643 app.thread.scheduleLowMemory();
12644 } else {
12645 app.thread.processInBackground();
12646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012647 }
12648 } catch (Exception e) {
12649 // whatever.
12650 }
12651 }
12652
12653 /**
12654 * Returns true if things are idle enough to perform GCs.
12655 */
Josh Bartel7f208742010-02-25 11:01:44 -060012656 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012657 boolean processingBroadcasts = false;
12658 for (BroadcastQueue q : mBroadcastQueues) {
12659 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12660 processingBroadcasts = true;
12661 }
12662 }
12663 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012664 && (mSleeping || (mMainStack.mResumedActivity != null &&
12665 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012666 }
12667
12668 /**
12669 * Perform GCs on all processes that are waiting for it, but only
12670 * if things are idle.
12671 */
12672 final void performAppGcsLocked() {
12673 final int N = mProcessesToGc.size();
12674 if (N <= 0) {
12675 return;
12676 }
Josh Bartel7f208742010-02-25 11:01:44 -060012677 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012678 while (mProcessesToGc.size() > 0) {
12679 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012680 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012681 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12682 <= SystemClock.uptimeMillis()) {
12683 // To avoid spamming the system, we will GC processes one
12684 // at a time, waiting a few seconds between each.
12685 performAppGcLocked(proc);
12686 scheduleAppGcsLocked();
12687 return;
12688 } else {
12689 // It hasn't been long enough since we last GCed this
12690 // process... put it in the list to wait for its time.
12691 addProcessToGcListLocked(proc);
12692 break;
12693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 }
12695 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012696
12697 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012698 }
12699 }
12700
12701 /**
12702 * If all looks good, perform GCs on all processes waiting for them.
12703 */
12704 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012705 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 performAppGcsLocked();
12707 return;
12708 }
12709 // Still not idle, wait some more.
12710 scheduleAppGcsLocked();
12711 }
12712
12713 /**
12714 * Schedule the execution of all pending app GCs.
12715 */
12716 final void scheduleAppGcsLocked() {
12717 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012718
12719 if (mProcessesToGc.size() > 0) {
12720 // Schedule a GC for the time to the next process.
12721 ProcessRecord proc = mProcessesToGc.get(0);
12722 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12723
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012724 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012725 long now = SystemClock.uptimeMillis();
12726 if (when < (now+GC_TIMEOUT)) {
12727 when = now + GC_TIMEOUT;
12728 }
12729 mHandler.sendMessageAtTime(msg, when);
12730 }
12731 }
12732
12733 /**
12734 * Add a process to the array of processes waiting to be GCed. Keeps the
12735 * list in sorted order by the last GC time. The process can't already be
12736 * on the list.
12737 */
12738 final void addProcessToGcListLocked(ProcessRecord proc) {
12739 boolean added = false;
12740 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12741 if (mProcessesToGc.get(i).lastRequestedGc <
12742 proc.lastRequestedGc) {
12743 added = true;
12744 mProcessesToGc.add(i+1, proc);
12745 break;
12746 }
12747 }
12748 if (!added) {
12749 mProcessesToGc.add(0, proc);
12750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 }
12752
12753 /**
12754 * Set up to ask a process to GC itself. This will either do it
12755 * immediately, or put it on the list of processes to gc the next
12756 * time things are idle.
12757 */
12758 final void scheduleAppGcLocked(ProcessRecord app) {
12759 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012760 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012761 return;
12762 }
12763 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012764 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765 scheduleAppGcsLocked();
12766 }
12767 }
12768
Dianne Hackborn287952c2010-09-22 22:34:31 -070012769 final void checkExcessivePowerUsageLocked(boolean doKills) {
12770 updateCpuStatsNow();
12771
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012772 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012773 boolean doWakeKills = doKills;
12774 boolean doCpuKills = doKills;
12775 if (mLastPowerCheckRealtime == 0) {
12776 doWakeKills = false;
12777 }
12778 if (mLastPowerCheckUptime == 0) {
12779 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012780 }
12781 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012782 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012783 }
12784 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070012785 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
12786 final long curUptime = SystemClock.uptimeMillis();
12787 final long uptimeSince = curUptime - mLastPowerCheckUptime;
12788 mLastPowerCheckRealtime = curRealtime;
12789 mLastPowerCheckUptime = curUptime;
12790 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
12791 doWakeKills = false;
12792 }
12793 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
12794 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012795 }
12796 int i = mLruProcesses.size();
12797 while (i > 0) {
12798 i--;
12799 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012800 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012801 long wtime;
12802 synchronized (stats) {
12803 wtime = stats.getProcessWakeTime(app.info.uid,
12804 app.pid, curRealtime);
12805 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012806 long wtimeUsed = wtime - app.lastWakeTime;
12807 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
12808 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012809 StringBuilder sb = new StringBuilder(128);
12810 sb.append("Wake for ");
12811 app.toShortString(sb);
12812 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012813 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012814 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012815 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012816 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070012817 sb.append((wtimeUsed*100)/realtimeSince);
12818 sb.append("%)");
12819 Slog.i(TAG, sb.toString());
12820 sb.setLength(0);
12821 sb.append("CPU for ");
12822 app.toShortString(sb);
12823 sb.append(": over ");
12824 TimeUtils.formatDuration(uptimeSince, sb);
12825 sb.append(" used ");
12826 TimeUtils.formatDuration(cputimeUsed, sb);
12827 sb.append(" (");
12828 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070012829 sb.append("%)");
12830 Slog.i(TAG, sb.toString());
12831 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012832 // If a process has held a wake lock for more
12833 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012834 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070012835 if (doWakeKills && realtimeSince > 0
12836 && ((wtimeUsed*100)/realtimeSince) >= 50) {
12837 synchronized (stats) {
12838 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
12839 realtimeSince, wtimeUsed);
12840 }
12841 Slog.w(TAG, "Excessive wake lock in " + app.processName
12842 + " (pid " + app.pid + "): held " + wtimeUsed
12843 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012844 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12845 app.processName, app.setAdj, "excessive wake lock");
12846 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012847 } else if (doCpuKills && uptimeSince > 0
12848 && ((cputimeUsed*100)/uptimeSince) >= 50) {
12849 synchronized (stats) {
12850 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
12851 uptimeSince, cputimeUsed);
12852 }
12853 Slog.w(TAG, "Excessive CPU in " + app.processName
12854 + " (pid " + app.pid + "): used " + cputimeUsed
12855 + " during " + uptimeSince);
12856 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12857 app.processName, app.setAdj, "excessive cpu");
12858 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012859 } else {
12860 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012861 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012862 }
12863 }
12864 }
12865 }
12866
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012867 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
12868 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012870 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012871
12872 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012873 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012874 }
12875
Dianne Hackborn287952c2010-09-22 22:34:31 -070012876 final boolean wasKeeping = app.keeping;
12877
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012878 boolean success = true;
12879
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012880 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881
Jeff Brown10e89712011-07-08 18:52:57 -070012882 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070012883 if (wasKeeping && !app.keeping) {
12884 // This app is no longer something we want to keep. Note
12885 // its current wake lock time to later know to kill it if
12886 // it is not behaving well.
12887 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12888 synchronized (stats) {
12889 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
12890 app.pid, SystemClock.elapsedRealtime());
12891 }
12892 app.lastCpuTime = app.curCpuTime;
12893 }
12894
12895 app.setRawAdj = app.curRawAdj;
12896 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012897
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012898 if (app.curAdj != app.setAdj) {
12899 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080012900 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012901 TAG, "Set " + app.pid + " " + app.processName +
12902 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012903 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070012904 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012905 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012906 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070012907 }
12908 }
12909 if (app.setSchedGroup != app.curSchedGroup) {
12910 app.setSchedGroup = app.curSchedGroup;
12911 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
12912 "Setting process group of " + app.processName
12913 + " to " + app.curSchedGroup);
12914 if (app.waitingToKill != null &&
12915 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
12916 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
12917 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
12918 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070012919 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070012920 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012921 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070012922 } else {
12923 if (true) {
12924 long oldId = Binder.clearCallingIdentity();
12925 try {
12926 Process.setProcessGroup(app.pid, app.curSchedGroup);
12927 } catch (Exception e) {
12928 Slog.w(TAG, "Failed setting process group of " + app.pid
12929 + " to " + app.curSchedGroup);
12930 e.printStackTrace();
12931 } finally {
12932 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070012933 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012934 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070012935 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012936 try {
Jeff Brown10e89712011-07-08 18:52:57 -070012937 app.thread.setSchedulingGroup(app.curSchedGroup);
12938 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070012939 }
12940 }
12941 }
12942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012944 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012945 }
12946
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012947 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012948 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012949 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080012950 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012951 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012952 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 }
12954 }
12955 return resumedActivity;
12956 }
12957
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012958 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012959 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012960 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12961 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012962 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12963 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964
12965 mAdjSeq++;
12966
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012967 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
12968 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012969 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
12970 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012971 if (nowHidden != wasHidden) {
12972 // Changed to/from hidden state, so apps after it in the LRU
12973 // list may also be changed.
12974 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070012976 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012977 }
12978
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012979 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012980 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012981 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
12982
12983 if (false) {
12984 RuntimeException e = new RuntimeException();
12985 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012986 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 }
12988
12989 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012990 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012992 // Let's determine how many processes we have running vs.
12993 // how many slots we have for background processes; we may want
12994 // to put multiple processes in a slot of there are enough of
12995 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012996 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
12997 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
12998 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
12999 if (emptyFactor < 1) emptyFactor = 1;
13000 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13001 if (hiddenFactor < 1) hiddenFactor = 1;
13002 int stepHidden = 0;
13003 int stepEmpty = 0;
13004 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13005 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013006 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013007 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013008 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013009
13010 mNumNonHiddenProcs = 0;
13011 mNumHiddenProcs = 0;
13012
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013013 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013015 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013016 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013017 int nextHiddenAdj = curHiddenAdj+1;
13018 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13019 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 while (i > 0) {
13021 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013022 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013023 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013024 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013025 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013026 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13027 // This process was assigned as a hidden process... step the
13028 // hidden level.
13029 mNumHiddenProcs++;
13030 if (curHiddenAdj != nextHiddenAdj) {
13031 stepHidden++;
13032 if (stepHidden >= hiddenFactor) {
13033 stepHidden = 0;
13034 curHiddenAdj = nextHiddenAdj;
13035 nextHiddenAdj += 2;
13036 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13037 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13038 }
13039 }
13040 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013041 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013042 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013043 Slog.i(TAG, "No longer want " + app.processName
13044 + " (pid " + app.pid + "): hidden #" + numHidden);
13045 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13046 app.processName, app.setAdj, "too many background");
13047 app.killedBackground = true;
13048 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013049 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013050 } else {
13051 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13052 // This process was assigned as an empty process... step the
13053 // empty level.
13054 if (curEmptyAdj != nextEmptyAdj) {
13055 stepEmpty++;
13056 if (stepEmpty >= emptyFactor) {
13057 stepEmpty = 0;
13058 curEmptyAdj = nextEmptyAdj;
13059 nextEmptyAdj += 2;
13060 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13061 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13062 }
13063 }
13064 }
13065 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13066 mNumNonHiddenProcs++;
13067 }
13068 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13069 numEmpty++;
13070 if (numEmpty > emptyProcessLimit) {
13071 Slog.i(TAG, "No longer want " + app.processName
13072 + " (pid " + app.pid + "): empty #" + numEmpty);
13073 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13074 app.processName, app.setAdj, "too many background");
13075 app.killedBackground = true;
13076 Process.killProcessQuiet(app.pid);
13077 }
13078 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013079 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013080 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013081 // If this is an isolated process, and there are no
13082 // services running in it, then the process is no longer
13083 // needed. We agressively kill these because we can by
13084 // definition not re-use the same process again, and it is
13085 // good to avoid having whatever code was running in them
13086 // left sitting around after no longer needed.
13087 Slog.i(TAG, "Isolated process " + app.processName
13088 + " (pid " + app.pid + ") no longer needed");
13089 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13090 app.processName, app.setAdj, "isolated not needed");
13091 app.killedBackground = true;
13092 Process.killProcessQuiet(app.pid);
13093 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013094 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13095 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13096 && !app.killedBackground) {
13097 numTrimming++;
13098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 }
13100 }
13101
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013102 mNumServiceProcs = mNewNumServiceProcs;
13103
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013104 // Now determine the memory trimming level of background processes.
13105 // Unfortunately we need to start at the back of the list to do this
13106 // properly. We only do this if the number of background apps we
13107 // are managing to keep around is less than half the maximum we desire;
13108 // if we are keeping a good number around, we'll let them use whatever
13109 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013110 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13111 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13112 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013113 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013114 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013115 int minFactor = 2;
13116 if (mHomeProcess != null) minFactor++;
13117 if (mPreviousProcess != null) minFactor++;
13118 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013119 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013120 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013121 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013122 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013123 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013124 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13125 } else {
13126 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13127 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013128 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013129 for (i=0; i<N; i++) {
13130 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013131 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13132 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013133 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013134 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13135 try {
13136 app.thread.scheduleTrimMemory(curLevel);
13137 } catch (RemoteException e) {
13138 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013139 if (false) {
13140 // For now we won't do this; our memory trimming seems
13141 // to be good enough at this point that destroying
13142 // activities causes more harm than good.
13143 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13144 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013145 // Need to do this on its own message because the stack may not
13146 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013147 // For these apps we will also finish their activities
13148 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013149 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013150 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013151 }
13152 }
13153 app.trimMemoryLevel = curLevel;
13154 step++;
13155 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013156 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013157 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013158 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13159 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013160 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013161 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13162 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013163 break;
13164 }
13165 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013166 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013167 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013168 && app.thread != null) {
13169 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013170 app.thread.scheduleTrimMemory(
13171 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013172 } catch (RemoteException e) {
13173 }
13174 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013175 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013176 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013177 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013178 && app.pendingUiClean) {
13179 // If this application is now in the background and it
13180 // had done UI, then give it the special trim level to
13181 // have it free UI resources.
13182 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13183 if (app.trimMemoryLevel < level && app.thread != null) {
13184 try {
13185 app.thread.scheduleTrimMemory(level);
13186 } catch (RemoteException e) {
13187 }
13188 }
13189 app.pendingUiClean = false;
13190 }
13191 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013192 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013193 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013194 } catch (RemoteException e) {
13195 }
13196 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013197 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013198 }
13199 }
13200 } else {
13201 final int N = mLruProcesses.size();
13202 for (i=0; i<N; i++) {
13203 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013204 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013205 && app.pendingUiClean) {
13206 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13207 && app.thread != null) {
13208 try {
13209 app.thread.scheduleTrimMemory(
13210 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13211 } catch (RemoteException e) {
13212 }
13213 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013214 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013215 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013216 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013217 }
13218 }
13219
13220 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013221 // Need to do this on its own message because the stack may not
13222 // be in a consistent state at this point.
13223 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 }
13226
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013227 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 synchronized (this) {
13229 int i;
13230
13231 // First remove any unused application processes whose package
13232 // has been removed.
13233 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13234 final ProcessRecord app = mRemovedProcesses.get(i);
13235 if (app.activities.size() == 0
13236 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013237 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 TAG, "Exiting empty application process "
13239 + app.processName + " ("
13240 + (app.thread != null ? app.thread.asBinder() : null)
13241 + ")\n");
13242 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013243 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13244 app.processName, app.setAdj, "empty");
13245 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 } else {
13247 try {
13248 app.thread.scheduleExit();
13249 } catch (Exception e) {
13250 // Ignore exceptions.
13251 }
13252 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013253 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013254 mRemovedProcesses.remove(i);
13255
13256 if (app.persistent) {
13257 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013258 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013259 }
13260 }
13261 }
13262 }
13263
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013264 // Now update the oom adj for all processes.
13265 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266 }
13267 }
13268
13269 /** This method sends the specified signal to each of the persistent apps */
13270 public void signalPersistentProcesses(int sig) throws RemoteException {
13271 if (sig != Process.SIGNAL_USR1) {
13272 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13273 }
13274
13275 synchronized (this) {
13276 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13277 != PackageManager.PERMISSION_GRANTED) {
13278 throw new SecurityException("Requires permission "
13279 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13280 }
13281
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013282 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13283 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013284 if (r.thread != null && r.persistent) {
13285 Process.sendSignal(r.pid, sig);
13286 }
13287 }
13288 }
13289 }
13290
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013291 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13292 if (proc == null || proc == mProfileProc) {
13293 proc = mProfileProc;
13294 path = mProfileFile;
13295 profileType = mProfileType;
13296 clearProfilerLocked();
13297 }
13298 if (proc == null) {
13299 return;
13300 }
13301 try {
13302 proc.thread.profilerControl(false, path, null, profileType);
13303 } catch (RemoteException e) {
13304 throw new IllegalStateException("Process disappeared");
13305 }
13306 }
13307
13308 private void clearProfilerLocked() {
13309 if (mProfileFd != null) {
13310 try {
13311 mProfileFd.close();
13312 } catch (IOException e) {
13313 }
13314 }
13315 mProfileApp = null;
13316 mProfileProc = null;
13317 mProfileFile = null;
13318 mProfileType = 0;
13319 mAutoStopProfiler = false;
13320 }
13321
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013322 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013323 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013324
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013325 try {
13326 synchronized (this) {
13327 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13328 // its own permission.
13329 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13330 != PackageManager.PERMISSION_GRANTED) {
13331 throw new SecurityException("Requires permission "
13332 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013333 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013334
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013335 if (start && fd == null) {
13336 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013337 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013338
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013339 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013340 if (process != null) {
13341 try {
13342 int pid = Integer.parseInt(process);
13343 synchronized (mPidsSelfLocked) {
13344 proc = mPidsSelfLocked.get(pid);
13345 }
13346 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013347 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013348
13349 if (proc == null) {
13350 HashMap<String, SparseArray<ProcessRecord>> all
13351 = mProcessNames.getMap();
13352 SparseArray<ProcessRecord> procs = all.get(process);
13353 if (procs != null && procs.size() > 0) {
13354 proc = procs.valueAt(0);
13355 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013356 }
13357 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013358
13359 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013360 throw new IllegalArgumentException("Unknown process: " + process);
13361 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013362
13363 if (start) {
13364 stopProfilerLocked(null, null, 0);
13365 setProfileApp(proc.info, proc.processName, path, fd, false);
13366 mProfileProc = proc;
13367 mProfileType = profileType;
13368 try {
13369 fd = fd.dup();
13370 } catch (IOException e) {
13371 fd = null;
13372 }
13373 proc.thread.profilerControl(start, path, fd, profileType);
13374 fd = null;
13375 mProfileFd = null;
13376 } else {
13377 stopProfilerLocked(proc, path, profileType);
13378 if (fd != null) {
13379 try {
13380 fd.close();
13381 } catch (IOException e) {
13382 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013383 }
13384 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013385
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013386 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013387 }
13388 } catch (RemoteException e) {
13389 throw new IllegalStateException("Process disappeared");
13390 } finally {
13391 if (fd != null) {
13392 try {
13393 fd.close();
13394 } catch (IOException e) {
13395 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013396 }
13397 }
13398 }
Andy McFadden824c5102010-07-09 16:26:57 -070013399
13400 public boolean dumpHeap(String process, boolean managed,
13401 String path, ParcelFileDescriptor fd) throws RemoteException {
13402
13403 try {
13404 synchronized (this) {
13405 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13406 // its own permission (same as profileControl).
13407 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13408 != PackageManager.PERMISSION_GRANTED) {
13409 throw new SecurityException("Requires permission "
13410 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13411 }
13412
13413 if (fd == null) {
13414 throw new IllegalArgumentException("null fd");
13415 }
13416
13417 ProcessRecord proc = null;
13418 try {
13419 int pid = Integer.parseInt(process);
13420 synchronized (mPidsSelfLocked) {
13421 proc = mPidsSelfLocked.get(pid);
13422 }
13423 } catch (NumberFormatException e) {
13424 }
13425
13426 if (proc == null) {
13427 HashMap<String, SparseArray<ProcessRecord>> all
13428 = mProcessNames.getMap();
13429 SparseArray<ProcessRecord> procs = all.get(process);
13430 if (procs != null && procs.size() > 0) {
13431 proc = procs.valueAt(0);
13432 }
13433 }
13434
13435 if (proc == null || proc.thread == null) {
13436 throw new IllegalArgumentException("Unknown process: " + process);
13437 }
13438
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013439 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13440 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013441 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13442 throw new SecurityException("Process not debuggable: " + proc);
13443 }
13444 }
13445
13446 proc.thread.dumpHeap(managed, path, fd);
13447 fd = null;
13448 return true;
13449 }
13450 } catch (RemoteException e) {
13451 throw new IllegalStateException("Process disappeared");
13452 } finally {
13453 if (fd != null) {
13454 try {
13455 fd.close();
13456 } catch (IOException e) {
13457 }
13458 }
13459 }
13460 }
13461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013462 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13463 public void monitor() {
13464 synchronized (this) { }
13465 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013466
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013467 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013468 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13469 ProcessRecord processRecord = mLruProcesses.get(i);
13470 try {
13471 if (processRecord.thread != null) {
13472 processRecord.thread.setCoreSettings(settings);
13473 }
13474 } catch (RemoteException re) {
13475 /* ignore */
13476 }
13477 }
13478 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013479
13480 // Multi-user methods
13481
Amith Yamasani742a6712011-05-04 14:49:28 -070013482 public boolean switchUser(int userId) {
13483 final int callingUid = Binder.getCallingUid();
13484 if (callingUid != 0 && callingUid != Process.myUid()) {
13485 Slog.e(TAG, "Trying to switch user from unauthorized app");
13486 return false;
13487 }
13488 if (mCurrentUserId == userId)
13489 return true;
13490
13491 synchronized (this) {
13492 // Check if user is already logged in, otherwise check if user exists first before
13493 // adding to the list of logged in users.
13494 if (mLoggedInUsers.indexOfKey(userId) < 0) {
13495 if (!userExists(userId)) {
13496 return false;
13497 }
13498 mLoggedInUsers.append(userId, userId);
13499 }
13500
13501 mCurrentUserId = userId;
13502 boolean haveActivities = mMainStack.switchUser(userId);
13503 if (!haveActivities) {
13504 startHomeActivityLocked(userId);
13505 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013506
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013507 }
Amith Yamasani13593602012-03-22 16:16:17 -070013508
13509 // Inform of user switch
13510 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
Amith Yamasani2a003292012-08-14 18:25:45 -070013511 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Amith Yamasani1ab36c12012-08-17 13:55:02 -070013512 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_USERS);
Amith Yamasani13593602012-03-22 16:16:17 -070013513
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013514 return true;
13515 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013516
Amith Yamasani52f1d752012-03-28 18:19:29 -070013517 @Override
13518 public UserInfo getCurrentUser() throws RemoteException {
13519 final int callingUid = Binder.getCallingUid();
13520 if (callingUid != 0 && callingUid != Process.myUid()) {
13521 Slog.e(TAG, "Trying to get user from unauthorized app");
13522 return null;
13523 }
Amith Yamasani258848d2012-08-10 17:06:33 -070013524 return getUserManager().getUserInfo(mCurrentUserId);
Amith Yamasani52f1d752012-03-28 18:19:29 -070013525 }
13526
Amith Yamasani13593602012-03-22 16:16:17 -070013527 private void onUserRemoved(Intent intent) {
Amith Yamasani2a003292012-08-14 18:25:45 -070013528 int extraUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
Amith Yamasani13593602012-03-22 16:16:17 -070013529 if (extraUserId < 1) return;
13530
13531 // Kill all the processes for the user
13532 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
13533 synchronized (this) {
13534 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
13535 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
13536 SparseArray<ProcessRecord> uids = uidMap.getValue();
13537 for (int i = 0; i < uids.size(); i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013538 if (UserHandle.getUserId(uids.keyAt(i)) == extraUserId) {
Amith Yamasani13593602012-03-22 16:16:17 -070013539 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
13540 }
13541 }
13542 }
13543
13544 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
13545 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
13546 false, false, true, true, extraUserId);
13547 }
13548 }
13549 }
13550
Amith Yamasani742a6712011-05-04 14:49:28 -070013551 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013552 UserInfo user = getUserManager().getUserInfo(userId);
13553 return user != null;
13554 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013555
Amith Yamasani258848d2012-08-10 17:06:33 -070013556 UserManager getUserManager() {
13557 if (mUserManager == null) {
13558 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13559 }
13560 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013561 }
13562
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013563 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013564 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013565
13566 throw new SecurityException("Caller uid=" + uid
13567 + " is not privileged to communicate with user=" + userId);
13568 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013569
13570 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013571 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013572 }
13573
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013574 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013575 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013576 ApplicationInfo newInfo = new ApplicationInfo(info);
13577 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013578 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13579 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013580 return newInfo;
13581 }
13582
13583 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013584 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013585 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013586 return aInfo;
13587 }
13588
13589 ActivityInfo info = new ActivityInfo(aInfo);
13590 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13591 return info;
13592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013593}