blob: 84fcd5ebda6afc727e1c22b1fdb3071f32c70a16 [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;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.content.Intent;
66import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070067import android.content.IIntentReceiver;
68import android.content.IIntentSender;
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;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070078import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.content.pm.ProviderInfo;
80import android.content.pm.ResolveInfo;
81import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070082import android.content.pm.UserInfo;
Dianne Hackborn860755f2010-06-03 18:47:52 -070083import android.content.pm.PackageManager.NameNotFoundException;
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;
Amith Yamasani742a6712011-05-04 14:49:28 -0700112import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700114import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import android.util.EventLog;
Dianne Hackborn905577f2011-09-07 18:31:28 -0700116import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800117import android.util.Slog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800118import android.util.Log;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.PrintWriterPrinter;
120import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700121import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700122import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.view.Gravity;
124import android.view.LayoutInflater;
125import android.view.View;
126import android.view.WindowManager;
127import android.view.WindowManagerPolicy;
128
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700129import java.io.BufferedInputStream;
130import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700131import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.DataInputStream;
133import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134import java.io.File;
135import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700136import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200139import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800140import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700142import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.lang.IllegalStateException;
144import java.lang.ref.WeakReference;
145import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700146import java.util.Collection;
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;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700178 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800179 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700181 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700182 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700183 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700184 static final boolean DEBUG_POWER = localLOGV || false;
185 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700186 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 static final boolean VALIDATE_TOKENS = false;
188 static final boolean SHOW_ACTIVITY_START_TIME = true;
189
190 // Control over CPU and battery monitoring.
191 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
192 static final boolean MONITOR_CPU_USAGE = true;
193 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
194 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
195 static final boolean MONITOR_THREAD_CPU_USAGE = false;
196
Dianne Hackborn1655be42009-05-08 14:29:01 -0700197 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700198 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800200 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700202 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 // Maximum number of recent tasks that we can remember.
205 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700206
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700207 // Amount of time after a call to stopAppSwitches() during which we will
208 // prevent further untrusted switches from happening.
209 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
211 // How long we wait for a launched process to attach to the activity manager
212 // before we decide it's never going to come up for real.
213 static final int PROC_START_TIMEOUT = 10*1000;
214
Jeff Brown3f9dd282011-07-08 20:02:19 -0700215 // How long we wait for a launched process to attach to the activity manager
216 // before we decide it's never going to come up for real, when the process was
217 // started with a wrapper for instrumentation (such as Valgrind) because it
218 // could take much longer than usual.
219 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 // How long to wait after going idle before forcing apps to GC.
222 static final int GC_TIMEOUT = 5*1000;
223
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700224 // The minimum amount of time between successive GC requests for a process.
225 static final int GC_MIN_INTERVAL = 60*1000;
226
Dianne Hackborn287952c2010-09-22 22:34:31 -0700227 // The rate at which we check for apps using excessive power -- 15 mins.
228 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
229
230 // The minimum sample duration we will allow before deciding we have
231 // enough data on wake locks to start killing things.
232 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
233
234 // The minimum sample duration we will allow before deciding we have
235 // enough data on CPU usage to start killing things.
236 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800239 static final int BROADCAST_FG_TIMEOUT = 10*1000;
240 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
242 // How long we wait for a service to finish executing.
243 static final int SERVICE_TIMEOUT = 20*1000;
244
245 // How long a service needs to be running until restarting its process
246 // is no longer considered to be a relaunch of the service.
247 static final int SERVICE_RESTART_DURATION = 5*1000;
248
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700249 // How long a service needs to be running until it will start back at
250 // SERVICE_RESTART_DURATION after being killed.
251 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
252
253 // Multiplying factor to increase restart duration time by, for each time
254 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
255 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
256
257 // The minimum amount of time between restarting services that we allow.
258 // That is, when multiple services are restarting, we won't allow each
259 // to restart less than this amount of time from the last one.
260 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 // Maximum amount of time for there to be no activity on a service before
263 // we consider it non-essential and allow its process to go on the
264 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700265 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266
267 // How long we wait until we timeout on key dispatching.
268 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // How long we wait until we timeout on key dispatching during instrumentation.
271 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
272
Dan Egnor42471dd2010-01-07 17:25:22 -0800273 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800274
275 static final String[] EMPTY_STRING_ARRAY = new String[0];
276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700277 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700278
279 private final boolean mHeadless;
280
Joe Onorato54a4a412011-11-02 20:50:08 -0700281 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
282 // default actuion automatically. Important for devices without direct input
283 // devices.
284 private boolean mShowDialogs = true;
285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700287 * Description of a request to start a new activity, which has been held
288 * due to app switches being disabled.
289 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700290 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700291 ActivityRecord r;
292 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700293 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700294 }
295
296 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
297 = new ArrayList<PendingActivityLaunch>();
298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800300 BroadcastQueue mFgBroadcastQueue;
301 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800302 // Convenient for easy iteration over the queues. Foreground is first
303 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800304 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800305
306 BroadcastQueue broadcastQueueForIntent(Intent intent) {
307 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
308 if (DEBUG_BACKGROUND_BROADCAST) {
309 Slog.i(TAG, "Broadcast intent " + intent + " on "
310 + (isFg ? "foreground" : "background")
311 + " queue");
312 }
313 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
314 }
315
316 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
317 for (BroadcastQueue queue : mBroadcastQueues) {
318 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
319 if (r != null) {
320 return r;
321 }
322 }
323 return null;
324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * Activity we have told the window manager to have key focus.
328 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700329 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700330 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800331 * List of intents that were used to start the most recent tasks.
332 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700333 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334
335 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700336 * Process management.
337 */
338 final ProcessList mProcessList = new ProcessList();
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * All of the applications we currently have running organized by name.
342 * The keys are strings of the application package name (as
343 * returned by the package manager), and the keys are ApplicationRecord
344 * objects.
345 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700346 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
348 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800349 * The currently running isolated processes.
350 */
351 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
352
353 /**
354 * Counter for assigning isolated process uids, to avoid frequently reusing the
355 * same ones.
356 */
357 int mNextIsolatedProcessUid = 0;
358
359 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700360 * The currently running heavy-weight process, if any.
361 */
362 ProcessRecord mHeavyWeightProcess = null;
363
364 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 * The last time that various processes have crashed.
366 */
367 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
368
369 /**
370 * Set of applications that we consider to be bad, and will reject
371 * incoming broadcasts from (which the user has no control over).
372 * Processes are added to this set when they have crashed twice within
373 * a minimum amount of time; they are removed from it when they are
374 * later restarted (hopefully due to some user action). The value is the
375 * time it was added to the list.
376 */
377 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
378
379 /**
380 * All of the processes we currently have running organized by pid.
381 * The keys are the pid running the application.
382 *
383 * <p>NOTE: This object is protected by its own lock, NOT the global
384 * activity manager lock!
385 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700386 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387
388 /**
389 * All of the processes that have been forced to be foreground. The key
390 * is the pid of the caller who requested it (we hold a death
391 * link on it).
392 */
393 abstract class ForegroundToken implements IBinder.DeathRecipient {
394 int pid;
395 IBinder token;
396 }
397 final SparseArray<ForegroundToken> mForegroundProcesses
398 = new SparseArray<ForegroundToken>();
399
400 /**
401 * List of records for processes that someone had tried to start before the
402 * system was ready. We don't start them at that point, but ensure they
403 * are started by the time booting is complete.
404 */
405 final ArrayList<ProcessRecord> mProcessesOnHold
406 = new ArrayList<ProcessRecord>();
407
408 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800409 * List of persistent applications that are in the process
410 * of being started.
411 */
412 final ArrayList<ProcessRecord> mPersistentStartingProcesses
413 = new ArrayList<ProcessRecord>();
414
415 /**
416 * Processes that are being forcibly torn down.
417 */
418 final ArrayList<ProcessRecord> mRemovedProcesses
419 = new ArrayList<ProcessRecord>();
420
421 /**
422 * List of running applications, sorted by recent usage.
423 * The first entry in the list is the least recently used.
424 * It contains ApplicationRecord objects. This list does NOT include
425 * any persistent application records (since we never want to exit them).
426 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800427 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800428 = new ArrayList<ProcessRecord>();
429
430 /**
431 * List of processes that should gc as soon as things are idle.
432 */
433 final ArrayList<ProcessRecord> mProcessesToGc
434 = new ArrayList<ProcessRecord>();
435
436 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800437 * This is the process holding what we currently consider to be
438 * the "home" activity.
439 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800441
442 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700443 * This is the process holding the activity the user last visited that
444 * is in a different process from the one they are currently in.
445 */
446 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800447
448 /**
449 * The time at which the previous process was last visible.
450 */
451 long mPreviousProcessVisibleTime;
452
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700453 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400454 * Packages that the user has asked to have run in screen size
455 * compatibility mode instead of filling the screen.
456 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700457 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400458
459 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 * Set of PendingResultRecord objects that are currently active.
461 */
462 final HashSet mPendingResultRecords = new HashSet();
463
464 /**
465 * Set of IntentSenderRecord objects that are currently active.
466 */
467 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
468 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
469
470 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800471 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700472 * already logged DropBox entries for. Guarded by itself. If
473 * something (rogue user app) forces this over
474 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
475 */
476 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
477 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
478
479 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700480 * Strict Mode background batched logging state.
481 *
482 * The string buffer is guarded by itself, and its lock is also
483 * used to determine if another batched write is already
484 * in-flight.
485 */
486 private final StringBuilder mStrictModeBuffer = new StringBuilder();
487
488 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 * Keeps track of all IIntentReceivers that have been registered for
490 * broadcasts. Hash keys are the receiver IBinder, hash value is
491 * a ReceiverList.
492 */
493 final HashMap mRegisteredReceivers = new HashMap();
494
495 /**
496 * Resolver for broadcast intents to registered receivers.
497 * Holds BroadcastFilter (subclass of IntentFilter).
498 */
499 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
500 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
501 @Override
502 protected boolean allowFilterResult(
503 BroadcastFilter filter, List<BroadcastFilter> dest) {
504 IBinder target = filter.receiverList.receiver.asBinder();
505 for (int i=dest.size()-1; i>=0; i--) {
506 if (dest.get(i).receiverList.receiver.asBinder() == target) {
507 return false;
508 }
509 }
510 return true;
511 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700512
513 @Override
514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
520 * State of all active sticky broadcasts. Keys are the action of the
521 * sticky Intent, values are an ArrayList of all broadcasted intents with
522 * that action (which should usually be one).
523 */
524 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
525 new HashMap<String, ArrayList<Intent>>();
526
Amith Yamasani742a6712011-05-04 14:49:28 -0700527 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
529 /**
530 * All currently bound service connections. Keys are the IBinder of
531 * the client's IServiceConnection.
532 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700533 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
534 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * List of services that we have been asked to start,
538 * but haven't yet been able to. It is used to hold start requests
539 * while waiting for their corresponding application thread to get
540 * going.
541 */
542 final ArrayList<ServiceRecord> mPendingServices
543 = new ArrayList<ServiceRecord>();
544
545 /**
546 * List of services that are scheduled to restart following a crash.
547 */
548 final ArrayList<ServiceRecord> mRestartingServices
549 = new ArrayList<ServiceRecord>();
550
551 /**
552 * List of services that are in the process of being stopped.
553 */
554 final ArrayList<ServiceRecord> mStoppingServices
555 = new ArrayList<ServiceRecord>();
556
557 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700558 * Backup/restore process management
559 */
560 String mBackupAppName = null;
561 BackupRecord mBackupTarget = null;
562
563 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * List of PendingThumbnailsRecord objects of clients who are still
565 * waiting to receive all of the thumbnails for a task.
566 */
567 final ArrayList mPendingThumbnails = new ArrayList();
568
569 /**
570 * List of HistoryRecord objects that have been finished and must
571 * still report back to a pending thumbnail receiver.
572 */
573 final ArrayList mCancelledThumbnails = new ArrayList();
574
Amith Yamasani742a6712011-05-04 14:49:28 -0700575 final ProviderMap mProviderMap = new ProviderMap();
576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800577 /**
578 * List of content providers who have clients waiting for them. The
579 * application is currently being launched and the provider will be
580 * removed from this list once it is published.
581 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700582 final ArrayList<ContentProviderRecord> mLaunchingProviders
583 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
585 /**
586 * Global set of specific Uri permissions that have been granted.
587 */
588 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
589 = new SparseArray<HashMap<Uri, UriPermission>>();
590
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800591 CoreSettingsObserver mCoreSettingsObserver;
592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800593 /**
594 * Thread-local storage used to carry caller permissions over through
595 * indirect content-provider access.
596 * @see #ActivityManagerService.openContentUri()
597 */
598 private class Identity {
599 public int pid;
600 public int uid;
601
602 Identity(int _pid, int _uid) {
603 pid = _pid;
604 uid = _uid;
605 }
606 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
609
610 /**
611 * All information we have collected about the runtime performance of
612 * any user id that can impact battery performance.
613 */
614 final BatteryStatsService mBatteryStatsService;
615
616 /**
617 * information about component usage
618 */
619 final UsageStatsService mUsageStatsService;
620
621 /**
622 * Current configuration information. HistoryRecord objects are given
623 * a reference to this object to indicate which configuration they are
624 * currently running in, so this object must be kept immutable.
625 */
626 Configuration mConfiguration = new Configuration();
627
628 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800629 * Current sequencing integer of the configuration, for skipping old
630 * configurations.
631 */
632 int mConfigurationSeq = 0;
633
634 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700635 * Hardware-reported OpenGLES version.
636 */
637 final int GL_ES_VERSION;
638
639 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800640 * List of initialization arguments to pass to all processes when binding applications to them.
641 * For example, references to the commonly used services.
642 */
643 HashMap<String, IBinder> mAppBindArgs;
644
645 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700646 * Temporary to avoid allocations. Protected by main lock.
647 */
648 final StringBuilder mStringBuilder = new StringBuilder(256);
649
650 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 * Used to control how we initialize the service.
652 */
653 boolean mStartRunning = false;
654 ComponentName mTopComponent;
655 String mTopAction;
656 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700657 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 boolean mSystemReady = false;
659 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700660 boolean mWaitingUpdate = false;
661 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700662 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700663 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664
665 Context mContext;
666
667 int mFactoryTest;
668
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700669 boolean mCheckedForSetup;
670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700672 * The time at which we will allow normal application switches again,
673 * after a call to {@link #stopAppSwitches()}.
674 */
675 long mAppSwitchesAllowedTime;
676
677 /**
678 * This is set to true after the first switch after mAppSwitchesAllowedTime
679 * is set; any switches after that will clear the time.
680 */
681 boolean mDidAppSwitch;
682
683 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700684 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700685 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 long mLastPowerCheckRealtime;
687
688 /**
689 * Last time (in uptime) at which we checked for power usage.
690 */
691 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692
693 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800694 * Set while we are wanting to sleep, to prevent any
695 * activities from being started/resumed.
696 */
697 boolean mSleeping = false;
698
699 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700700 * Set if we are shutting down the system, similar to sleeping.
701 */
702 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703
704 /**
705 * Task identifier that activities are currently being started
706 * in. Incremented each time a new task is created.
707 * todo: Replace this with a TokenSpace class that generates non-repeating
708 * integers that won't wrap.
709 */
710 int mCurTask = 1;
711
712 /**
713 * Current sequence id for oom_adj computation traversal.
714 */
715 int mAdjSeq = 0;
716
717 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700718 * Current sequence id for process LRU updating.
719 */
720 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721
722 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700723 * Keep track of the number of service processes we last found, to
724 * determine on the next iteration which should be B services.
725 */
726 int mNumServiceProcs = 0;
727 int mNewNumServiceProcs = 0;
728
729 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 * System monitoring: number of processes that died since the last
731 * N procs were started.
732 */
733 int[] mProcDeaths = new int[20];
734
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700735 /**
736 * This is set if we had to do a delayed dexopt of an app before launching
737 * it, to increasing the ANR timeouts in that case.
738 */
739 boolean mDidDexOpt;
740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 String mDebugApp = null;
742 boolean mWaitForDebugger = false;
743 boolean mDebugTransient = false;
744 String mOrigDebugApp = null;
745 boolean mOrigWaitForDebugger = false;
746 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700747 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700748 String mProfileApp = null;
749 ProcessRecord mProfileProc = null;
750 String mProfileFile;
751 ParcelFileDescriptor mProfileFd;
752 int mProfileType = 0;
753 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800754 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755
Jeff Sharkeya4620792011-05-20 15:29:23 -0700756 final RemoteCallbackList<IProcessObserver> mProcessObservers
757 = new RemoteCallbackList<IProcessObserver>();
758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 /**
760 * Callback of last caller to {@link #requestPss}.
761 */
762 Runnable mRequestPssCallback;
763
764 /**
765 * Remaining processes for which we are waiting results from the last
766 * call to {@link #requestPss}.
767 */
768 final ArrayList<ProcessRecord> mRequestPssList
769 = new ArrayList<ProcessRecord>();
770
771 /**
772 * Runtime statistics collection thread. This object's lock is used to
773 * protect all related state.
774 */
775 final Thread mProcessStatsThread;
776
777 /**
778 * Used to collect process stats when showing not responding dialog.
779 * Protected by mProcessStatsThread.
780 */
781 final ProcessStats mProcessStats = new ProcessStats(
782 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700783 final AtomicLong mLastCpuTime = new AtomicLong(0);
784 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 long mLastWriteTime = 0;
787
788 /**
789 * Set to true after the system has finished booting.
790 */
791 boolean mBooted = false;
792
Dianne Hackborn7d608422011-08-07 16:24:18 -0700793 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700794 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800795
796 WindowManagerService mWindowManager;
797
798 static ActivityManagerService mSelf;
799 static ActivityThread mSystemThread;
800
801 private final class AppDeathRecipient implements IBinder.DeathRecipient {
802 final ProcessRecord mApp;
803 final int mPid;
804 final IApplicationThread mAppThread;
805
806 AppDeathRecipient(ProcessRecord app, int pid,
807 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800808 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 TAG, "New death recipient " + this
810 + " for thread " + thread.asBinder());
811 mApp = app;
812 mPid = pid;
813 mAppThread = thread;
814 }
815
816 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800817 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 TAG, "Death received in " + this
819 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 synchronized(ActivityManagerService.this) {
821 appDiedLocked(mApp, mPid, mAppThread);
822 }
823 }
824 }
825
826 static final int SHOW_ERROR_MSG = 1;
827 static final int SHOW_NOT_RESPONDING_MSG = 2;
828 static final int SHOW_FACTORY_ERROR_MSG = 3;
829 static final int UPDATE_CONFIGURATION_MSG = 4;
830 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
831 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 static final int SERVICE_TIMEOUT_MSG = 12;
833 static final int UPDATE_TIME_ZONE = 13;
834 static final int SHOW_UID_ERROR_MSG = 14;
835 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700837 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700838 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800839 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700840 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
841 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700842 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700843 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700844 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700845 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700846 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700847 static final int DISPATCH_FOREGROUND_ACTIVITIES_CHANGED = 31;
848 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700849 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800851 static final int FIRST_ACTIVITY_STACK_MSG = 100;
852 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
853 static final int FIRST_COMPAT_MODE_MSG = 300;
854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700856 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700857 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858
859 final Handler mHandler = new Handler() {
860 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800861 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 //}
863
864 public void handleMessage(Message msg) {
865 switch (msg.what) {
866 case SHOW_ERROR_MSG: {
867 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 synchronized (ActivityManagerService.this) {
869 ProcessRecord proc = (ProcessRecord)data.get("app");
870 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800871 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 return;
873 }
874 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700875 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800876 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 d.show();
878 proc.crashDialog = d;
879 } else {
880 // The device is asleep, so just pretend that the user
881 // saw a crash dialog and hit "force quit".
882 res.set(0);
883 }
884 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700885
886 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 } break;
888 case SHOW_NOT_RESPONDING_MSG: {
889 synchronized (ActivityManagerService.this) {
890 HashMap data = (HashMap) msg.obj;
891 ProcessRecord proc = (ProcessRecord)data.get("app");
892 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800893 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 return;
895 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800896
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700897 Intent intent = new Intent("android.intent.action.ANR");
898 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800899 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
900 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700901 }
902 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800903 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700904 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800906 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700907 mContext, proc, (ActivityRecord)data.get("activity"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 d.show();
909 proc.anrDialog = d;
910 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700911
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700912 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700914 case SHOW_STRICT_MODE_VIOLATION_MSG: {
915 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
916 synchronized (ActivityManagerService.this) {
917 ProcessRecord proc = (ProcessRecord) data.get("app");
918 if (proc == null) {
919 Slog.e(TAG, "App not found when showing strict mode dialog.");
920 break;
921 }
922 if (proc.crashDialog != null) {
923 Slog.e(TAG, "App already has strict mode dialog: " + proc);
924 return;
925 }
926 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700927 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700928 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
929 d.show();
930 proc.crashDialog = d;
931 } else {
932 // The device is asleep, so just pretend that the user
933 // saw a crash dialog and hit "force quit".
934 res.set(0);
935 }
936 }
937 ensureBootCompleted();
938 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800939 case SHOW_FACTORY_ERROR_MSG: {
940 Dialog d = new FactoryErrorDialog(
941 mContext, msg.getData().getCharSequence("msg"));
942 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700943 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 } break;
945 case UPDATE_CONFIGURATION_MSG: {
946 final ContentResolver resolver = mContext.getContentResolver();
947 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
948 } break;
949 case GC_BACKGROUND_PROCESSES_MSG: {
950 synchronized (ActivityManagerService.this) {
951 performAppGcsIfAppropriateLocked();
952 }
953 } break;
954 case WAIT_FOR_DEBUGGER_MSG: {
955 synchronized (ActivityManagerService.this) {
956 ProcessRecord app = (ProcessRecord)msg.obj;
957 if (msg.arg1 != 0) {
958 if (!app.waitedForDebugger) {
959 Dialog d = new AppWaitingForDebuggerDialog(
960 ActivityManagerService.this,
961 mContext, app);
962 app.waitDialog = d;
963 app.waitedForDebugger = true;
964 d.show();
965 }
966 } else {
967 if (app.waitDialog != null) {
968 app.waitDialog.dismiss();
969 app.waitDialog = null;
970 }
971 }
972 }
973 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700975 if (mDidDexOpt) {
976 mDidDexOpt = false;
977 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
978 nmsg.obj = msg.obj;
979 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
980 return;
981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 serviceTimeout((ProcessRecord)msg.obj);
983 } break;
984 case UPDATE_TIME_ZONE: {
985 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800986 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
987 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 if (r.thread != null) {
989 try {
990 r.thread.updateTimeZone();
991 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800992 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994 }
995 }
996 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700997 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700998 case CLEAR_DNS_CACHE: {
999 synchronized (ActivityManagerService.this) {
1000 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1001 ProcessRecord r = mLruProcesses.get(i);
1002 if (r.thread != null) {
1003 try {
1004 r.thread.clearDnsCache();
1005 } catch (RemoteException ex) {
1006 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1007 }
1008 }
1009 }
1010 }
1011 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001012 case UPDATE_HTTP_PROXY: {
1013 ProxyProperties proxy = (ProxyProperties)msg.obj;
1014 String host = "";
1015 String port = "";
1016 String exclList = "";
1017 if (proxy != null) {
1018 host = proxy.getHost();
1019 port = Integer.toString(proxy.getPort());
1020 exclList = proxy.getExclusionList();
1021 }
1022 synchronized (ActivityManagerService.this) {
1023 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1024 ProcessRecord r = mLruProcesses.get(i);
1025 if (r.thread != null) {
1026 try {
1027 r.thread.setHttpProxy(host, port, exclList);
1028 } catch (RemoteException ex) {
1029 Slog.w(TAG, "Failed to update http proxy for: " +
1030 r.info.processName);
1031 }
1032 }
1033 }
1034 }
1035 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001037 String title = "System UIDs Inconsistent";
1038 String text = "UIDs on the system are inconsistent, you need to wipe your"
1039 + " data partition or your device will be unstable.";
1040 Log.e(TAG, title + ": " + text);
1041 if (mShowDialogs) {
1042 // XXX This is a temporary dialog, no need to localize.
1043 AlertDialog d = new BaseErrorDialog(mContext);
1044 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1045 d.setCancelable(false);
1046 d.setTitle(title);
1047 d.setMessage(text);
1048 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1049 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1050 mUidAlert = d;
1051 d.show();
1052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 } break;
1054 case IM_FEELING_LUCKY_MSG: {
1055 if (mUidAlert != null) {
1056 mUidAlert.dismiss();
1057 mUidAlert = null;
1058 }
1059 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001061 if (mDidDexOpt) {
1062 mDidDexOpt = false;
1063 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1064 nmsg.obj = msg.obj;
1065 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1066 return;
1067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 ProcessRecord app = (ProcessRecord)msg.obj;
1069 synchronized (ActivityManagerService.this) {
1070 processStartTimedOutLocked(app);
1071 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001072 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001073 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1074 synchronized (ActivityManagerService.this) {
1075 doPendingActivityLaunchesLocked(true);
1076 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001077 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001078 case KILL_APPLICATION_MSG: {
1079 synchronized (ActivityManagerService.this) {
1080 int uid = msg.arg1;
1081 boolean restart = (msg.arg2 == 1);
1082 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001083 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1084 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001085 }
1086 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001087 case FINALIZE_PENDING_INTENT_MSG: {
1088 ((PendingIntentRecord)msg.obj).completeFinalize();
1089 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001090 case POST_HEAVY_NOTIFICATION_MSG: {
1091 INotificationManager inm = NotificationManager.getService();
1092 if (inm == null) {
1093 return;
1094 }
1095
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001096 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001097 ProcessRecord process = root.app;
1098 if (process == null) {
1099 return;
1100 }
1101
1102 try {
1103 Context context = mContext.createPackageContext(process.info.packageName, 0);
1104 String text = mContext.getString(R.string.heavy_weight_notification,
1105 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1106 Notification notification = new Notification();
1107 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1108 notification.when = 0;
1109 notification.flags = Notification.FLAG_ONGOING_EVENT;
1110 notification.tickerText = text;
1111 notification.defaults = 0; // please be quiet
1112 notification.sound = null;
1113 notification.vibrate = null;
1114 notification.setLatestEventInfo(context, text,
1115 mContext.getText(R.string.heavy_weight_notification_detail),
1116 PendingIntent.getActivity(mContext, 0, root.intent,
1117 PendingIntent.FLAG_CANCEL_CURRENT));
1118
1119 try {
1120 int[] outId = new int[1];
1121 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1122 notification, outId);
1123 } catch (RuntimeException e) {
1124 Slog.w(ActivityManagerService.TAG,
1125 "Error showing notification for heavy-weight app", e);
1126 } catch (RemoteException e) {
1127 }
1128 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001129 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001130 }
1131 } break;
1132 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1133 INotificationManager inm = NotificationManager.getService();
1134 if (inm == null) {
1135 return;
1136 }
1137 try {
1138 inm.cancelNotification("android",
1139 R.string.heavy_weight_notification);
1140 } catch (RuntimeException e) {
1141 Slog.w(ActivityManagerService.TAG,
1142 "Error canceling notification for service", e);
1143 } catch (RemoteException e) {
1144 }
1145 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001146 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1147 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001148 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001149 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001150 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1151 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001152 }
1153 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001154 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1155 synchronized (ActivityManagerService.this) {
1156 ActivityRecord ar = (ActivityRecord)msg.obj;
1157 if (mCompatModeDialog != null) {
1158 if (mCompatModeDialog.mAppInfo.packageName.equals(
1159 ar.info.applicationInfo.packageName)) {
1160 return;
1161 }
1162 mCompatModeDialog.dismiss();
1163 mCompatModeDialog = null;
1164 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001165 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001166 if (mCompatModePackages.getPackageAskCompatModeLocked(
1167 ar.packageName)) {
1168 int mode = mCompatModePackages.computeCompatModeLocked(
1169 ar.info.applicationInfo);
1170 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1171 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1172 mCompatModeDialog = new CompatModeDialog(
1173 ActivityManagerService.this, mContext,
1174 ar.info.applicationInfo);
1175 mCompatModeDialog.show();
1176 }
1177 }
1178 }
1179 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001180 break;
1181 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001182 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001183 final int pid = msg.arg1;
1184 final int uid = msg.arg2;
1185 final boolean foregroundActivities = (Boolean) msg.obj;
1186 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 break;
1188 }
1189 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001190 final int pid = msg.arg1;
1191 final int uid = msg.arg2;
1192 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001193 break;
1194 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001195 case REPORT_MEM_USAGE: {
1196 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1197 if (!isDebuggable) {
1198 return;
1199 }
1200 synchronized (ActivityManagerService.this) {
1201 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001202 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1203 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001204 // avoid spamming.
1205 return;
1206 }
1207 mLastMemUsageReportTime = now;
1208 }
1209 Thread thread = new Thread() {
1210 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001211 StringBuilder dropBuilder = new StringBuilder(1024);
1212 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001213 StringWriter oomSw = new StringWriter();
1214 PrintWriter oomPw = new PrintWriter(oomSw);
1215 StringWriter catSw = new StringWriter();
1216 PrintWriter catPw = new PrintWriter(catSw);
1217 String[] emptyArgs = new String[] { };
1218 StringBuilder tag = new StringBuilder(128);
1219 StringBuilder stack = new StringBuilder(128);
1220 tag.append("Low on memory -- ");
1221 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1222 tag, stack);
1223 dropBuilder.append(stack);
1224 dropBuilder.append('\n');
1225 dropBuilder.append('\n');
1226 String oomString = oomSw.toString();
1227 dropBuilder.append(oomString);
1228 dropBuilder.append('\n');
1229 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001230 try {
1231 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1232 "procrank", });
1233 final InputStreamReader converter = new InputStreamReader(
1234 proc.getInputStream());
1235 BufferedReader in = new BufferedReader(converter);
1236 String line;
1237 while (true) {
1238 line = in.readLine();
1239 if (line == null) {
1240 break;
1241 }
1242 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001243 logBuilder.append(line);
1244 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001246 dropBuilder.append(line);
1247 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001248 }
1249 converter.close();
1250 } catch (IOException e) {
1251 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001252 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001253 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001254 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001255 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001256 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001257 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001258 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001259 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001260 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001261 addErrorToDropBox("lowmem", null, "system_server", null,
1262 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001263 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001264 synchronized (ActivityManagerService.this) {
1265 long now = SystemClock.uptimeMillis();
1266 if (mLastMemUsageReportTime < now) {
1267 mLastMemUsageReportTime = now;
1268 }
1269 }
1270 }
1271 };
1272 thread.start();
1273 break;
1274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
1276 }
1277 };
1278
1279 public static void setSystemProcess() {
1280 try {
1281 ActivityManagerService m = mSelf;
1282
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001283 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001285 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001286 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 if (MONITOR_CPU_USAGE) {
1288 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 ServiceManager.addService("permission", new PermissionController(m));
1291
1292 ApplicationInfo info =
1293 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001294 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001295 mSystemThread.installSystemApplicationInfo(info);
1296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 synchronized (mSelf) {
1298 ProcessRecord app = mSelf.newProcessRecordLocked(
1299 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001300 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001302 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001303 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001304 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 synchronized (mSelf.mPidsSelfLocked) {
1306 mSelf.mPidsSelfLocked.put(app.pid, app);
1307 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001308 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 }
1310 } catch (PackageManager.NameNotFoundException e) {
1311 throw new RuntimeException(
1312 "Unable to find android system package", e);
1313 }
1314 }
1315
1316 public void setWindowManager(WindowManagerService wm) {
1317 mWindowManager = wm;
1318 }
1319
1320 public static final Context main(int factoryTest) {
1321 AThread thr = new AThread();
1322 thr.start();
1323
1324 synchronized (thr) {
1325 while (thr.mService == null) {
1326 try {
1327 thr.wait();
1328 } catch (InterruptedException e) {
1329 }
1330 }
1331 }
1332
1333 ActivityManagerService m = thr.mService;
1334 mSelf = m;
1335 ActivityThread at = ActivityThread.systemMain();
1336 mSystemThread = at;
1337 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001338 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 m.mContext = context;
1340 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001341 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342
1343 m.mBatteryStatsService.publish(context);
1344 m.mUsageStatsService.publish(context);
1345
1346 synchronized (thr) {
1347 thr.mReady = true;
1348 thr.notifyAll();
1349 }
1350
1351 m.startRunning(null, null, null, null);
1352
1353 return context;
1354 }
1355
1356 public static ActivityManagerService self() {
1357 return mSelf;
1358 }
1359
1360 static class AThread extends Thread {
1361 ActivityManagerService mService;
1362 boolean mReady = false;
1363
1364 public AThread() {
1365 super("ActivityManager");
1366 }
1367
1368 public void run() {
1369 Looper.prepare();
1370
1371 android.os.Process.setThreadPriority(
1372 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001373 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374
1375 ActivityManagerService m = new ActivityManagerService();
1376
1377 synchronized (this) {
1378 mService = m;
1379 notifyAll();
1380 }
1381
1382 synchronized (this) {
1383 while (!mReady) {
1384 try {
1385 wait();
1386 } catch (InterruptedException e) {
1387 }
1388 }
1389 }
1390
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001391 // For debug builds, log event loop stalls to dropbox for analysis.
1392 if (StrictMode.conditionallyEnableDebugLogging()) {
1393 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1394 }
1395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 Looper.loop();
1397 }
1398 }
1399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 static class MemBinder extends Binder {
1401 ActivityManagerService mActivityManagerService;
1402 MemBinder(ActivityManagerService activityManagerService) {
1403 mActivityManagerService = activityManagerService;
1404 }
1405
1406 @Override
1407 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001408 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1409 != PackageManager.PERMISSION_GRANTED) {
1410 pw.println("Permission Denial: can't dump meminfo from from pid="
1411 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1412 + " without permission " + android.Manifest.permission.DUMP);
1413 return;
1414 }
1415
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001416 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001417 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 }
1420
Chet Haase9c1e23b2011-03-24 10:51:31 -07001421 static class GraphicsBinder extends Binder {
1422 ActivityManagerService mActivityManagerService;
1423 GraphicsBinder(ActivityManagerService activityManagerService) {
1424 mActivityManagerService = activityManagerService;
1425 }
1426
1427 @Override
1428 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001429 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1430 != PackageManager.PERMISSION_GRANTED) {
1431 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1432 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1433 + " without permission " + android.Manifest.permission.DUMP);
1434 return;
1435 }
1436
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001437 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001438 }
1439 }
1440
Jeff Brown6754ba22011-12-14 20:20:01 -08001441 static class DbBinder extends Binder {
1442 ActivityManagerService mActivityManagerService;
1443 DbBinder(ActivityManagerService activityManagerService) {
1444 mActivityManagerService = activityManagerService;
1445 }
1446
1447 @Override
1448 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1449 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1450 != PackageManager.PERMISSION_GRANTED) {
1451 pw.println("Permission Denial: can't dump dbinfo from from pid="
1452 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1453 + " without permission " + android.Manifest.permission.DUMP);
1454 return;
1455 }
1456
1457 mActivityManagerService.dumpDbInfo(fd, pw, args);
1458 }
1459 }
1460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 static class CpuBinder extends Binder {
1462 ActivityManagerService mActivityManagerService;
1463 CpuBinder(ActivityManagerService activityManagerService) {
1464 mActivityManagerService = activityManagerService;
1465 }
1466
1467 @Override
1468 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001469 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1470 != PackageManager.PERMISSION_GRANTED) {
1471 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1472 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1473 + " without permission " + android.Manifest.permission.DUMP);
1474 return;
1475 }
1476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001478 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1479 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1480 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
1482 }
1483 }
1484
1485 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001486 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001487
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001488 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1489 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1490 mBroadcastQueues[0] = mFgBroadcastQueue;
1491 mBroadcastQueues[1] = mBgBroadcastQueue;
1492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 File dataDir = Environment.getDataDirectory();
1494 File systemDir = new File(dataDir, "system");
1495 systemDir.mkdirs();
1496 mBatteryStatsService = new BatteryStatsService(new File(
1497 systemDir, "batterystats.bin").toString());
1498 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001499 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001500 mOnBattery = DEBUG_POWER ? true
1501 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001502 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001504 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001505 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001506 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507
Jack Palevichb90d28c2009-07-22 15:35:24 -07001508 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1509 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1510
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001511 mConfiguration.setToDefaults();
1512 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001513 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 mProcessStats.init();
1515
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001516 mCompatModePackages = new CompatModePackages(this, systemDir);
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 // Add ourself to the Watchdog monitors.
1519 Watchdog.getInstance().addMonitor(this);
1520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 mProcessStatsThread = new Thread("ProcessStats") {
1522 public void run() {
1523 while (true) {
1524 try {
1525 try {
1526 synchronized(this) {
1527 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001528 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001530 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 // + ", write delay=" + nextWriteDelay);
1532 if (nextWriteDelay < nextCpuDelay) {
1533 nextCpuDelay = nextWriteDelay;
1534 }
1535 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001536 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 this.wait(nextCpuDelay);
1538 }
1539 }
1540 } catch (InterruptedException e) {
1541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 updateCpuStatsNow();
1543 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001544 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 };
1549 mProcessStatsThread.start();
1550 }
1551
1552 @Override
1553 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1554 throws RemoteException {
1555 try {
1556 return super.onTransact(code, data, reply, flags);
1557 } catch (RuntimeException e) {
1558 // The activity manager only throws security exceptions, so let's
1559 // log all others.
1560 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001561 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 }
1563 throw e;
1564 }
1565 }
1566
1567 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001568 final long now = SystemClock.uptimeMillis();
1569 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1570 return;
1571 }
1572 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1573 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001574 mProcessStatsThread.notify();
1575 }
1576 }
1577 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 void updateCpuStatsNow() {
1580 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001581 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 final long now = SystemClock.uptimeMillis();
1583 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001586 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1587 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 haveNewCpuStats = true;
1589 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001590 //Slog.i(TAG, mProcessStats.printCurrentState());
1591 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 // + mProcessStats.getTotalCpuPercent() + "%");
1593
Joe Onorato8a9b2202010-02-26 18:56:32 -08001594 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if ("true".equals(SystemProperties.get("events.cpu"))) {
1596 int user = mProcessStats.getLastUserTime();
1597 int system = mProcessStats.getLastSystemTime();
1598 int iowait = mProcessStats.getLastIoWaitTime();
1599 int irq = mProcessStats.getLastIrqTime();
1600 int softIrq = mProcessStats.getLastSoftIrqTime();
1601 int idle = mProcessStats.getLastIdleTime();
1602
1603 int total = user + system + iowait + irq + softIrq + idle;
1604 if (total == 0) total = 1;
1605
Doug Zongker2bec3d42009-12-04 12:52:44 -08001606 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 ((user+system+iowait+irq+softIrq) * 100) / total,
1608 (user * 100) / total,
1609 (system * 100) / total,
1610 (iowait * 100) / total,
1611 (irq * 100) / total,
1612 (softIrq * 100) / total);
1613 }
1614 }
1615
Amith Yamasanie43530a2009-08-21 13:11:37 -07001616 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001617 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001618 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 synchronized(mPidsSelfLocked) {
1620 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001621 if (mOnBattery) {
1622 int perc = bstats.startAddingCpuLocked();
1623 int totalUTime = 0;
1624 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001625 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001627 ProcessStats.Stats st = mProcessStats.getStats(i);
1628 if (!st.working) {
1629 continue;
1630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001632 int otherUTime = (st.rel_utime*perc)/100;
1633 int otherSTime = (st.rel_stime*perc)/100;
1634 totalUTime += otherUTime;
1635 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 if (pr != null) {
1637 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001638 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1639 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001640 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001641 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001642 } else {
1643 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001644 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001645 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001646 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1647 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001648 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001652 bstats.finishAddingCpuLocked(perc, totalUTime,
1653 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
1655 }
1656 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1659 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001660 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001661 }
1662 }
1663 }
1664 }
1665
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001666 @Override
1667 public void batteryNeedsCpuUpdate() {
1668 updateCpuStatsNow();
1669 }
1670
1671 @Override
1672 public void batteryPowerChanged(boolean onBattery) {
1673 // When plugging in, update the CPU stats first before changing
1674 // the plug state.
1675 updateCpuStatsNow();
1676 synchronized (this) {
1677 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001678 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001679 }
1680 }
1681 }
1682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 /**
1684 * Initialize the application bind args. These are passed to each
1685 * process when the bindApplication() IPC is sent to the process. They're
1686 * lazily setup to make sure the services are running when they're asked for.
1687 */
1688 private HashMap<String, IBinder> getCommonServicesLocked() {
1689 if (mAppBindArgs == null) {
1690 mAppBindArgs = new HashMap<String, IBinder>();
1691
1692 // Setup the application init args
1693 mAppBindArgs.put("package", ServiceManager.getService("package"));
1694 mAppBindArgs.put("window", ServiceManager.getService("window"));
1695 mAppBindArgs.put(Context.ALARM_SERVICE,
1696 ServiceManager.getService(Context.ALARM_SERVICE));
1697 }
1698 return mAppBindArgs;
1699 }
1700
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001701 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if (mFocusedActivity != r) {
1703 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001704 if (r != null) {
1705 mWindowManager.setFocusedApp(r.appToken, true);
1706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709
Dianne Hackborn906497c2010-05-10 15:57:38 -07001710 private final void updateLruProcessInternalLocked(ProcessRecord app,
1711 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001713 int lrui = mLruProcesses.indexOf(app);
1714 if (lrui >= 0) mLruProcesses.remove(lrui);
1715
1716 int i = mLruProcesses.size()-1;
1717 int skipTop = 0;
1718
Dianne Hackborn906497c2010-05-10 15:57:38 -07001719 app.lruSeq = mLruSeq;
1720
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001721 // compute the new weight for this process.
1722 if (updateActivityTime) {
1723 app.lastActivityTime = SystemClock.uptimeMillis();
1724 }
1725 if (app.activities.size() > 0) {
1726 // If this process has activities, we more strongly want to keep
1727 // it around.
1728 app.lruWeight = app.lastActivityTime;
1729 } else if (app.pubProviders.size() > 0) {
1730 // If this process contains content providers, we want to keep
1731 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001732 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001733 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001734 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001735 } else {
1736 // If this process doesn't have activities, we less strongly
1737 // want to keep it around, and generally want to avoid getting
1738 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001739 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001741 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001742 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001743
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001744 while (i >= 0) {
1745 ProcessRecord p = mLruProcesses.get(i);
1746 // If this app shouldn't be in front of the first N background
1747 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001748 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001749 skipTop--;
1750 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001751 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001752 mLruProcesses.add(i+1, app);
1753 break;
1754 }
1755 i--;
1756 }
1757 if (i < 0) {
1758 mLruProcesses.add(0, app);
1759 }
1760
Dianne Hackborn906497c2010-05-10 15:57:38 -07001761 // If the app is currently using a content provider or service,
1762 // bump those processes as well.
1763 if (app.connections.size() > 0) {
1764 for (ConnectionRecord cr : app.connections) {
1765 if (cr.binding != null && cr.binding.service != null
1766 && cr.binding.service.app != null
1767 && cr.binding.service.app.lruSeq != mLruSeq) {
1768 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1769 updateActivityTime, i+1);
1770 }
1771 }
1772 }
1773 if (app.conProviders.size() > 0) {
1774 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001775 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1776 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001777 updateActivityTime, i+1);
1778 }
1779 }
1780 }
1781
Joe Onorato8a9b2202010-02-26 18:56:32 -08001782 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001783 if (oomAdj) {
1784 updateOomAdjLocked();
1785 }
1786 }
1787
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001789 boolean oomAdj, boolean updateActivityTime) {
1790 mLruSeq++;
1791 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1792 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001793
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001794 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 String processName, int uid) {
1796 if (uid == Process.SYSTEM_UID) {
1797 // The system gets to run in any process. If there are multiple
1798 // processes with the same uid, just pick the first (this
1799 // should never happen).
1800 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1801 processName);
1802 return procs != null ? procs.valueAt(0) : null;
1803 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001804 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 ProcessRecord proc = mProcessNames.get(processName, uid);
1806 return proc;
1807 }
1808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001810 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001811 try {
1812 if (pm.performDexOpt(packageName)) {
1813 mDidDexOpt = true;
1814 }
1815 } catch (RemoteException e) {
1816 }
1817 }
1818
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 int transit = mWindowManager.getPendingAppTransition();
1821 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1822 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1823 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1824 }
1825
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001826 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001828 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1829 boolean isolated) {
1830 ProcessRecord app;
1831 if (!isolated) {
1832 app = getProcessRecordLocked(processName, info.uid);
1833 } else {
1834 // If this is an isolated process, it can't re-use an existing process.
1835 app = null;
1836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 // We don't have to do anything more if:
1838 // (1) There is an existing application record; and
1839 // (2) The caller doesn't think it is dead, OR there is no thread
1840 // object attached to it so we know it couldn't have crashed; and
1841 // (3) There is a pid assigned to it, so it is either starting or
1842 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001843 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 + " app=" + app + " knownToBeDead=" + knownToBeDead
1845 + " thread=" + (app != null ? app.thread : null)
1846 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001847 if (app != null && app.pid > 0) {
1848 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001849 // We already have the app running, or are waiting for it to
1850 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001851 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001852 // If this is a new package in the process, add the package to the list
1853 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001854 return app;
1855 } else {
1856 // An application record is attached to a previous process,
1857 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001858 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001859 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 String hostingNameStr = hostingName != null
1864 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001865
1866 if (!isolated) {
1867 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1868 // If we are in the background, then check to see if this process
1869 // is bad. If so, we will just silently fail.
1870 if (mBadProcesses.get(info.processName, info.uid) != null) {
1871 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1872 + "/" + info.processName);
1873 return null;
1874 }
1875 } else {
1876 // When the user is explicitly starting a process, then clear its
1877 // crash count so that we won't make it bad until they see at
1878 // least one crash dialog again, and make the process good again
1879 // if it had been bad.
1880 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001881 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001882 mProcessCrashTimes.remove(info.processName, info.uid);
1883 if (mBadProcesses.get(info.processName, info.uid) != null) {
1884 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1885 info.processName);
1886 mBadProcesses.remove(info.processName, info.uid);
1887 if (app != null) {
1888 app.bad = false;
1889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891 }
1892 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001895 app = newProcessRecordLocked(null, info, processName, isolated);
1896 if (app == null) {
1897 Slog.w(TAG, "Failed making new process record for "
1898 + processName + "/" + info.uid + " isolated=" + isolated);
1899 return null;
1900 }
1901 mProcessNames.put(processName, app.uid, app);
1902 if (isolated) {
1903 mIsolatedProcesses.put(app.uid, app);
1904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 } else {
1906 // If this is a new package in the process, add the package to the list
1907 app.addPackage(info.packageName);
1908 }
1909
1910 // If the system is not ready yet, then hold off on starting this
1911 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001912 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001913 && !isAllowedWhileBooting(info)
1914 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 if (!mProcessesOnHold.contains(app)) {
1916 mProcessesOnHold.add(app);
1917 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001918 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001919 return app;
1920 }
1921
1922 startProcessLocked(app, hostingType, hostingNameStr);
1923 return (app.pid != 0) ? app : null;
1924 }
1925
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001926 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1927 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1928 }
1929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 private final void startProcessLocked(ProcessRecord app,
1931 String hostingType, String hostingNameStr) {
1932 if (app.pid > 0 && app.pid != MY_PID) {
1933 synchronized (mPidsSelfLocked) {
1934 mPidsSelfLocked.remove(app.pid);
1935 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1936 }
1937 app.pid = 0;
1938 }
1939
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001940 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1941 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 mProcessesOnHold.remove(app);
1943
1944 updateCpuStats();
1945
1946 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1947 mProcDeaths[0] = 0;
1948
1949 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001950 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001953 if (!app.isolated) {
1954 try {
1955 gids = mContext.getPackageManager().getPackageGids(
1956 app.info.packageName);
1957 } catch (PackageManager.NameNotFoundException e) {
1958 Slog.w(TAG, "Unable to retrieve gids", e);
1959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1962 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1963 && mTopComponent != null
1964 && app.processName.equals(mTopComponent.getPackageName())) {
1965 uid = 0;
1966 }
1967 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1968 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1969 uid = 0;
1970 }
1971 }
1972 int debugFlags = 0;
1973 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1974 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001975 // Also turn on CheckJNI for debuggable apps. It's quite
1976 // awkward to turn on otherwise.
1977 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001979 // Run the app in safe mode if its manifest requests so or the
1980 // system is booted in safe mode.
1981 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1982 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001983 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1986 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1987 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001988 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1989 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if ("1".equals(SystemProperties.get("debug.assert"))) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1993 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07001994
1995 // Start the process. It will either succeed and return a result containing
1996 // the PID of the new process, or else throw a RuntimeException.
1997 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07001998 app.processName, uid, uid, gids, debugFlags,
1999 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2002 synchronized (bs) {
2003 if (bs.isOnBattery()) {
2004 app.batteryStats.incStartsLocked();
2005 }
2006 }
2007
Jeff Brown3f9dd282011-07-08 20:02:19 -07002008 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 app.processName, hostingType,
2010 hostingNameStr != null ? hostingNameStr : "");
2011
2012 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002013 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 }
2015
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002016 StringBuilder buf = mStringBuilder;
2017 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002018 buf.append("Start proc ");
2019 buf.append(app.processName);
2020 buf.append(" for ");
2021 buf.append(hostingType);
2022 if (hostingNameStr != null) {
2023 buf.append(" ");
2024 buf.append(hostingNameStr);
2025 }
2026 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002027 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 buf.append(" uid=");
2029 buf.append(uid);
2030 buf.append(" gids={");
2031 if (gids != null) {
2032 for (int gi=0; gi<gids.length; gi++) {
2033 if (gi != 0) buf.append(", ");
2034 buf.append(gids[gi]);
2035
2036 }
2037 }
2038 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002039 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002040 app.pid = startResult.pid;
2041 app.usingWrapper = startResult.usingWrapper;
2042 app.removed = false;
2043 synchronized (mPidsSelfLocked) {
2044 this.mPidsSelfLocked.put(startResult.pid, app);
2045 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2046 msg.obj = app;
2047 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2048 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 }
2050 } catch (RuntimeException e) {
2051 // XXX do better error recovery.
2052 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002053 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 }
2055 }
2056
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 if (resumed) {
2059 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2060 } else {
2061 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2062 }
2063 }
2064
Amith Yamasani742a6712011-05-04 14:49:28 -07002065 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002066 if (mHeadless) {
2067 // Added because none of the other calls to ensureBootCompleted seem to fire
2068 // when running headless.
2069 ensureBootCompleted();
2070 return false;
2071 }
2072
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002073 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2074 && mTopAction == null) {
2075 // We are running in factory test mode, but unable to find
2076 // the factory test app, so just sit around displaying the
2077 // error message and don't try to start anything.
2078 return false;
2079 }
2080 Intent intent = new Intent(
2081 mTopAction,
2082 mTopData != null ? Uri.parse(mTopData) : null);
2083 intent.setComponent(mTopComponent);
2084 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2085 intent.addCategory(Intent.CATEGORY_HOME);
2086 }
2087 ActivityInfo aInfo =
2088 intent.resolveActivityInfo(mContext.getPackageManager(),
2089 STOCK_PM_FLAGS);
2090 if (aInfo != null) {
2091 intent.setComponent(new ComponentName(
2092 aInfo.applicationInfo.packageName, aInfo.name));
2093 // Don't do this if the home app is currently being
2094 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002095 aInfo = new ActivityInfo(aInfo);
2096 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002097 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2098 aInfo.applicationInfo.uid);
2099 if (app == null || app.instrumentationClass == null) {
2100 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002101 mMainStack.startActivityLocked(null, intent, null, aInfo,
2102 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 }
2104 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002105
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002106 return true;
2107 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002108
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002109 /**
2110 * Starts the "new version setup screen" if appropriate.
2111 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002112 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002113 // Only do this once per boot.
2114 if (mCheckedForSetup) {
2115 return;
2116 }
2117
2118 // We will show this screen if the current one is a different
2119 // version than the last one shown, and we are not running in
2120 // low-level factory test mode.
2121 final ContentResolver resolver = mContext.getContentResolver();
2122 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2123 Settings.Secure.getInt(resolver,
2124 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2125 mCheckedForSetup = true;
2126
2127 // See if we should be showing the platform update setup UI.
2128 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2129 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2130 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2131
2132 // We don't allow third party apps to replace this.
2133 ResolveInfo ri = null;
2134 for (int i=0; ris != null && i<ris.size(); i++) {
2135 if ((ris.get(i).activityInfo.applicationInfo.flags
2136 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2137 ri = ris.get(i);
2138 break;
2139 }
2140 }
2141
2142 if (ri != null) {
2143 String vers = ri.activityInfo.metaData != null
2144 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2145 : null;
2146 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2147 vers = ri.activityInfo.applicationInfo.metaData.getString(
2148 Intent.METADATA_SETUP_VERSION);
2149 }
2150 String lastVers = Settings.Secure.getString(
2151 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2152 if (vers != null && !vers.equals(lastVers)) {
2153 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2154 intent.setComponent(new ComponentName(
2155 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002156 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2157 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002158 }
2159 }
2160 }
2161 }
2162
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002163 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002164 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002165 }
2166
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002167 void enforceNotIsolatedCaller(String caller) {
2168 if (UserId.isIsolated(Binder.getCallingUid())) {
2169 throw new SecurityException("Isolated process not allowed to call " + caller);
2170 }
2171 }
2172
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002173 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002174 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002175 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002176 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2177 }
2178 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002179
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002180 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002181 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2182 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002183 synchronized (this) {
2184 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2185 }
2186 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002187
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002188 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002189 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002190 synchronized (this) {
2191 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2192 }
2193 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002194
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002195 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002196 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2197 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002198 synchronized (this) {
2199 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002200 }
2201 }
2202
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002203 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002204 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002205 synchronized (this) {
2206 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2207 }
2208 }
2209
2210 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002211 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2212 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002213 synchronized (this) {
2214 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2215 }
2216 }
2217
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002218 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002219 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002220
2221 final int identHash = System.identityHashCode(r);
2222 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002224
Jeff Sharkeya4620792011-05-20 15:29:23 -07002225 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2226 int i = mProcessObservers.beginBroadcast();
2227 while (i > 0) {
2228 i--;
2229 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2230 if (observer != null) {
2231 try {
2232 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2233 } catch (RemoteException e) {
2234 }
2235 }
2236 }
2237 mProcessObservers.finishBroadcast();
2238 }
2239
2240 private void dispatchProcessDied(int pid, int uid) {
2241 int i = mProcessObservers.beginBroadcast();
2242 while (i > 0) {
2243 i--;
2244 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2245 if (observer != null) {
2246 try {
2247 observer.onProcessDied(pid, uid);
2248 } catch (RemoteException e) {
2249 }
2250 }
2251 }
2252 mProcessObservers.finishBroadcast();
2253 }
2254
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002255 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002256 final int N = mPendingActivityLaunches.size();
2257 if (N <= 0) {
2258 return;
2259 }
2260 for (int i=0; i<N; i++) {
2261 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002262 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002263 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002264 }
2265 mPendingActivityLaunches.clear();
2266 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002267
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002268 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002269 Intent intent, String resolvedType, IBinder resultTo,
2270 String resultWho, int requestCode, int startFlags,
2271 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002272 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002273 int userId = 0;
2274 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2275 // Requesting home, set the identity to the current user
2276 // HACK!
2277 userId = mCurrentUserId;
2278 } else {
2279 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2280 // the current user's userId
2281 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2282 userId = 0;
2283 } else {
2284 userId = Binder.getOrigCallingUser();
2285 }
2286 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002287 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002288 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2289 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002290 }
2291
2292 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002293 Intent intent, String resolvedType, IBinder resultTo,
2294 String resultWho, int requestCode, int startFlags, String profileFile,
2295 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002296 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002297 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002298 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002299 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002300 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2301 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002302 return res;
2303 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002304
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002305 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 Intent intent, String resolvedType, IBinder resultTo,
2307 String resultWho, int requestCode, int startFlags, Configuration config,
2308 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002309 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002310 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002311 resultTo, resultWho, requestCode, startFlags,
2312 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002313 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002314 }
2315
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002316 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002317 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002318 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002319 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002320 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002321 // Refuse possible leaked file descriptors
2322 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2323 throw new IllegalArgumentException("File descriptors passed in Intent");
2324 }
2325
2326 IIntentSender sender = intent.getTarget();
2327 if (!(sender instanceof PendingIntentRecord)) {
2328 throw new IllegalArgumentException("Bad PendingIntent object");
2329 }
2330
2331 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002332
2333 synchronized (this) {
2334 // If this is coming from the currently resumed activity, it is
2335 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 if (mMainStack.mResumedActivity != null
2337 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002338 Binder.getCallingUid()) {
2339 mAppSwitchesAllowedTime = 0;
2340 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002341 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002342 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2343 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002344 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002345 }
2346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002348 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 // Refuse possible leaked file descriptors
2350 if (intent != null && intent.hasFileDescriptors() == true) {
2351 throw new IllegalArgumentException("File descriptors passed in Intent");
2352 }
2353
2354 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002355 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2356 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002357 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 return false;
2359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 if (r.app == null || r.app.thread == null) {
2361 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002362 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 return false;
2364 }
2365 intent = new Intent(intent);
2366 // The caller is not allowed to change the data.
2367 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2368 // And we are resetting to find the next component...
2369 intent.setComponent(null);
2370
2371 ActivityInfo aInfo = null;
2372 try {
2373 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002374 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002376 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2377 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378
2379 // Look for the original activity in the list...
2380 final int N = resolves != null ? resolves.size() : 0;
2381 for (int i=0; i<N; i++) {
2382 ResolveInfo rInfo = resolves.get(i);
2383 if (rInfo.activityInfo.packageName.equals(r.packageName)
2384 && rInfo.activityInfo.name.equals(r.info.name)) {
2385 // We found the current one... the next matching is
2386 // after it.
2387 i++;
2388 if (i<N) {
2389 aInfo = resolves.get(i).activityInfo;
2390 }
2391 break;
2392 }
2393 }
2394 } catch (RemoteException e) {
2395 }
2396
2397 if (aInfo == null) {
2398 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002399 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 return false;
2401 }
2402
2403 intent.setComponent(new ComponentName(
2404 aInfo.applicationInfo.packageName, aInfo.name));
2405 intent.setFlags(intent.getFlags()&~(
2406 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2407 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2408 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2409 Intent.FLAG_ACTIVITY_NEW_TASK));
2410
2411 // Okay now we need to start the new activity, replacing the
2412 // currently running activity. This is a little tricky because
2413 // we want to start the new one as if the current one is finished,
2414 // but not finish the current one first so that there is no flicker.
2415 // And thus...
2416 final boolean wasFinishing = r.finishing;
2417 r.finishing = true;
2418
2419 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002420 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 final String resultWho = r.resultWho;
2422 final int requestCode = r.requestCode;
2423 r.resultTo = null;
2424 if (resultTo != null) {
2425 resultTo.removeResultsLocked(r, resultWho, requestCode);
2426 }
2427
2428 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002430 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2431 resultWho, requestCode, -1, r.launchedFromUid, 0,
2432 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 Binder.restoreCallingIdentity(origId);
2434
2435 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002436 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002437 return false;
2438 }
2439 return true;
2440 }
2441 }
2442
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002443 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002445 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002446
2447 // This is so super not safe, that only the system (or okay root)
2448 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002449 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002450 final int callingUid = Binder.getCallingUid();
2451 if (callingUid != 0 && callingUid != Process.myUid()) {
2452 throw new SecurityException(
2453 "startActivityInPackage only available to the system");
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455
Amith Yamasani742a6712011-05-04 14:49:28 -07002456 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002457 resultTo, resultWho, requestCode, startFlags,
2458 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002459 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002460 }
2461
2462 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002464 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002466 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002467 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002468 }
2469
2470 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002471 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2472 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002473
2474 // This is so super not safe, that only the system (or okay root)
2475 // can do it.
2476 final int callingUid = Binder.getCallingUid();
2477 if (callingUid != 0 && callingUid != Process.myUid()) {
2478 throw new SecurityException(
2479 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002481 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002482 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002483 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
2485
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002486 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002488 // Quick case: check if the top-most recent task is the same.
2489 if (N > 0 && mRecentTasks.get(0) == task) {
2490 return;
2491 }
2492 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 for (int i=0; i<N; i++) {
2494 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002495 if (task.userId == tr.userId
2496 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2497 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 mRecentTasks.remove(i);
2499 i--;
2500 N--;
2501 if (task.intent == null) {
2502 // If the new recent task we are adding is not fully
2503 // specified, then replace it with the existing recent task.
2504 task = tr;
2505 }
2506 }
2507 }
2508 if (N >= MAX_RECENT_TASKS) {
2509 mRecentTasks.remove(N-1);
2510 }
2511 mRecentTasks.add(0, task);
2512 }
2513
2514 public void setRequestedOrientation(IBinder token,
2515 int requestedOrientation) {
2516 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002517 ActivityRecord r = mMainStack.isInStackLocked(token);
2518 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 return;
2520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002522 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002524 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002525 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 if (config != null) {
2527 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002528 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 }
2531 }
2532 Binder.restoreCallingIdentity(origId);
2533 }
2534 }
2535
2536 public int getRequestedOrientation(IBinder token) {
2537 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002538 ActivityRecord r = mMainStack.isInStackLocked(token);
2539 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2541 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002542 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
2544 }
2545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 /**
2547 * This is the internal entry point for handling Activity.finish().
2548 *
2549 * @param token The Binder token referencing the Activity we want to finish.
2550 * @param resultCode Result code, if any, from this Activity.
2551 * @param resultData Result data (Intent), if any, from this Activity.
2552 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002553 * @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 -08002554 */
2555 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2556 // Refuse possible leaked file descriptors
2557 if (resultData != null && resultData.hasFileDescriptors() == true) {
2558 throw new IllegalArgumentException("File descriptors passed in Intent");
2559 }
2560
2561 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002562 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002564 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 if (next != null) {
2566 // ask watcher if this is allowed
2567 boolean resumeOK = true;
2568 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002569 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002571 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 }
2573
2574 if (!resumeOK) {
2575 return false;
2576 }
2577 }
2578 }
2579 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002580 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 resultData, "app-request");
2582 Binder.restoreCallingIdentity(origId);
2583 return res;
2584 }
2585 }
2586
Dianne Hackborn860755f2010-06-03 18:47:52 -07002587 public final void finishHeavyWeightApp() {
2588 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2589 != PackageManager.PERMISSION_GRANTED) {
2590 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2591 + Binder.getCallingPid()
2592 + ", uid=" + Binder.getCallingUid()
2593 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2594 Slog.w(TAG, msg);
2595 throw new SecurityException(msg);
2596 }
2597
2598 synchronized(this) {
2599 if (mHeavyWeightProcess == null) {
2600 return;
2601 }
2602
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002603 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002604 mHeavyWeightProcess.activities);
2605 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002606 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002607 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002608 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002609 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002611 null, "finish-heavy");
2612 }
2613 }
2614 }
2615
2616 mHeavyWeightProcess = null;
2617 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2618 }
2619 }
2620
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002621 public void crashApplication(int uid, int initialPid, String packageName,
2622 String message) {
2623 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2624 != PackageManager.PERMISSION_GRANTED) {
2625 String msg = "Permission Denial: crashApplication() from pid="
2626 + Binder.getCallingPid()
2627 + ", uid=" + Binder.getCallingUid()
2628 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2629 Slog.w(TAG, msg);
2630 throw new SecurityException(msg);
2631 }
2632
2633 synchronized(this) {
2634 ProcessRecord proc = null;
2635
2636 // Figure out which process to kill. We don't trust that initialPid
2637 // still has any relation to current pids, so must scan through the
2638 // list.
2639 synchronized (mPidsSelfLocked) {
2640 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2641 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002642 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002643 continue;
2644 }
2645 if (p.pid == initialPid) {
2646 proc = p;
2647 break;
2648 }
2649 for (String str : p.pkgList) {
2650 if (str.equals(packageName)) {
2651 proc = p;
2652 }
2653 }
2654 }
2655 }
2656
2657 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002658 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002659 + " initialPid=" + initialPid
2660 + " packageName=" + packageName);
2661 return;
2662 }
2663
2664 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002665 if (proc.pid == Process.myPid()) {
2666 Log.w(TAG, "crashApplication: trying to crash self!");
2667 return;
2668 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002669 long ident = Binder.clearCallingIdentity();
2670 try {
2671 proc.thread.scheduleCrash(message);
2672 } catch (RemoteException e) {
2673 }
2674 Binder.restoreCallingIdentity(ident);
2675 }
2676 }
2677 }
2678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 public final void finishSubActivity(IBinder token, String resultWho,
2680 int requestCode) {
2681 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002682 ActivityRecord self = mMainStack.isInStackLocked(token);
2683 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 return;
2685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686
2687 final long origId = Binder.clearCallingIdentity();
2688
2689 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002690 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2691 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 if (r.resultTo == self && r.requestCode == requestCode) {
2693 if ((r.resultWho == null && resultWho == null) ||
2694 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002695 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696 Activity.RESULT_CANCELED, null, "request-sub");
2697 }
2698 }
2699 }
2700
2701 Binder.restoreCallingIdentity(origId);
2702 }
2703 }
2704
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002705 public boolean willActivityBeVisible(IBinder token) {
2706 synchronized(this) {
2707 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002708 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2709 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002710 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002711 return true;
2712 }
2713 if (r.fullscreen && !r.finishing) {
2714 return false;
2715 }
2716 }
2717 return true;
2718 }
2719 }
2720
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002721 public void overridePendingTransition(IBinder token, String packageName,
2722 int enterAnim, int exitAnim) {
2723 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002724 ActivityRecord self = mMainStack.isInStackLocked(token);
2725 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002726 return;
2727 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002728
2729 final long origId = Binder.clearCallingIdentity();
2730
2731 if (self.state == ActivityState.RESUMED
2732 || self.state == ActivityState.PAUSING) {
2733 mWindowManager.overridePendingAppTransition(packageName,
2734 enterAnim, exitAnim);
2735 }
2736
2737 Binder.restoreCallingIdentity(origId);
2738 }
2739 }
2740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002742 * Main function for removing an existing process from the activity manager
2743 * as a result of that process going away. Clears out all connections
2744 * to the process.
2745 */
2746 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002747 boolean restarting, boolean allowRestart) {
2748 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002749 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002750 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002751 }
2752
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002753 if (mProfileProc == app) {
2754 clearProfilerLocked();
2755 }
2756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002758 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2759 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2760 mMainStack.mPausingActivity = null;
2761 }
2762 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2763 mMainStack.mLastPausedActivity = null;
2764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765
2766 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002767 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768
2769 boolean atTop = true;
2770 boolean hasVisibleActivities = false;
2771
2772 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002774 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 TAG, "Removing app " + app + " from history with " + i + " entries");
2776 while (i > 0) {
2777 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002778 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002779 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2781 if (r.app == app) {
2782 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002783 if (ActivityStack.DEBUG_ADD_REMOVE) {
2784 RuntimeException here = new RuntimeException("here");
2785 here.fillInStackTrace();
2786 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2787 + ": haveState=" + r.haveState
2788 + " stateNotNeeded=" + r.stateNotNeeded
2789 + " finishing=" + r.finishing
2790 + " state=" + r.state, here);
2791 }
2792 if (!r.finishing) {
2793 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002794 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2795 System.identityHashCode(r),
2796 r.task.taskId, r.shortComponentName,
2797 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002798 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002799 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800
2801 } else {
2802 // We have the current state for this activity, so
2803 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002804 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002805 TAG, "Keeping entry, setting app to null");
2806 if (r.visible) {
2807 hasVisibleActivities = true;
2808 }
2809 r.app = null;
2810 r.nowVisible = false;
2811 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002812 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2813 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 r.icicle = null;
2815 }
2816 }
2817
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002818 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820 atTop = false;
2821 }
2822
2823 app.activities.clear();
2824
2825 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002826 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 + " running instrumentation " + app.instrumentationClass);
2828 Bundle info = new Bundle();
2829 info.putString("shortMsg", "Process crashed.");
2830 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2831 }
2832
2833 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 // If there was nothing to resume, and we are not already
2836 // restarting this process, but there is a visible activity that
2837 // is hosted by the process... then make sure all visible
2838 // activities are running, taking care of restarting this
2839 // process.
2840 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842 }
2843 }
2844 }
2845 }
2846
2847 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2848 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002850 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2851 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2853 return i;
2854 }
2855 }
2856 return -1;
2857 }
2858
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002859 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 IApplicationThread thread) {
2861 if (thread == null) {
2862 return null;
2863 }
2864
2865 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002866 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
2868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 IApplicationThread thread) {
2871
2872 mProcDeaths[0]++;
2873
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002874 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2875 synchronized (stats) {
2876 stats.noteProcessDiedLocked(app.info.uid, pid);
2877 }
2878
Magnus Edlund7bb25812010-02-24 15:45:06 +01002879 // Clean up already done if the process has been re-started.
2880 if (app.pid == pid && app.thread != null &&
2881 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002882 if (!app.killedBackground) {
2883 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2884 + ") has died.");
2885 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002886 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002887 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 TAG, "Dying app: " + app + ", pid: " + pid
2889 + ", thread: " + thread.asBinder());
2890 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002891 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892
2893 if (doLowMem) {
2894 // If there are no longer any background processes running,
2895 // and the app that died was not running instrumentation,
2896 // then tell everyone we are now low on memory.
2897 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002898 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2899 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002900 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 haveBg = true;
2902 break;
2903 }
2904 }
2905
2906 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002907 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002908 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002909 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2910 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002911 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002912 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2913 // The low memory report is overriding any current
2914 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002915 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002916 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002917 rec.lastRequestedGc = 0;
2918 } else {
2919 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002921 rec.reportLowMemory = true;
2922 rec.lastLowMemory = now;
2923 mProcessesToGc.remove(rec);
2924 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 }
2926 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002927 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002928 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002931 } else if (app.pid != pid) {
2932 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002933 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002934 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002935 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002936 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002937 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 + thread.asBinder());
2939 }
2940 }
2941
Dan Egnor42471dd2010-01-07 17:25:22 -08002942 /**
2943 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002944 * @param clearTraces causes the dump file to be erased prior to the new
2945 * traces being written, if true; when false, the new traces will be
2946 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002947 * @param firstPids of dalvik VM processes to dump stack traces for first
2948 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002949 * @return file containing stack traces, or null if no dump file is configured
2950 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002951 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2952 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002953 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2954 if (tracesPath == null || tracesPath.length() == 0) {
2955 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002957
2958 File tracesFile = new File(tracesPath);
2959 try {
2960 File tracesDir = tracesFile.getParentFile();
2961 if (!tracesDir.exists()) tracesFile.mkdirs();
2962 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2963
Christopher Tate6ee412d2010-05-28 12:01:56 -07002964 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002965 tracesFile.createNewFile();
2966 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2967 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002968 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002969 return null;
2970 }
2971
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002972 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2973 return tracesFile;
2974 }
2975
2976 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2977 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002978 // Use a FileObserver to detect when traces finish writing.
2979 // The order of traces is considered important to maintain for legibility.
2980 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2981 public synchronized void onEvent(int event, String path) { notify(); }
2982 };
2983
2984 try {
2985 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002986
2987 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002988 if (firstPids != null) {
2989 try {
2990 int num = firstPids.size();
2991 for (int i = 0; i < num; i++) {
2992 synchronized (observer) {
2993 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
2994 observer.wait(200); // Wait for write-close, give up after 200msec
2995 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002996 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002997 } catch (InterruptedException e) {
2998 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002999 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003000 }
3001
3002 // Next measure CPU usage.
3003 if (processStats != null) {
3004 processStats.init();
3005 System.gc();
3006 processStats.update();
3007 try {
3008 synchronized (processStats) {
3009 processStats.wait(500); // measure over 1/2 second.
3010 }
3011 } catch (InterruptedException e) {
3012 }
3013 processStats.update();
3014
3015 // We'll take the stack crawls of just the top apps using CPU.
3016 final int N = processStats.countWorkingStats();
3017 int numProcs = 0;
3018 for (int i=0; i<N && numProcs<5; i++) {
3019 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3020 if (lastPids.indexOfKey(stats.pid) >= 0) {
3021 numProcs++;
3022 try {
3023 synchronized (observer) {
3024 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3025 observer.wait(200); // Wait for write-close, give up after 200msec
3026 }
3027 } catch (InterruptedException e) {
3028 Log.wtf(TAG, e);
3029 }
3030
3031 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003032 }
3033 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003034
Dan Egnor42471dd2010-01-07 17:25:22 -08003035 } finally {
3036 observer.stopWatching();
3037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 }
3039
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003040 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
3041 if (IS_USER_BUILD) {
3042 return;
3043 }
3044 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3045 if (tracesPath == null || tracesPath.length() == 0) {
3046 return;
3047 }
3048
3049 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3050 StrictMode.allowThreadDiskWrites();
3051 try {
3052 final File tracesFile = new File(tracesPath);
3053 final File tracesDir = tracesFile.getParentFile();
3054 final File tracesTmp = new File(tracesDir, "__tmp__");
3055 try {
3056 if (!tracesDir.exists()) tracesFile.mkdirs();
3057 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3058
3059 if (tracesFile.exists()) {
3060 tracesTmp.delete();
3061 tracesFile.renameTo(tracesTmp);
3062 }
3063 StringBuilder sb = new StringBuilder();
3064 Time tobj = new Time();
3065 tobj.set(System.currentTimeMillis());
3066 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3067 sb.append(": ");
3068 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3069 sb.append(" since ");
3070 sb.append(msg);
3071 FileOutputStream fos = new FileOutputStream(tracesFile);
3072 fos.write(sb.toString().getBytes());
3073 if (app == null) {
3074 fos.write("\n*** No application process!".getBytes());
3075 }
3076 fos.close();
3077 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3078 } catch (IOException e) {
3079 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3080 return;
3081 }
3082
3083 if (app != null) {
3084 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3085 firstPids.add(app.pid);
3086 dumpStackTraces(tracesPath, firstPids, null, null);
3087 }
3088
3089 File lastTracesFile = null;
3090 File curTracesFile = null;
3091 for (int i=9; i>=0; i--) {
3092 String name = String.format("slow%02d.txt", i);
3093 curTracesFile = new File(tracesDir, name);
3094 if (curTracesFile.exists()) {
3095 if (lastTracesFile != null) {
3096 curTracesFile.renameTo(lastTracesFile);
3097 } else {
3098 curTracesFile.delete();
3099 }
3100 }
3101 lastTracesFile = curTracesFile;
3102 }
3103 tracesFile.renameTo(curTracesFile);
3104 if (tracesTmp.exists()) {
3105 tracesTmp.renameTo(tracesFile);
3106 }
3107 } finally {
3108 StrictMode.setThreadPolicy(oldPolicy);
3109 }
3110 }
3111
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003112 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3113 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003114 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3115 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3116
Dianne Hackborn287952c2010-09-22 22:34:31 -07003117 if (mController != null) {
3118 try {
3119 // 0 == continue, -1 = kill process immediately
3120 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3121 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3122 } catch (RemoteException e) {
3123 mController = null;
3124 }
3125 }
3126
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003127 long anrTime = SystemClock.uptimeMillis();
3128 if (MONITOR_CPU_USAGE) {
3129 updateCpuStatsNow();
3130 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003131
3132 synchronized (this) {
3133 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3134 if (mShuttingDown) {
3135 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3136 return;
3137 } else if (app.notResponding) {
3138 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3139 return;
3140 } else if (app.crashing) {
3141 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3142 return;
3143 }
3144
3145 // In case we come through here for the same app before completing
3146 // this one, mark as anring now so we will bail out.
3147 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003148
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003149 // Log the ANR to the event log.
3150 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3151 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003152
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003153 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003154 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155
3156 int parentPid = app.pid;
3157 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003158 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003159
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003160 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003161
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003162 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3163 ProcessRecord r = mLruProcesses.get(i);
3164 if (r != null && r.thread != null) {
3165 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003166 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3167 if (r.persistent) {
3168 firstPids.add(pid);
3169 } else {
3170 lastPids.put(pid, Boolean.TRUE);
3171 }
3172 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 }
3175 }
3176
Dan Egnor42471dd2010-01-07 17:25:22 -08003177 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003178 StringBuilder info = mStringBuilder;
3179 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003180 info.append("ANR in ").append(app.processName);
3181 if (activity != null && activity.shortComponentName != null) {
3182 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003183 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003184 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003186 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003188 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003189 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191
Dianne Hackborn287952c2010-09-22 22:34:31 -07003192 final ProcessStats processStats = new ProcessStats(true);
3193
3194 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3195
Dan Egnor42471dd2010-01-07 17:25:22 -08003196 String cpuInfo = null;
3197 if (MONITOR_CPU_USAGE) {
3198 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003199 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003200 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003201 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003202 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003203 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 }
3205
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003206 info.append(processStats.printCurrentState(anrTime));
3207
Joe Onorato8a9b2202010-02-26 18:56:32 -08003208 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003209 if (tracesFile == null) {
3210 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3211 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3212 }
3213
Jeff Sharkeya353d262011-10-28 11:12:06 -07003214 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3215 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003216
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003217 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003219 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3220 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003222 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3223 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 }
3225 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003226 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 }
3228 }
3229
Dan Egnor42471dd2010-01-07 17:25:22 -08003230 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3231 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3232 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003233
3234 synchronized (this) {
3235 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003236 Slog.w(TAG, "Killing " + app + ": background ANR");
3237 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3238 app.processName, app.setAdj, "background ANR");
3239 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003240 return;
3241 }
3242
3243 // Set the app's notResponding state, and look up the errorReportReceiver
3244 makeAppNotRespondingLocked(app,
3245 activity != null ? activity.shortComponentName : null,
3246 annotation != null ? "ANR " + annotation : "ANR",
3247 info.toString());
3248
3249 // Bring up the infamous App Not Responding dialog
3250 Message msg = Message.obtain();
3251 HashMap map = new HashMap();
3252 msg.what = SHOW_NOT_RESPONDING_MSG;
3253 msg.obj = map;
3254 map.put("app", app);
3255 if (activity != null) {
3256 map.put("activity", activity);
3257 }
3258
3259 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 }
3262
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003263 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3264 if (!mLaunchWarningShown) {
3265 mLaunchWarningShown = true;
3266 mHandler.post(new Runnable() {
3267 @Override
3268 public void run() {
3269 synchronized (ActivityManagerService.this) {
3270 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3271 d.show();
3272 mHandler.postDelayed(new Runnable() {
3273 @Override
3274 public void run() {
3275 synchronized (ActivityManagerService.this) {
3276 d.dismiss();
3277 mLaunchWarningShown = false;
3278 }
3279 }
3280 }, 4000);
3281 }
3282 }
3283 });
3284 }
3285 }
3286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003288 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003289 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 int uid = Binder.getCallingUid();
3291 int pid = Binder.getCallingPid();
3292 long callingId = Binder.clearCallingIdentity();
3293 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003294 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 int pkgUid = -1;
3296 synchronized(this) {
3297 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003298 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 } catch (RemoteException e) {
3300 }
3301 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003302 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 return false;
3304 }
3305 if (uid == pkgUid || checkComponentPermission(
3306 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003307 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003309 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 } else {
3311 throw new SecurityException(pid+" does not have permission:"+
3312 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3313 "for process:"+packageName);
3314 }
3315 }
3316
3317 try {
3318 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003319 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3321 Uri.fromParts("package", packageName, null));
3322 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003323 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003324 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 } catch (RemoteException e) {
3326 }
3327 } finally {
3328 Binder.restoreCallingIdentity(callingId);
3329 }
3330 return true;
3331 }
3332
Dianne Hackborn03abb812010-01-04 18:43:19 -08003333 public void killBackgroundProcesses(final String packageName) {
3334 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3335 != PackageManager.PERMISSION_GRANTED &&
3336 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3337 != PackageManager.PERMISSION_GRANTED) {
3338 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 + Binder.getCallingPid()
3340 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003341 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003342 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 throw new SecurityException(msg);
3344 }
3345
Amith Yamasani483f3b02012-03-13 16:08:00 -07003346 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 long callingId = Binder.clearCallingIdentity();
3348 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003349 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003350 int pkgUid = -1;
3351 synchronized(this) {
3352 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003353 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 } catch (RemoteException e) {
3355 }
3356 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003357 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 return;
3359 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003360 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003361 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3362 }
3363 } finally {
3364 Binder.restoreCallingIdentity(callingId);
3365 }
3366 }
3367
3368 public void killAllBackgroundProcesses() {
3369 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3370 != PackageManager.PERMISSION_GRANTED) {
3371 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3372 + Binder.getCallingPid()
3373 + ", uid=" + Binder.getCallingUid()
3374 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3375 Slog.w(TAG, msg);
3376 throw new SecurityException(msg);
3377 }
3378
3379 long callingId = Binder.clearCallingIdentity();
3380 try {
3381 synchronized(this) {
3382 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3383 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3384 final int NA = apps.size();
3385 for (int ia=0; ia<NA; ia++) {
3386 ProcessRecord app = apps.valueAt(ia);
3387 if (app.persistent) {
3388 // we don't kill persistent processes
3389 continue;
3390 }
3391 if (app.removed) {
3392 procs.add(app);
3393 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3394 app.removed = true;
3395 procs.add(app);
3396 }
3397 }
3398 }
3399
3400 int N = procs.size();
3401 for (int i=0; i<N; i++) {
3402 removeProcessLocked(procs.get(i), false, true, "kill all background");
3403 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003404 }
3405 } finally {
3406 Binder.restoreCallingIdentity(callingId);
3407 }
3408 }
3409
3410 public void forceStopPackage(final String packageName) {
3411 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3412 != PackageManager.PERMISSION_GRANTED) {
3413 String msg = "Permission Denial: forceStopPackage() from pid="
3414 + Binder.getCallingPid()
3415 + ", uid=" + Binder.getCallingUid()
3416 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003417 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003418 throw new SecurityException(msg);
3419 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003420 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003421 long callingId = Binder.clearCallingIdentity();
3422 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003423 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003424 int pkgUid = -1;
3425 synchronized(this) {
3426 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003427 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003428 } catch (RemoteException e) {
3429 }
3430 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003431 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003432 return;
3433 }
3434 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003435 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003436 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003437 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003438 } catch (IllegalArgumentException e) {
3439 Slog.w(TAG, "Failed trying to unstop package "
3440 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 }
3443 } finally {
3444 Binder.restoreCallingIdentity(callingId);
3445 }
3446 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003447
3448 /*
3449 * The pkg name and uid have to be specified.
3450 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3451 */
3452 public void killApplicationWithUid(String pkg, int uid) {
3453 if (pkg == null) {
3454 return;
3455 }
3456 // Make sure the uid is valid.
3457 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003458 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003459 return;
3460 }
3461 int callerUid = Binder.getCallingUid();
3462 // Only the system server can kill an application
3463 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003464 // Post an aysnc message to kill the application
3465 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3466 msg.arg1 = uid;
3467 msg.arg2 = 0;
3468 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003469 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003470 } else {
3471 throw new SecurityException(callerUid + " cannot kill pkg: " +
3472 pkg);
3473 }
3474 }
3475
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003476 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003477 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003478 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003479 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003480 if (reason != null) {
3481 intent.putExtra("reason", reason);
3482 }
3483
3484 final int uid = Binder.getCallingUid();
3485 final long origId = Binder.clearCallingIdentity();
3486 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003487 mWindowManager.closeSystemDialogs(reason);
3488
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003489 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003490 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003491 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003492 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003493 Activity.RESULT_CANCELED, null, "close-sys");
3494 }
3495 }
3496
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003497 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003498 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003499 }
3500 Binder.restoreCallingIdentity(origId);
3501 }
3502
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003503 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003504 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003505 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003506 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3507 for (int i=pids.length-1; i>=0; i--) {
3508 infos[i] = new Debug.MemoryInfo();
3509 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003510 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003511 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003512 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003513
Dianne Hackbornb437e092011-08-05 17:50:29 -07003514 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003515 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003516 long[] pss = new long[pids.length];
3517 for (int i=pids.length-1; i>=0; i--) {
3518 pss[i] = Debug.getPss(pids[i]);
3519 }
3520 return pss;
3521 }
3522
Christopher Tate5e1ab332009-09-01 20:32:49 -07003523 public void killApplicationProcess(String processName, int uid) {
3524 if (processName == null) {
3525 return;
3526 }
3527
3528 int callerUid = Binder.getCallingUid();
3529 // Only the system server can kill an application
3530 if (callerUid == Process.SYSTEM_UID) {
3531 synchronized (this) {
3532 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003533 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003534 try {
3535 app.thread.scheduleSuicide();
3536 } catch (RemoteException e) {
3537 // If the other end already died, then our work here is done.
3538 }
3539 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003540 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003541 + processName + " / " + uid);
3542 }
3543 }
3544 } else {
3545 throw new SecurityException(callerUid + " cannot kill app process: " +
3546 processName);
3547 }
3548 }
3549
Dianne Hackborn03abb812010-01-04 18:43:19 -08003550 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003551 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003552 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3553 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003554 if (!mProcessesReady) {
3555 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 intent.putExtra(Intent.EXTRA_UID, uid);
3558 broadcastIntentLocked(null, null, intent,
3559 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003560 false, false,
3561 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 }
3563
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003564 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003565 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003566 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003567 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568
Dianne Hackborn03abb812010-01-04 18:43:19 -08003569 // Remove all processes this package may have touched: all with the
3570 // same UID (except for the system or root user), and all whose name
3571 // matches the package name.
3572 final String procNamePrefix = packageName + ":";
3573 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3574 final int NA = apps.size();
3575 for (int ia=0; ia<NA; ia++) {
3576 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003577 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003578 // we don't kill persistent processes
3579 continue;
3580 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003581 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003582 if (doit) {
3583 procs.add(app);
3584 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003585 } else if ((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
3586 || app.processName.equals(packageName)
3587 || app.processName.startsWith(procNamePrefix)) {
3588 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003589 if (!doit) {
3590 return true;
3591 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003592 app.removed = true;
3593 procs.add(app);
3594 }
3595 }
3596 }
3597 }
3598
3599 int N = procs.size();
3600 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003601 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003602 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003603 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003604 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003605
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003606 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003607 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003608 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003609 int i;
3610 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 if (uid < 0) {
3613 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003614 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 } catch (RemoteException e) {
3616 }
3617 }
3618
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003619 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003620 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003621
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003622 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3623 while (badApps.hasNext()) {
3624 SparseArray<Long> ba = badApps.next();
3625 if (ba.get(uid) != null) {
3626 badApps.remove();
3627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 }
3629 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003630
3631 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003632 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003634 TaskRecord lastTask = null;
3635 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003636 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003637 final boolean samePackage = r.packageName.equals(name);
3638 if ((samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003639 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003640 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003641 if (r.finishing) {
3642 // If this activity is just finishing, then it is not
3643 // interesting as far as something to stop.
3644 continue;
3645 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003646 return true;
3647 }
3648 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003649 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003650 if (samePackage) {
3651 if (r.app != null) {
3652 r.app.removed = true;
3653 }
3654 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003656 lastTask = r.task;
3657 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003658 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003659 i--;
3660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 }
3662 }
3663
3664 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003665 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003666 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003667 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003668 if (!doit) {
3669 return true;
3670 }
3671 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003672 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 if (service.app != null) {
3674 service.app.removed = true;
3675 }
3676 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003677 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 services.add(service);
3679 }
3680 }
3681
3682 N = services.size();
3683 for (i=0; i<N; i++) {
3684 bringDownServiceLocked(services.get(i), true);
3685 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003686
3687 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani37ce3a82012-02-06 12:04:42 -08003688 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(-1).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003689 if (provider.info.packageName.equals(name)
3690 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3691 if (!doit) {
3692 return true;
3693 }
3694 didSomething = true;
3695 providers.add(provider);
3696 }
3697 }
3698
3699 N = providers.size();
3700 for (i=0; i<N; i++) {
3701 removeDyingProviderLocked(null, providers.get(i));
3702 }
3703
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003704 if (doit) {
3705 if (purgeCache) {
3706 AttributeCache ac = AttributeCache.instance();
3707 if (ac != null) {
3708 ac.removePackage(name);
3709 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003710 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003711 if (mBooted) {
3712 mMainStack.resumeTopActivityLocked(null);
3713 mMainStack.scheduleIdleLocked();
3714 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003715 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003716
3717 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
3719
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003720 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003721 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003723 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003724 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003725 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 + "/" + uid + ")");
3727
3728 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003729 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003730 if (mHeavyWeightProcess == app) {
3731 mHeavyWeightProcess = null;
3732 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003734 boolean needRestart = false;
3735 if (app.pid > 0 && app.pid != MY_PID) {
3736 int pid = app.pid;
3737 synchronized (mPidsSelfLocked) {
3738 mPidsSelfLocked.remove(pid);
3739 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3740 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003741 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003742 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003743 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003744 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003746 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003748 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 } else {
3750 needRestart = true;
3751 }
3752 }
3753 } else {
3754 mRemovedProcesses.add(app);
3755 }
3756
3757 return needRestart;
3758 }
3759
3760 private final void processStartTimedOutLocked(ProcessRecord app) {
3761 final int pid = app.pid;
3762 boolean gone = false;
3763 synchronized (mPidsSelfLocked) {
3764 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3765 if (knownApp != null && knownApp.thread == null) {
3766 mPidsSelfLocked.remove(pid);
3767 gone = true;
3768 }
3769 }
3770
3771 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003772 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003773 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003774 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003775 mProcessNames.remove(app.processName, app.uid);
3776 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003777 if (mHeavyWeightProcess == app) {
3778 mHeavyWeightProcess = null;
3779 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3780 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003781 // Take care of any launching providers waiting for this process.
3782 checkAppInLaunchingProvidersLocked(app, true);
3783 // Take care of any services that are waiting for the process.
3784 for (int i=0; i<mPendingServices.size(); i++) {
3785 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003786 if ((app.uid == sr.appInfo.uid
3787 && app.processName.equals(sr.processName))
3788 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003789 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003790 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003791 mPendingServices.remove(i);
3792 i--;
3793 bringDownServiceLocked(sr, true);
3794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003796 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3797 app.processName, app.setAdj, "start timeout");
3798 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003799 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003800 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003801 try {
3802 IBackupManager bm = IBackupManager.Stub.asInterface(
3803 ServiceManager.getService(Context.BACKUP_SERVICE));
3804 bm.agentDisconnected(app.info.packageName);
3805 } catch (RemoteException e) {
3806 // Can't happen; the backup manager is local
3807 }
3808 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003809 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003811 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003814 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 }
3816 }
3817
3818 private final boolean attachApplicationLocked(IApplicationThread thread,
3819 int pid) {
3820
3821 // Find the application record that is being attached... either via
3822 // the pid if we are running in multiple processes, or just pull the
3823 // next app record if we are emulating process with anonymous threads.
3824 ProcessRecord app;
3825 if (pid != MY_PID && pid >= 0) {
3826 synchronized (mPidsSelfLocked) {
3827 app = mPidsSelfLocked.get(pid);
3828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 } else {
3830 app = null;
3831 }
3832
3833 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003834 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003836 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003838 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 } else {
3840 try {
3841 thread.scheduleExit();
3842 } catch (Exception e) {
3843 // Ignore exceptions.
3844 }
3845 }
3846 return false;
3847 }
3848
3849 // If this application record is still attached to a previous
3850 // process, clean it up now.
3851 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003852 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 }
3854
3855 // Tell the process all about itself.
3856
Joe Onorato8a9b2202010-02-26 18:56:32 -08003857 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 TAG, "Binding process pid " + pid + " to record " + app);
3859
3860 String processName = app.processName;
3861 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003862 AppDeathRecipient adr = new AppDeathRecipient(
3863 app, pid, thread);
3864 thread.asBinder().linkToDeath(adr, 0);
3865 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 } catch (RemoteException e) {
3867 app.resetPackageList();
3868 startProcessLocked(app, "link fail", processName);
3869 return false;
3870 }
3871
Doug Zongker2bec3d42009-12-04 12:52:44 -08003872 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873
3874 app.thread = thread;
3875 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003876 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3877 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 app.forcingToForeground = null;
3879 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003880 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 app.debugging = false;
3882
3883 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3884
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003885 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003886 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003888 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003889 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003890 }
3891
Joe Onorato8a9b2202010-02-26 18:56:32 -08003892 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 TAG, "New app record " + app
3894 + " thread=" + thread.asBinder() + " pid=" + pid);
3895 try {
3896 int testMode = IApplicationThread.DEBUG_OFF;
3897 if (mDebugApp != null && mDebugApp.equals(processName)) {
3898 testMode = mWaitForDebugger
3899 ? IApplicationThread.DEBUG_WAIT
3900 : IApplicationThread.DEBUG_ON;
3901 app.debugging = true;
3902 if (mDebugTransient) {
3903 mDebugApp = mOrigDebugApp;
3904 mWaitForDebugger = mOrigWaitForDebugger;
3905 }
3906 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003907 String profileFile = app.instrumentationProfileFile;
3908 ParcelFileDescriptor profileFd = null;
3909 boolean profileAutoStop = false;
3910 if (mProfileApp != null && mProfileApp.equals(processName)) {
3911 mProfileProc = app;
3912 profileFile = mProfileFile;
3913 profileFd = mProfileFd;
3914 profileAutoStop = mAutoStopProfiler;
3915 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003916 boolean enableOpenGlTrace = false;
3917 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3918 enableOpenGlTrace = true;
3919 mOpenGlTraceApp = null;
3920 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003921
Christopher Tate181fafa2009-05-14 11:12:14 -07003922 // If the app is being launched for restore or full backup, set it up specially
3923 boolean isRestrictedBackupMode = false;
3924 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3925 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003926 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003927 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3928 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003929
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003930 ensurePackageDexOpt(app.instrumentationInfo != null
3931 ? app.instrumentationInfo.packageName
3932 : app.info.packageName);
3933 if (app.instrumentationClass != null) {
3934 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003935 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003936 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003937 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003938 ApplicationInfo appInfo = app.instrumentationInfo != null
3939 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003940 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003941 if (profileFd != null) {
3942 profileFd = profileFd.dup();
3943 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003944 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003945 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003946 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3947 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003948 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003949 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003950 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003951 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 } catch (Exception e) {
3953 // todo: Yikes! What should we do? For now we will try to
3954 // start another process, but that could easily get us in
3955 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003956 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957
3958 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003959 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 startProcessLocked(app, "bind fail", processName);
3961 return false;
3962 }
3963
3964 // Remove this record from the list of starting applications.
3965 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003966 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3967 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 mProcessesOnHold.remove(app);
3969
3970 boolean badApp = false;
3971 boolean didSomething = false;
3972
3973 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003974 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003975 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003976 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 && processName.equals(hr.processName)) {
3978 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003979 if (mHeadless) {
3980 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3981 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 didSomething = true;
3983 }
3984 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003985 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 + hr.intent.getComponent().flattenToShortString(), e);
3987 badApp = true;
3988 }
3989 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003990 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 }
3992 }
3993
3994 // Find any services that should be running in this process...
3995 if (!badApp && mPendingServices.size() > 0) {
3996 ServiceRecord sr = null;
3997 try {
3998 for (int i=0; i<mPendingServices.size(); i++) {
3999 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004000 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4001 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 continue;
4003 }
4004
4005 mPendingServices.remove(i);
4006 i--;
4007 realStartServiceLocked(sr, app);
4008 didSomething = true;
4009 }
4010 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004011 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 + sr.shortName, e);
4013 badApp = true;
4014 }
4015 }
4016
Christopher Tatef46723b2012-01-26 14:19:24 -08004017 // Check if a next-broadcast receiver is in this process...
4018 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004020 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004022 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
4025 }
4026
Christopher Tate181fafa2009-05-14 11:12:14 -07004027 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004028 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004029 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004030 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004031 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004032 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4033 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4034 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004035 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004036 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 e.printStackTrace();
4038 }
4039 }
4040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 if (badApp) {
4042 // todo: Also need to kill application to deal with all
4043 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004044 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004045 return false;
4046 }
4047
4048 if (!didSomething) {
4049 updateOomAdjLocked();
4050 }
4051
4052 return true;
4053 }
4054
4055 public final void attachApplication(IApplicationThread thread) {
4056 synchronized (this) {
4057 int callingPid = Binder.getCallingPid();
4058 final long origId = Binder.clearCallingIdentity();
4059 attachApplicationLocked(thread, callingPid);
4060 Binder.restoreCallingIdentity(origId);
4061 }
4062 }
4063
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004064 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004066 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4067 if (stopProfiling) {
4068 synchronized (this) {
4069 if (mProfileProc == r.app) {
4070 if (mProfileFd != null) {
4071 try {
4072 mProfileFd.close();
4073 } catch (IOException e) {
4074 }
4075 clearProfilerLocked();
4076 }
4077 }
4078 }
4079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 Binder.restoreCallingIdentity(origId);
4081 }
4082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004084 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004085 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 mWindowManager.enableScreenAfterBoot();
4087 }
4088
Dianne Hackborn661cd522011-08-22 00:26:20 -07004089 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004090 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004091 mWindowManager.showBootMessage(msg, always);
4092 }
4093
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004094 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004095 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004096 synchronized (this) {
4097 mMainStack.dismissKeyguardOnNextActivityLocked();
4098 }
4099 }
4100
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004101 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004102 IntentFilter pkgFilter = new IntentFilter();
4103 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4104 pkgFilter.addDataScheme("package");
4105 mContext.registerReceiver(new BroadcastReceiver() {
4106 @Override
4107 public void onReceive(Context context, Intent intent) {
4108 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4109 if (pkgs != null) {
4110 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004111 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004112 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4113 setResultCode(Activity.RESULT_OK);
4114 return;
4115 }
4116 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004117 }
4118 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004119 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004120 }, pkgFilter);
4121
4122 synchronized (this) {
4123 // Ensure that any processes we had put on hold are now started
4124 // up.
4125 final int NP = mProcessesOnHold.size();
4126 if (NP > 0) {
4127 ArrayList<ProcessRecord> procs =
4128 new ArrayList<ProcessRecord>(mProcessesOnHold);
4129 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004130 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4131 + procs.get(ip));
4132 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004133 }
4134 }
4135
4136 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004137 // Start looking for apps that are abusing wake locks.
4138 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004139 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004140 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004141 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004142 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004143 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004144 broadcastIntentLocked(null, null,
4145 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4146 null, null, 0, null, null,
4147 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004148 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004149 }
4150 }
4151 }
4152
4153 final void ensureBootCompleted() {
4154 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004155 boolean enableScreen;
4156 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004157 booting = mBooting;
4158 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004159 enableScreen = !mBooted;
4160 mBooted = true;
4161 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004162
4163 if (booting) {
4164 finishBooting();
4165 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004166
4167 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004168 enableScreenAfterBoot();
4169 }
4170 }
4171
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004172 public final void activityPaused(IBinder token) {
4173 final long origId = Binder.clearCallingIdentity();
4174 mMainStack.activityPaused(token, false);
4175 Binder.restoreCallingIdentity(origId);
4176 }
4177
4178 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4179 CharSequence description) {
4180 if (localLOGV) Slog.v(
4181 TAG, "Activity stopped: token=" + token);
4182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 // Refuse possible leaked file descriptors
4184 if (icicle != null && icicle.hasFileDescriptors()) {
4185 throw new IllegalArgumentException("File descriptors passed in Bundle");
4186 }
4187
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004188 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189
4190 final long origId = Binder.clearCallingIdentity();
4191
4192 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004193 r = mMainStack.isInStackLocked(token);
4194 if (r != null) {
4195 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 }
4197 }
4198
4199 if (r != null) {
4200 sendPendingThumbnail(r, null, null, null, false);
4201 }
4202
4203 trimApplications();
4204
4205 Binder.restoreCallingIdentity(origId);
4206 }
4207
4208 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004209 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004210 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 }
4212
4213 public String getCallingPackage(IBinder token) {
4214 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004215 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004216 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 }
4218 }
4219
4220 public ComponentName getCallingActivity(IBinder token) {
4221 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004222 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 return r != null ? r.intent.getComponent() : null;
4224 }
4225 }
4226
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004227 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004228 ActivityRecord r = mMainStack.isInStackLocked(token);
4229 if (r == null) {
4230 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004231 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004232 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004233 }
4234
4235 public ComponentName getActivityClassForToken(IBinder token) {
4236 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004237 ActivityRecord r = mMainStack.isInStackLocked(token);
4238 if (r == null) {
4239 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004240 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004241 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
4243 }
4244
4245 public String getPackageForToken(IBinder token) {
4246 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004247 ActivityRecord r = mMainStack.isInStackLocked(token);
4248 if (r == null) {
4249 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004251 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 }
4253 }
4254
4255 public IIntentSender getIntentSender(int type,
4256 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004257 int requestCode, Intent[] intents, String[] resolvedTypes,
4258 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004259 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004261 if (intents != null) {
4262 if (intents.length < 1) {
4263 throw new IllegalArgumentException("Intents array length must be >= 1");
4264 }
4265 for (int i=0; i<intents.length; i++) {
4266 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004267 if (intent != null) {
4268 if (intent.hasFileDescriptors()) {
4269 throw new IllegalArgumentException("File descriptors passed in Intent");
4270 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004271 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004272 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4273 throw new IllegalArgumentException(
4274 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4275 }
4276 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004277 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004278 }
4279 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004280 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004281 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004282 }
4283 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004284 if (options != null) {
4285 if (options.hasFileDescriptors()) {
4286 throw new IllegalArgumentException("File descriptors passed in options");
4287 }
4288 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 synchronized(this) {
4291 int callingUid = Binder.getCallingUid();
4292 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004293 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004294 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004295 .getPackageUid(packageName, UserId.getUserId(callingUid));
4296 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004297 String msg = "Permission Denial: getIntentSender() from pid="
4298 + Binder.getCallingPid()
4299 + ", uid=" + Binder.getCallingUid()
4300 + ", (need uid=" + uid + ")"
4301 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004302 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 throw new SecurityException(msg);
4304 }
4305 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004306
Amith Yamasani742a6712011-05-04 14:49:28 -07004307 if (DEBUG_MU)
4308 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4309 + Binder.getOrigCallingUid());
4310 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004311 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004313 } catch (RemoteException e) {
4314 throw new SecurityException(e);
4315 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004316 }
4317 }
4318
4319 IIntentSender getIntentSenderLocked(int type,
4320 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004321 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4322 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004323 if (DEBUG_MU)
4324 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004325 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004326 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004327 activity = mMainStack.isInStackLocked(token);
4328 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004329 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004331 if (activity.finishing) {
4332 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004334 }
4335
4336 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4337 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4338 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4339 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4340 |PendingIntent.FLAG_UPDATE_CURRENT);
4341
4342 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4343 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004344 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004345 WeakReference<PendingIntentRecord> ref;
4346 ref = mIntentSenderRecords.get(key);
4347 PendingIntentRecord rec = ref != null ? ref.get() : null;
4348 if (rec != null) {
4349 if (!cancelCurrent) {
4350 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004351 if (rec.key.requestIntent != null) {
4352 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4353 }
4354 if (intents != null) {
4355 intents[intents.length-1] = rec.key.requestIntent;
4356 rec.key.allIntents = intents;
4357 rec.key.allResolvedTypes = resolvedTypes;
4358 } else {
4359 rec.key.allIntents = null;
4360 rec.key.allResolvedTypes = null;
4361 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004363 return rec;
4364 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004365 rec.canceled = true;
4366 mIntentSenderRecords.remove(key);
4367 }
4368 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 return rec;
4370 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004371 rec = new PendingIntentRecord(this, key, callingUid);
4372 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004373 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004374 if (activity.pendingResults == null) {
4375 activity.pendingResults
4376 = new HashSet<WeakReference<PendingIntentRecord>>();
4377 }
4378 activity.pendingResults.add(rec.ref);
4379 }
4380 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 }
4382
4383 public void cancelIntentSender(IIntentSender sender) {
4384 if (!(sender instanceof PendingIntentRecord)) {
4385 return;
4386 }
4387 synchronized(this) {
4388 PendingIntentRecord rec = (PendingIntentRecord)sender;
4389 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004390 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004391 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004392 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 String msg = "Permission Denial: cancelIntentSender() from pid="
4394 + Binder.getCallingPid()
4395 + ", uid=" + Binder.getCallingUid()
4396 + " is not allowed to cancel packges "
4397 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004398 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 throw new SecurityException(msg);
4400 }
4401 } catch (RemoteException e) {
4402 throw new SecurityException(e);
4403 }
4404 cancelIntentSenderLocked(rec, true);
4405 }
4406 }
4407
4408 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4409 rec.canceled = true;
4410 mIntentSenderRecords.remove(rec.key);
4411 if (cleanActivity && rec.key.activity != null) {
4412 rec.key.activity.pendingResults.remove(rec.ref);
4413 }
4414 }
4415
4416 public String getPackageForIntentSender(IIntentSender pendingResult) {
4417 if (!(pendingResult instanceof PendingIntentRecord)) {
4418 return null;
4419 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004420 try {
4421 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4422 return res.key.packageName;
4423 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004424 }
4425 return null;
4426 }
4427
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004428 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4429 if (!(pendingResult instanceof PendingIntentRecord)) {
4430 return false;
4431 }
4432 try {
4433 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4434 if (res.key.allIntents == null) {
4435 return false;
4436 }
4437 for (int i=0; i<res.key.allIntents.length; i++) {
4438 Intent intent = res.key.allIntents[i];
4439 if (intent.getPackage() != null && intent.getComponent() != null) {
4440 return false;
4441 }
4442 }
4443 return true;
4444 } catch (ClassCastException e) {
4445 }
4446 return false;
4447 }
4448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004449 public void setProcessLimit(int max) {
4450 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4451 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004452 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004453 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004454 mProcessLimitOverride = max;
4455 }
4456 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 }
4458
4459 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004460 synchronized (this) {
4461 return mProcessLimitOverride;
4462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 }
4464
4465 void foregroundTokenDied(ForegroundToken token) {
4466 synchronized (ActivityManagerService.this) {
4467 synchronized (mPidsSelfLocked) {
4468 ForegroundToken cur
4469 = mForegroundProcesses.get(token.pid);
4470 if (cur != token) {
4471 return;
4472 }
4473 mForegroundProcesses.remove(token.pid);
4474 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4475 if (pr == null) {
4476 return;
4477 }
4478 pr.forcingToForeground = null;
4479 pr.foregroundServices = false;
4480 }
4481 updateOomAdjLocked();
4482 }
4483 }
4484
4485 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4486 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4487 "setProcessForeground()");
4488 synchronized(this) {
4489 boolean changed = false;
4490
4491 synchronized (mPidsSelfLocked) {
4492 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004493 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004494 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004495 return;
4496 }
4497 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4498 if (oldToken != null) {
4499 oldToken.token.unlinkToDeath(oldToken, 0);
4500 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004501 if (pr != null) {
4502 pr.forcingToForeground = null;
4503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 changed = true;
4505 }
4506 if (isForeground && token != null) {
4507 ForegroundToken newToken = new ForegroundToken() {
4508 public void binderDied() {
4509 foregroundTokenDied(this);
4510 }
4511 };
4512 newToken.pid = pid;
4513 newToken.token = token;
4514 try {
4515 token.linkToDeath(newToken, 0);
4516 mForegroundProcesses.put(pid, newToken);
4517 pr.forcingToForeground = token;
4518 changed = true;
4519 } catch (RemoteException e) {
4520 // If the process died while doing this, we will later
4521 // do the cleanup with the process death link.
4522 }
4523 }
4524 }
4525
4526 if (changed) {
4527 updateOomAdjLocked();
4528 }
4529 }
4530 }
4531
4532 // =========================================================
4533 // PERMISSIONS
4534 // =========================================================
4535
4536 static class PermissionController extends IPermissionController.Stub {
4537 ActivityManagerService mActivityManagerService;
4538 PermissionController(ActivityManagerService activityManagerService) {
4539 mActivityManagerService = activityManagerService;
4540 }
4541
4542 public boolean checkPermission(String permission, int pid, int uid) {
4543 return mActivityManagerService.checkPermission(permission, pid,
4544 uid) == PackageManager.PERMISSION_GRANTED;
4545 }
4546 }
4547
4548 /**
4549 * This can be called with or without the global lock held.
4550 */
4551 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004552 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004553 // We might be performing an operation on behalf of an indirect binder
4554 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4555 // client identity accordingly before proceeding.
4556 Identity tlsIdentity = sCallerIdentity.get();
4557 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004558 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4560 uid = tlsIdentity.uid;
4561 pid = tlsIdentity.pid;
4562 }
4563
4564 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004565 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 return PackageManager.PERMISSION_GRANTED;
4567 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004568 // Isolated processes don't get any permissions.
4569 if (UserId.isIsolated(uid)) {
4570 return PackageManager.PERMISSION_DENIED;
4571 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004572 // If there is a uid that owns whatever is being accessed, it has
4573 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004574 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004575 return PackageManager.PERMISSION_GRANTED;
4576 }
4577 // If the target is not exported, then nobody else can get to it.
4578 if (!exported) {
4579 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 return PackageManager.PERMISSION_DENIED;
4581 }
4582 if (permission == null) {
4583 return PackageManager.PERMISSION_GRANTED;
4584 }
4585 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004586 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004587 .checkUidPermission(permission, uid);
4588 } catch (RemoteException e) {
4589 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004590 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004591 }
4592 return PackageManager.PERMISSION_DENIED;
4593 }
4594
4595 /**
4596 * As the only public entry point for permissions checking, this method
4597 * can enforce the semantic that requesting a check on a null global
4598 * permission is automatically denied. (Internally a null permission
4599 * string is used when calling {@link #checkComponentPermission} in cases
4600 * when only uid-based security is needed.)
4601 *
4602 * This can be called with or without the global lock held.
4603 */
4604 public int checkPermission(String permission, int pid, int uid) {
4605 if (permission == null) {
4606 return PackageManager.PERMISSION_DENIED;
4607 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004608 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 }
4610
4611 /**
4612 * Binder IPC calls go through the public entry point.
4613 * This can be called with or without the global lock held.
4614 */
4615 int checkCallingPermission(String permission) {
4616 return checkPermission(permission,
4617 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004618 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 }
4620
4621 /**
4622 * This can be called with or without the global lock held.
4623 */
4624 void enforceCallingPermission(String permission, String func) {
4625 if (checkCallingPermission(permission)
4626 == PackageManager.PERMISSION_GRANTED) {
4627 return;
4628 }
4629
4630 String msg = "Permission Denial: " + func + " from pid="
4631 + Binder.getCallingPid()
4632 + ", uid=" + Binder.getCallingUid()
4633 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004634 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 throw new SecurityException(msg);
4636 }
4637
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004638 /**
4639 * Determine if UID is holding permissions required to access {@link Uri} in
4640 * the given {@link ProviderInfo}. Final permission checking is always done
4641 * in {@link ContentProvider}.
4642 */
4643 private final boolean checkHoldingPermissionsLocked(
4644 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004645 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4646 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004647
4648 if (pi.applicationInfo.uid == uid) {
4649 return true;
4650 } else if (!pi.exported) {
4651 return false;
4652 }
4653
4654 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4655 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004657 // check if target holds top-level <provider> permissions
4658 if (!readMet && pi.readPermission != null
4659 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4660 readMet = true;
4661 }
4662 if (!writeMet && pi.writePermission != null
4663 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4664 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004665 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004666
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004667 // track if unprotected read/write is allowed; any denied
4668 // <path-permission> below removes this ability
4669 boolean allowDefaultRead = pi.readPermission == null;
4670 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004671
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004672 // check if target holds any <path-permission> that match uri
4673 final PathPermission[] pps = pi.pathPermissions;
4674 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004675 final String path = uri.getPath();
4676 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004677 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004678 i--;
4679 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004680 if (pp.match(path)) {
4681 if (!readMet) {
4682 final String pprperm = pp.getReadPermission();
4683 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4684 + pprperm + " for " + pp.getPath()
4685 + ": match=" + pp.match(path)
4686 + " check=" + pm.checkUidPermission(pprperm, uid));
4687 if (pprperm != null) {
4688 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4689 readMet = true;
4690 } else {
4691 allowDefaultRead = false;
4692 }
4693 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004694 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004695 if (!writeMet) {
4696 final String ppwperm = pp.getWritePermission();
4697 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4698 + ppwperm + " for " + pp.getPath()
4699 + ": match=" + pp.match(path)
4700 + " check=" + pm.checkUidPermission(ppwperm, uid));
4701 if (ppwperm != null) {
4702 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4703 writeMet = true;
4704 } else {
4705 allowDefaultWrite = false;
4706 }
4707 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004708 }
4709 }
4710 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004711 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004712
4713 // grant unprotected <provider> read/write, if not blocked by
4714 // <path-permission> above
4715 if (allowDefaultRead) readMet = true;
4716 if (allowDefaultWrite) writeMet = true;
4717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 } catch (RemoteException e) {
4719 return false;
4720 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004721
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004722 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004723 }
4724
4725 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4726 int modeFlags) {
4727 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004728 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 return true;
4730 }
4731 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4732 if (perms == null) return false;
4733 UriPermission perm = perms.get(uri);
4734 if (perm == null) return false;
4735 return (modeFlags&perm.modeFlags) == modeFlags;
4736 }
4737
4738 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004739 enforceNotIsolatedCaller("checkUriPermission");
4740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 // Another redirected-binder-call permissions check as in
4742 // {@link checkComponentPermission}.
4743 Identity tlsIdentity = sCallerIdentity.get();
4744 if (tlsIdentity != null) {
4745 uid = tlsIdentity.uid;
4746 pid = tlsIdentity.pid;
4747 }
4748
Amith Yamasani742a6712011-05-04 14:49:28 -07004749 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 // Our own process gets to do everything.
4751 if (pid == MY_PID) {
4752 return PackageManager.PERMISSION_GRANTED;
4753 }
4754 synchronized(this) {
4755 return checkUriPermissionLocked(uri, uid, modeFlags)
4756 ? PackageManager.PERMISSION_GRANTED
4757 : PackageManager.PERMISSION_DENIED;
4758 }
4759 }
4760
Dianne Hackborn39792d22010-08-19 18:01:52 -07004761 /**
4762 * Check if the targetPkg can be granted permission to access uri by
4763 * the callingUid using the given modeFlags. Throws a security exception
4764 * if callingUid is not allowed to do this. Returns the uid of the target
4765 * if the URI permission grant should be performed; returns -1 if it is not
4766 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004767 * If you already know the uid of the target, you can supply it in
4768 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004769 */
4770 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004771 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004772 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4773 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4774 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004775 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004776 }
4777
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004778 if (targetPkg != null) {
4779 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4780 "Checking grant " + targetPkg + " permission to " + uri);
4781 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004782
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004783 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004784
4785 // If this is not a content: uri, we can't do anything with it.
4786 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004787 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004788 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004789 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 }
4791
4792 String name = uri.getAuthority();
4793 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004794 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4795 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004796 if (cpr != null) {
4797 pi = cpr.info;
4798 } else {
4799 try {
4800 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004801 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004802 } catch (RemoteException ex) {
4803 }
4804 }
4805 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004806 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004807 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004808 }
4809
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004810 int targetUid = lastTargetUid;
4811 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004812 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004813 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004814 if (targetUid < 0) {
4815 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4816 "Can't grant URI permission no uid for: " + targetPkg);
4817 return -1;
4818 }
4819 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004820 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004822 }
4823
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004824 if (targetUid >= 0) {
4825 // First... does the target actually need this permission?
4826 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4827 // No need to grant the target this permission.
4828 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4829 "Target " + targetPkg + " already has full permission to " + uri);
4830 return -1;
4831 }
4832 } else {
4833 // First... there is no target package, so can anyone access it?
4834 boolean allowed = pi.exported;
4835 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4836 if (pi.readPermission != null) {
4837 allowed = false;
4838 }
4839 }
4840 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4841 if (pi.writePermission != null) {
4842 allowed = false;
4843 }
4844 }
4845 if (allowed) {
4846 return -1;
4847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
4849
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004850 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004851 if (!pi.grantUriPermissions) {
4852 throw new SecurityException("Provider " + pi.packageName
4853 + "/" + pi.name
4854 + " does not allow granting of Uri permissions (uri "
4855 + uri + ")");
4856 }
4857 if (pi.uriPermissionPatterns != null) {
4858 final int N = pi.uriPermissionPatterns.length;
4859 boolean allowed = false;
4860 for (int i=0; i<N; i++) {
4861 if (pi.uriPermissionPatterns[i] != null
4862 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4863 allowed = true;
4864 break;
4865 }
4866 }
4867 if (!allowed) {
4868 throw new SecurityException("Provider " + pi.packageName
4869 + "/" + pi.name
4870 + " does not allow granting of permission to path of Uri "
4871 + uri);
4872 }
4873 }
4874
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004875 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004876 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004877 if (callingUid != Process.myUid()) {
4878 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4879 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4880 throw new SecurityException("Uid " + callingUid
4881 + " does not have permission to uri " + uri);
4882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 }
4884 }
4885
Dianne Hackborn39792d22010-08-19 18:01:52 -07004886 return targetUid;
4887 }
4888
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004889 public int checkGrantUriPermission(int callingUid, String targetPkg,
4890 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004891 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004892 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004893 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004894 }
4895 }
4896
Dianne Hackborn39792d22010-08-19 18:01:52 -07004897 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4898 Uri uri, int modeFlags, UriPermissionOwner owner) {
4899 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4900 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4901 if (modeFlags == 0) {
4902 return;
4903 }
4904
4905 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004906 // to the uri, and the target doesn't. Let's now give this to
4907 // the target.
4908
Joe Onorato8a9b2202010-02-26 18:56:32 -08004909 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004910 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004912 HashMap<Uri, UriPermission> targetUris
4913 = mGrantedUriPermissions.get(targetUid);
4914 if (targetUris == null) {
4915 targetUris = new HashMap<Uri, UriPermission>();
4916 mGrantedUriPermissions.put(targetUid, targetUris);
4917 }
4918
4919 UriPermission perm = targetUris.get(uri);
4920 if (perm == null) {
4921 perm = new UriPermission(targetUid, uri);
4922 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004923 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004926 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004928 } else {
4929 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4930 perm.readOwners.add(owner);
4931 owner.addReadPermission(perm);
4932 }
4933 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4934 perm.writeOwners.add(owner);
4935 owner.addWritePermission(perm);
4936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004937 }
4938 }
4939
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004940 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4941 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004942 if (targetPkg == null) {
4943 throw new NullPointerException("targetPkg");
4944 }
4945
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004946 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004947 if (targetUid < 0) {
4948 return;
4949 }
4950
4951 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4952 }
4953
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004954 static class NeededUriGrants extends ArrayList<Uri> {
4955 final String targetPkg;
4956 final int targetUid;
4957 final int flags;
4958
4959 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4960 targetPkg = _targetPkg;
4961 targetUid = _targetUid;
4962 flags = _flags;
4963 }
4964 }
4965
Dianne Hackborn39792d22010-08-19 18:01:52 -07004966 /**
4967 * Like checkGrantUriPermissionLocked, but takes an Intent.
4968 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004969 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4970 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004971 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004972 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4973 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004974 + " from " + intent + "; flags=0x"
4975 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4976
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004977 if (targetPkg == null) {
4978 throw new NullPointerException("targetPkg");
4979 }
4980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004981 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004982 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004983 }
4984 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004985 ClipData clip = intent.getClipData();
4986 if (data == null && clip == null) {
4987 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004988 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004989 if (data != null) {
4990 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
4991 mode, needed != null ? needed.targetUid : -1);
4992 if (target > 0) {
4993 if (needed == null) {
4994 needed = new NeededUriGrants(targetPkg, target, mode);
4995 }
4996 needed.add(data);
4997 }
4998 }
4999 if (clip != null) {
5000 for (int i=0; i<clip.getItemCount(); i++) {
5001 Uri uri = clip.getItemAt(i).getUri();
5002 if (uri != null) {
5003 int target = -1;
5004 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5005 mode, needed != null ? needed.targetUid : -1);
5006 if (target > 0) {
5007 if (needed == null) {
5008 needed = new NeededUriGrants(targetPkg, target, mode);
5009 }
5010 needed.add(uri);
5011 }
5012 } else {
5013 Intent clipIntent = clip.getItemAt(i).getIntent();
5014 if (clipIntent != null) {
5015 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5016 callingUid, targetPkg, clipIntent, mode, needed);
5017 if (newNeeded != null) {
5018 needed = newNeeded;
5019 }
5020 }
5021 }
5022 }
5023 }
5024
5025 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005026 }
5027
5028 /**
5029 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5030 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005031 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5032 UriPermissionOwner owner) {
5033 if (needed != null) {
5034 for (int i=0; i<needed.size(); i++) {
5035 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5036 needed.get(i), needed.flags, owner);
5037 }
5038 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005039 }
5040
5041 void grantUriPermissionFromIntentLocked(int callingUid,
5042 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005043 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005044 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005045 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 return;
5047 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005048
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005049 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005050 }
5051
5052 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5053 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005054 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005055 synchronized(this) {
5056 final ProcessRecord r = getRecordForAppLocked(caller);
5057 if (r == null) {
5058 throw new SecurityException("Unable to find app for caller "
5059 + caller
5060 + " when granting permission to uri " + uri);
5061 }
5062 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005063 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005064 }
5065 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005066 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 }
5068
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005069 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005070 null);
5071 }
5072 }
5073
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005074 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5076 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5077 HashMap<Uri, UriPermission> perms
5078 = mGrantedUriPermissions.get(perm.uid);
5079 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005080 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005081 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 perms.remove(perm.uri);
5083 if (perms.size() == 0) {
5084 mGrantedUriPermissions.remove(perm.uid);
5085 }
5086 }
5087 }
5088 }
5089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005090 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5091 int modeFlags) {
5092 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5093 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5094 if (modeFlags == 0) {
5095 return;
5096 }
5097
Joe Onorato8a9b2202010-02-26 18:56:32 -08005098 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005099 "Revoking all granted permissions to " + uri);
5100
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005101 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005102
5103 final String authority = uri.getAuthority();
5104 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005105 int userId = UserId.getUserId(callingUid);
5106 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005107 if (cpr != null) {
5108 pi = cpr.info;
5109 } else {
5110 try {
5111 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005112 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005113 } catch (RemoteException ex) {
5114 }
5115 }
5116 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005117 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005118 return;
5119 }
5120
5121 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005122 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 // Right now, if you are not the original owner of the permission,
5124 // you are not allowed to revoke it.
5125 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5126 throw new SecurityException("Uid " + callingUid
5127 + " does not have permission to uri " + uri);
5128 //}
5129 }
5130
5131 // Go through all of the permissions and remove any that match.
5132 final List<String> SEGMENTS = uri.getPathSegments();
5133 if (SEGMENTS != null) {
5134 final int NS = SEGMENTS.size();
5135 int N = mGrantedUriPermissions.size();
5136 for (int i=0; i<N; i++) {
5137 HashMap<Uri, UriPermission> perms
5138 = mGrantedUriPermissions.valueAt(i);
5139 Iterator<UriPermission> it = perms.values().iterator();
5140 toploop:
5141 while (it.hasNext()) {
5142 UriPermission perm = it.next();
5143 Uri targetUri = perm.uri;
5144 if (!authority.equals(targetUri.getAuthority())) {
5145 continue;
5146 }
5147 List<String> targetSegments = targetUri.getPathSegments();
5148 if (targetSegments == null) {
5149 continue;
5150 }
5151 if (targetSegments.size() < NS) {
5152 continue;
5153 }
5154 for (int j=0; j<NS; j++) {
5155 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5156 continue toploop;
5157 }
5158 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005159 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005160 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 perm.clearModes(modeFlags);
5162 if (perm.modeFlags == 0) {
5163 it.remove();
5164 }
5165 }
5166 if (perms.size() == 0) {
5167 mGrantedUriPermissions.remove(
5168 mGrantedUriPermissions.keyAt(i));
5169 N--;
5170 i--;
5171 }
5172 }
5173 }
5174 }
5175
5176 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5177 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005178 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005179 synchronized(this) {
5180 final ProcessRecord r = getRecordForAppLocked(caller);
5181 if (r == null) {
5182 throw new SecurityException("Unable to find app for caller "
5183 + caller
5184 + " when revoking permission to uri " + uri);
5185 }
5186 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005187 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 return;
5189 }
5190
5191 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5192 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5193 if (modeFlags == 0) {
5194 return;
5195 }
5196
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005197 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198
5199 final String authority = uri.getAuthority();
5200 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005201 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005202 if (cpr != null) {
5203 pi = cpr.info;
5204 } else {
5205 try {
5206 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005207 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005208 } catch (RemoteException ex) {
5209 }
5210 }
5211 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005212 Slog.w(TAG, "No content provider found for permission revoke: "
5213 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005214 return;
5215 }
5216
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005217 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 }
5219 }
5220
Dianne Hackborn7e269642010-08-25 19:50:20 -07005221 @Override
5222 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005223 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005224 synchronized(this) {
5225 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5226 return owner.getExternalTokenLocked();
5227 }
5228 }
5229
5230 @Override
5231 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5232 Uri uri, int modeFlags) {
5233 synchronized(this) {
5234 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5235 if (owner == null) {
5236 throw new IllegalArgumentException("Unknown owner: " + token);
5237 }
5238 if (fromUid != Binder.getCallingUid()) {
5239 if (Binder.getCallingUid() != Process.myUid()) {
5240 // Only system code can grant URI permissions on behalf
5241 // of other users.
5242 throw new SecurityException("nice try");
5243 }
5244 }
5245 if (targetPkg == null) {
5246 throw new IllegalArgumentException("null target");
5247 }
5248 if (uri == null) {
5249 throw new IllegalArgumentException("null uri");
5250 }
5251
5252 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5253 }
5254 }
5255
5256 @Override
5257 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5258 synchronized(this) {
5259 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5260 if (owner == null) {
5261 throw new IllegalArgumentException("Unknown owner: " + token);
5262 }
5263
5264 if (uri == null) {
5265 owner.removeUriPermissionsLocked(mode);
5266 } else {
5267 owner.removeUriPermissionLocked(uri, mode);
5268 }
5269 }
5270 }
5271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5273 synchronized (this) {
5274 ProcessRecord app =
5275 who != null ? getRecordForAppLocked(who) : null;
5276 if (app == null) return;
5277
5278 Message msg = Message.obtain();
5279 msg.what = WAIT_FOR_DEBUGGER_MSG;
5280 msg.obj = app;
5281 msg.arg1 = waiting ? 1 : 0;
5282 mHandler.sendMessage(msg);
5283 }
5284 }
5285
5286 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005287 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5288 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005289 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005290 outInfo.threshold = homeAppMem;
5291 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5292 outInfo.hiddenAppThreshold = hiddenAppMem;
5293 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005294 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005295 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5296 ProcessList.VISIBLE_APP_ADJ);
5297 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5298 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005299 }
5300
5301 // =========================================================
5302 // TASK MANAGEMENT
5303 // =========================================================
5304
5305 public List getTasks(int maxNum, int flags,
5306 IThumbnailReceiver receiver) {
5307 ArrayList list = new ArrayList();
5308
5309 PendingThumbnailsRecord pending = null;
5310 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005311 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312
5313 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005314 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5316 + ", receiver=" + receiver);
5317
5318 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5319 != PackageManager.PERMISSION_GRANTED) {
5320 if (receiver != null) {
5321 // If the caller wants to wait for pending thumbnails,
5322 // it ain't gonna get them.
5323 try {
5324 receiver.finished();
5325 } catch (RemoteException ex) {
5326 }
5327 }
5328 String msg = "Permission Denial: getTasks() from pid="
5329 + Binder.getCallingPid()
5330 + ", uid=" + Binder.getCallingUid()
5331 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005332 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 throw new SecurityException(msg);
5334 }
5335
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005336 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005337 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005338 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005339 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340 TaskRecord curTask = null;
5341 int numActivities = 0;
5342 int numRunning = 0;
5343 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005344 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005345 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005346 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005347
5348 // Initialize state for next task if needed.
5349 if (top == null ||
5350 (top.state == ActivityState.INITIALIZING
5351 && top.task == r.task)) {
5352 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353 curTask = r.task;
5354 numActivities = numRunning = 0;
5355 }
5356
5357 // Add 'r' into the current task.
5358 numActivities++;
5359 if (r.app != null && r.app.thread != null) {
5360 numRunning++;
5361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362
Joe Onorato8a9b2202010-02-26 18:56:32 -08005363 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 TAG, r.intent.getComponent().flattenToShortString()
5365 + ": task=" + r.task);
5366
5367 // If the next one is a different task, generate a new
5368 // TaskInfo entry for what we have.
5369 if (next == null || next.task != curTask) {
5370 ActivityManager.RunningTaskInfo ci
5371 = new ActivityManager.RunningTaskInfo();
5372 ci.id = curTask.taskId;
5373 ci.baseActivity = r.intent.getComponent();
5374 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005375 if (top.thumbHolder != null) {
5376 ci.description = top.thumbHolder.lastDescription;
5377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005378 ci.numActivities = numActivities;
5379 ci.numRunning = numRunning;
5380 //System.out.println(
5381 // "#" + maxNum + ": " + " descr=" + ci.description);
5382 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005383 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 TAG, "State=" + top.state + "Idle=" + top.idle
5385 + " app=" + top.app
5386 + " thr=" + (top.app != null ? top.app.thread : null));
5387 if (top.state == ActivityState.RESUMED
5388 || top.state == ActivityState.PAUSING) {
5389 if (top.idle && top.app != null
5390 && top.app.thread != null) {
5391 topRecord = top;
5392 topThumbnail = top.app.thread;
5393 } else {
5394 top.thumbnailNeeded = true;
5395 }
5396 }
5397 if (pending == null) {
5398 pending = new PendingThumbnailsRecord(receiver);
5399 }
5400 pending.pendingRecords.add(top);
5401 }
5402 list.add(ci);
5403 maxNum--;
5404 top = null;
5405 }
5406 }
5407
5408 if (pending != null) {
5409 mPendingThumbnails.add(pending);
5410 }
5411 }
5412
Joe Onorato8a9b2202010-02-26 18:56:32 -08005413 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414
5415 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005416 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005417 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005418 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005419 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005420 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005421 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005422 }
5423 }
5424
5425 if (pending == null && receiver != null) {
5426 // In this case all thumbnails were available and the client
5427 // is being asked to be told when the remaining ones come in...
5428 // which is unusually, since the top-most currently running
5429 // activity should never have a canned thumbnail! Oh well.
5430 try {
5431 receiver.finished();
5432 } catch (RemoteException ex) {
5433 }
5434 }
5435
5436 return list;
5437 }
5438
5439 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5440 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005441 final int callingUid = Binder.getCallingUid();
5442 // If it's the system uid asking, then use the current user id.
5443 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5444 // require the entire list.
5445 final int callingUserId = callingUid == Process.SYSTEM_UID
5446 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 synchronized (this) {
5448 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5449 "getRecentTasks()");
5450
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005451 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005453 final int N = mRecentTasks.size();
5454 ArrayList<ActivityManager.RecentTaskInfo> res
5455 = new ArrayList<ActivityManager.RecentTaskInfo>(
5456 maxNum < N ? maxNum : N);
5457 for (int i=0; i<N && maxNum > 0; i++) {
5458 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005459 // Only add calling user's recent tasks
5460 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005461 // Return the entry if desired by the caller. We always return
5462 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005463 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005464 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5465 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005466
Dianne Hackborn905577f2011-09-07 18:31:28 -07005467 if (i == 0
5468 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 || (tr.intent == null)
5470 || ((tr.intent.getFlags()
5471 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5472 ActivityManager.RecentTaskInfo rti
5473 = new ActivityManager.RecentTaskInfo();
5474 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005475 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 rti.baseIntent = new Intent(
5477 tr.intent != null ? tr.intent : tr.affinityIntent);
5478 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005479 rti.description = tr.lastDescription;
5480
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005481 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5482 // Check whether this activity is currently available.
5483 try {
5484 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005485 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5486 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005487 continue;
5488 }
5489 } else if (rti.baseIntent != null) {
5490 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005491 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005492 continue;
5493 }
5494 }
5495 } catch (RemoteException e) {
5496 // Will never happen.
5497 }
5498 }
5499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 res.add(rti);
5501 maxNum--;
5502 }
5503 }
5504 return res;
5505 }
5506 }
5507
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005508 private TaskRecord taskForIdLocked(int id) {
5509 final int N = mRecentTasks.size();
5510 for (int i=0; i<N; i++) {
5511 TaskRecord tr = mRecentTasks.get(i);
5512 if (tr.taskId == id) {
5513 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005514 }
5515 }
5516 return null;
5517 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005518
5519 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5520 synchronized (this) {
5521 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5522 "getTaskThumbnails()");
5523 TaskRecord tr = taskForIdLocked(id);
5524 if (tr != null) {
5525 return mMainStack.getTaskThumbnailsLocked(tr);
5526 }
5527 }
5528 return null;
5529 }
5530
5531 public boolean removeSubTask(int taskId, int subTaskIndex) {
5532 synchronized (this) {
5533 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5534 "removeSubTask()");
5535 long ident = Binder.clearCallingIdentity();
5536 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005537 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5538 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005539 } finally {
5540 Binder.restoreCallingIdentity(ident);
5541 }
5542 }
5543 }
5544
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005545 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5546 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005547 Intent baseIntent = new Intent(
5548 tr.intent != null ? tr.intent : tr.affinityIntent);
5549 ComponentName component = baseIntent.getComponent();
5550 if (component == null) {
5551 Slog.w(TAG, "Now component for base intent of task: " + tr);
5552 return;
5553 }
5554
5555 // Find any running services associated with this app.
5556 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005557 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005558 if (sr.packageName.equals(component.getPackageName())) {
5559 services.add(sr);
5560 }
5561 }
5562
5563 // Take care of any running services associated with the app.
5564 for (int i=0; i<services.size(); i++) {
5565 ServiceRecord sr = services.get(i);
5566 if (sr.startRequested) {
5567 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005568 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005569 stopServiceLocked(sr);
5570 } else {
5571 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005572 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005573 if (sr.app != null && sr.app.thread != null) {
5574 sendServiceArgsLocked(sr, false);
5575 }
5576 }
5577 }
5578 }
5579
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005580 if (killProcesses) {
5581 // Find any running processes associated with this app.
5582 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5583 SparseArray<ProcessRecord> appProcs
5584 = mProcessNames.getMap().get(component.getPackageName());
5585 if (appProcs != null) {
5586 for (int i=0; i<appProcs.size(); i++) {
5587 procs.add(appProcs.valueAt(i));
5588 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005589 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005590
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005591 // Kill the running processes.
5592 for (int i=0; i<procs.size(); i++) {
5593 ProcessRecord pr = procs.get(i);
5594 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5595 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5596 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5597 pr.processName, pr.setAdj, "remove task");
5598 Process.killProcessQuiet(pr.pid);
5599 } else {
5600 pr.waitingToKill = "remove task";
5601 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005602 }
5603 }
5604 }
5605
5606 public boolean removeTask(int taskId, int flags) {
5607 synchronized (this) {
5608 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5609 "removeTask()");
5610 long ident = Binder.clearCallingIdentity();
5611 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005612 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5613 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005614 if (r != null) {
5615 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005616 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005617 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005618 } else {
5619 TaskRecord tr = null;
5620 int i=0;
5621 while (i < mRecentTasks.size()) {
5622 TaskRecord t = mRecentTasks.get(i);
5623 if (t.taskId == taskId) {
5624 tr = t;
5625 break;
5626 }
5627 i++;
5628 }
5629 if (tr != null) {
5630 if (tr.numActivities <= 0) {
5631 // Caller is just removing a recent task that is
5632 // not actively running. That is easy!
5633 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005634 cleanUpRemovedTaskLocked(tr, flags);
5635 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005636 } else {
5637 Slog.w(TAG, "removeTask: task " + taskId
5638 + " does not have activities to remove, "
5639 + " but numActivities=" + tr.numActivities
5640 + ": " + tr);
5641 }
5642 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005643 }
5644 } finally {
5645 Binder.restoreCallingIdentity(ident);
5646 }
5647 }
5648 return false;
5649 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5652 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005653 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 TaskRecord jt = startTask;
5655
5656 // First look backwards
5657 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005658 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 if (r.task != jt) {
5660 jt = r.task;
5661 if (affinity.equals(jt.affinity)) {
5662 return j;
5663 }
5664 }
5665 }
5666
5667 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005668 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 jt = startTask;
5670 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005671 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 if (r.task != jt) {
5673 if (affinity.equals(jt.affinity)) {
5674 return j;
5675 }
5676 jt = r.task;
5677 }
5678 }
5679
5680 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005681 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 return N-1;
5683 }
5684
5685 return -1;
5686 }
5687
5688 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005689 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005691 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5693 "moveTaskToFront()");
5694
5695 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005696 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5697 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005698 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005699 return;
5700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 final long origId = Binder.clearCallingIdentity();
5702 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 TaskRecord tr = taskForIdLocked(task);
5704 if (tr != null) {
5705 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5706 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005708 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5709 // Caller wants the home activity moved with it. To accomplish this,
5710 // we'll just move the home task to the top first.
5711 mMainStack.moveHomeToFrontLocked();
5712 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005713 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005714 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005716 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5717 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005719 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5720 mMainStack.mUserLeaving = true;
5721 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005722 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5723 // Caller wants the home activity moved with it. To accomplish this,
5724 // we'll just move the home task to the top first.
5725 mMainStack.moveHomeToFrontLocked();
5726 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005727 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005728 return;
5729 }
5730 }
5731 } finally {
5732 Binder.restoreCallingIdentity(origId);
5733 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005734 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 }
5736 }
5737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 public void moveTaskToBack(int task) {
5739 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5740 "moveTaskToBack()");
5741
5742 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005743 if (mMainStack.mResumedActivity != null
5744 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005745 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5746 Binder.getCallingUid(), "Task to back")) {
5747 return;
5748 }
5749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005751 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 Binder.restoreCallingIdentity(origId);
5753 }
5754 }
5755
5756 /**
5757 * Moves an activity, and all of the other activities within the same task, to the bottom
5758 * of the history stack. The activity's order within the task is unchanged.
5759 *
5760 * @param token A reference to the activity we wish to move
5761 * @param nonRoot If false then this only works if the activity is the root
5762 * of a task; if true it will work for any activity in a task.
5763 * @return Returns true if the move completed, false if not.
5764 */
5765 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005766 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005767 synchronized(this) {
5768 final long origId = Binder.clearCallingIdentity();
5769 int taskId = getTaskForActivityLocked(token, !nonRoot);
5770 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005771 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005772 }
5773 Binder.restoreCallingIdentity(origId);
5774 }
5775 return false;
5776 }
5777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 public void moveTaskBackwards(int task) {
5779 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5780 "moveTaskBackwards()");
5781
5782 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005783 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5784 Binder.getCallingUid(), "Task backwards")) {
5785 return;
5786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 final long origId = Binder.clearCallingIdentity();
5788 moveTaskBackwardsLocked(task);
5789 Binder.restoreCallingIdentity(origId);
5790 }
5791 }
5792
5793 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005794 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 }
5796
5797 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5798 synchronized(this) {
5799 return getTaskForActivityLocked(token, onlyRoot);
5800 }
5801 }
5802
5803 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005804 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005805 TaskRecord lastTask = null;
5806 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005807 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005808 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 if (!onlyRoot || lastTask != r.task) {
5810 return r.task.taskId;
5811 }
5812 return -1;
5813 }
5814 lastTask = r.task;
5815 }
5816
5817 return -1;
5818 }
5819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 // =========================================================
5821 // THUMBNAILS
5822 // =========================================================
5823
5824 public void reportThumbnail(IBinder token,
5825 Bitmap thumbnail, CharSequence description) {
5826 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5827 final long origId = Binder.clearCallingIdentity();
5828 sendPendingThumbnail(null, token, thumbnail, description, true);
5829 Binder.restoreCallingIdentity(origId);
5830 }
5831
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005832 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 Bitmap thumbnail, CharSequence description, boolean always) {
5834 TaskRecord task = null;
5835 ArrayList receivers = null;
5836
5837 //System.out.println("Send pending thumbnail: " + r);
5838
5839 synchronized(this) {
5840 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005841 r = mMainStack.isInStackLocked(token);
5842 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 return;
5844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005846 if (thumbnail == null && r.thumbHolder != null) {
5847 thumbnail = r.thumbHolder.lastThumbnail;
5848 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
5850 if (thumbnail == null && !always) {
5851 // If there is no thumbnail, and this entry is not actually
5852 // going away, then abort for now and pick up the next
5853 // thumbnail we get.
5854 return;
5855 }
5856 task = r.task;
5857
5858 int N = mPendingThumbnails.size();
5859 int i=0;
5860 while (i<N) {
5861 PendingThumbnailsRecord pr =
5862 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5863 //System.out.println("Looking in " + pr.pendingRecords);
5864 if (pr.pendingRecords.remove(r)) {
5865 if (receivers == null) {
5866 receivers = new ArrayList();
5867 }
5868 receivers.add(pr);
5869 if (pr.pendingRecords.size() == 0) {
5870 pr.finished = true;
5871 mPendingThumbnails.remove(i);
5872 N--;
5873 continue;
5874 }
5875 }
5876 i++;
5877 }
5878 }
5879
5880 if (receivers != null) {
5881 final int N = receivers.size();
5882 for (int i=0; i<N; i++) {
5883 try {
5884 PendingThumbnailsRecord pr =
5885 (PendingThumbnailsRecord)receivers.get(i);
5886 pr.receiver.newThumbnail(
5887 task != null ? task.taskId : -1, thumbnail, description);
5888 if (pr.finished) {
5889 pr.receiver.finished();
5890 }
5891 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005892 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
5894 }
5895 }
5896 }
5897
5898 // =========================================================
5899 // CONTENT PROVIDERS
5900 // =========================================================
5901
Jeff Brown10e89712011-07-08 18:52:57 -07005902 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5903 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005904 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005905 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005906 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005907 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005908 } catch (RemoteException ex) {
5909 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005910 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005911 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5912 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 if (providers != null) {
5914 final int N = providers.size();
5915 for (int i=0; i<N; i++) {
5916 ProviderInfo cpi =
5917 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005918
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005919 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005920 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005922 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005923 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005924 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005925 if (DEBUG_MU)
5926 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 app.pubProviders.put(cpi.name, cpr);
5928 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005929 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 }
5931 }
5932 return providers;
5933 }
5934
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005935 /**
5936 * Check if {@link ProcessRecord} has a possible chance at accessing the
5937 * given {@link ProviderInfo}. Final permission checking is always done
5938 * in {@link ContentProvider}.
5939 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005941 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005943 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005945 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005946 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 return null;
5948 }
5949 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005950 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 == PackageManager.PERMISSION_GRANTED) {
5952 return null;
5953 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005954
5955 PathPermission[] pps = cpi.pathPermissions;
5956 if (pps != null) {
5957 int i = pps.length;
5958 while (i > 0) {
5959 i--;
5960 PathPermission pp = pps[i];
5961 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005962 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005963 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005964 return null;
5965 }
5966 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005967 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005968 == PackageManager.PERMISSION_GRANTED) {
5969 return null;
5970 }
5971 }
5972 }
5973
Dianne Hackbornb424b632010-08-18 15:59:05 -07005974 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5975 if (perms != null) {
5976 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5977 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5978 return null;
5979 }
5980 }
5981 }
5982
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005983 String msg;
5984 if (!cpi.exported) {
5985 msg = "Permission Denial: opening provider " + cpi.name
5986 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5987 + ", uid=" + callingUid + ") that is not exported from uid "
5988 + cpi.applicationInfo.uid;
5989 } else {
5990 msg = "Permission Denial: opening provider " + cpi.name
5991 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
5992 + ", uid=" + callingUid + ") requires "
5993 + cpi.readPermission + " or " + cpi.writePermission;
5994 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005995 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 return msg;
5997 }
5998
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005999 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6000 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006001 if (r != null) {
6002 Integer cnt = r.conProviders.get(cpr);
6003 if (DEBUG_PROVIDER) Slog.v(TAG,
6004 "Adding provider requested by "
6005 + r.processName + " from process "
6006 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6007 + " cnt=" + (cnt == null ? 1 : cnt));
6008 if (cnt == null) {
6009 cpr.clients.add(r);
6010 r.conProviders.put(cpr, new Integer(1));
6011 return true;
6012 } else {
6013 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6014 }
6015 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006016 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006017 }
6018 return false;
6019 }
6020
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006021 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6022 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006023 if (r != null) {
6024 Integer cnt = r.conProviders.get(cpr);
6025 if (DEBUG_PROVIDER) Slog.v(TAG,
6026 "Removing provider requested by "
6027 + r.processName + " from process "
6028 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6029 + " cnt=" + cnt);
6030 if (cnt == null || cnt.intValue() <= 1) {
6031 cpr.clients.remove(r);
6032 r.conProviders.remove(cpr);
6033 return true;
6034 } else {
6035 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6036 }
6037 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006038 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006039 }
6040 return false;
6041 }
6042
Amith Yamasani742a6712011-05-04 14:49:28 -07006043 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006044 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 ContentProviderRecord cpr;
6046 ProviderInfo cpi = null;
6047
6048 synchronized(this) {
6049 ProcessRecord r = null;
6050 if (caller != null) {
6051 r = getRecordForAppLocked(caller);
6052 if (r == null) {
6053 throw new SecurityException(
6054 "Unable to find app for caller " + caller
6055 + " (pid=" + Binder.getCallingPid()
6056 + ") when getting content provider " + name);
6057 }
6058 }
6059
6060 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006061 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006062 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006063 boolean providerRunning = cpr != null;
6064 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006066 String msg;
6067 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6068 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 }
6070
6071 if (r != null && cpr.canRunHere(r)) {
6072 // This provider has been published or is in the process
6073 // of being published... but it is also allowed to run
6074 // in the caller's process, so don't make a connection
6075 // and just let the caller instantiate its own instance.
6076 if (cpr.provider != null) {
6077 // don't give caller the provider object, it needs
6078 // to make its own.
6079 cpr = new ContentProviderRecord(cpr);
6080 }
6081 return cpr;
6082 }
6083
6084 final long origId = Binder.clearCallingIdentity();
6085
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006086 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006088 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006089 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006090 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006091 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006092 // make sure to count it as being accessed and thus
6093 // back up on the LRU list. This is good because
6094 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006095 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006096 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006097 }
6098
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006099 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006100 if (false) {
6101 if (cpr.name.flattenToShortString().equals(
6102 "com.android.providers.calendar/.CalendarProvider2")) {
6103 Slog.v(TAG, "****************** KILLING "
6104 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006105 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006106 }
6107 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006108 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006109 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6110 // NOTE: there is still a race here where a signal could be
6111 // pending on the process even though we managed to update its
6112 // adj level. Not sure what to do about this, but at least
6113 // the race is now smaller.
6114 if (!success) {
6115 // Uh oh... it looks like the provider's process
6116 // has been killed on us. We need to wait for a new
6117 // process to be started, and make sure its death
6118 // doesn't kill our process.
6119 Slog.i(TAG,
6120 "Existing provider " + cpr.name.flattenToShortString()
6121 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006122 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006123 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006124 if (!lastRef) {
6125 // This wasn't the last ref our process had on
6126 // the provider... we have now been killed, bail.
6127 return null;
6128 }
6129 providerRunning = false;
6130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132
6133 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006136 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006138 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006139 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006140 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 } catch (RemoteException ex) {
6142 }
6143 if (cpi == null) {
6144 return null;
6145 }
6146
Amith Yamasani483f3b02012-03-13 16:08:00 -07006147 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006148
Dianne Hackbornb424b632010-08-18 15:59:05 -07006149 String msg;
6150 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6151 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 }
6153
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006154 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006155 && !cpi.processName.equals("system")) {
6156 // If this content provider does not run in the system
6157 // process, and the system is not yet ready to run other
6158 // processes, then fail fast instead of hanging.
6159 throw new IllegalArgumentException(
6160 "Attempt to launch content provider before system ready");
6161 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006162
6163 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006164 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006165 final boolean firstClass = cpr == null;
6166 if (firstClass) {
6167 try {
6168 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006169 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 getApplicationInfo(
6171 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006172 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006174 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 + cpi.name);
6176 return null;
6177 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006178 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006179 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 } catch (RemoteException ex) {
6181 // pm is in same process, this will never happen.
6182 }
6183 }
6184
6185 if (r != null && cpr.canRunHere(r)) {
6186 // If this is a multiprocess provider, then just return its
6187 // info and allow the caller to instantiate it. Only do
6188 // this if the provider is the same user as the caller's
6189 // process, or can run as root (so can be in any process).
6190 return cpr;
6191 }
6192
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006193 if (DEBUG_PROVIDER) {
6194 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006195 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006196 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198
6199 // This is single process, and our app is now connecting to it.
6200 // See if we are already in the process of launching this
6201 // provider.
6202 final int N = mLaunchingProviders.size();
6203 int i;
6204 for (i=0; i<N; i++) {
6205 if (mLaunchingProviders.get(i) == cpr) {
6206 break;
6207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 }
6209
6210 // If the provider is not already being launched, then get it
6211 // started.
6212 if (i >= N) {
6213 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006214
6215 try {
6216 // Content provider is now in use, its package can't be stopped.
6217 try {
6218 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006219 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006220 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006221 } catch (IllegalArgumentException e) {
6222 Slog.w(TAG, "Failed trying to unstop package "
6223 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006224 }
6225
6226 ProcessRecord proc = startProcessLocked(cpi.processName,
6227 cpr.appInfo, false, 0, "content provider",
6228 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006229 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006230 if (proc == null) {
6231 Slog.w(TAG, "Unable to launch app "
6232 + cpi.applicationInfo.packageName + "/"
6233 + cpi.applicationInfo.uid + " for provider "
6234 + name + ": process is bad");
6235 return null;
6236 }
6237 cpr.launchingApp = proc;
6238 mLaunchingProviders.add(cpr);
6239 } finally {
6240 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 }
6243
6244 // Make sure the provider is published (the same provider class
6245 // may be published under multiple names).
6246 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006247 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006249
Amith Yamasani742a6712011-05-04 14:49:28 -07006250 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006251 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
6253 }
6254
6255 // Wait for the provider to be published...
6256 synchronized (cpr) {
6257 while (cpr.provider == null) {
6258 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006259 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 + cpi.applicationInfo.packageName + "/"
6261 + cpi.applicationInfo.uid + " for provider "
6262 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006263 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 cpi.applicationInfo.packageName,
6265 cpi.applicationInfo.uid, name);
6266 return null;
6267 }
6268 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006269 if (DEBUG_MU) {
6270 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6271 + cpr.launchingApp);
6272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 cpr.wait();
6274 } catch (InterruptedException ex) {
6275 }
6276 }
6277 }
6278 return cpr;
6279 }
6280
6281 public final ContentProviderHolder getContentProvider(
6282 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006283 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 if (caller == null) {
6285 String msg = "null IApplicationThread when getting content provider "
6286 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006287 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 throw new SecurityException(msg);
6289 }
6290
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006291 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 }
6293
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006294 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6295 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6296 "Do not have permission in call getContentProviderExternal()");
6297 return getContentProviderExternalUnchecked(name, token);
6298 }
6299
6300 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6301 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 }
6303
6304 /**
6305 * Drop a content provider from a ProcessRecord's bookkeeping
6306 * @param cpr
6307 */
6308 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006309 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006311 int userId = UserId.getUserId(Binder.getCallingUid());
6312 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006314 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006315 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006316 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 return;
6318 }
6319 final ProcessRecord r = getRecordForAppLocked(caller);
6320 if (r == null) {
6321 throw new SecurityException(
6322 "Unable to find app for caller " + caller +
6323 " when removing content provider " + name);
6324 }
6325 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006326 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006327 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6328 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6329 + r.info.processName + " from process "
6330 + localCpr.appInfo.processName);
6331 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006333 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006334 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 return;
6336 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006337 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006338 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 }
6342 }
6343
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006344 public void removeContentProviderExternal(String name, IBinder token) {
6345 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6346 "Do not have permission in call removeContentProviderExternal()");
6347 removeContentProviderExternalUnchecked(name, token);
6348 }
6349
6350 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006352 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6353 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 if(cpr == null) {
6355 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006356 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 return;
6358 }
6359
6360 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006361 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006362 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6363 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006364 if (localCpr.hasExternalProcessHandles()) {
6365 if (localCpr.removeExternalProcessHandleLocked(token)) {
6366 updateOomAdjLocked();
6367 } else {
6368 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6369 + " with no external reference for token: "
6370 + token + ".");
6371 }
6372 } else {
6373 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6374 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 }
6377 }
6378
6379 public final void publishContentProviders(IApplicationThread caller,
6380 List<ContentProviderHolder> providers) {
6381 if (providers == null) {
6382 return;
6383 }
6384
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006385 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 synchronized(this) {
6387 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006388 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006389 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 if (r == null) {
6391 throw new SecurityException(
6392 "Unable to find app for caller " + caller
6393 + " (pid=" + Binder.getCallingPid()
6394 + ") when publishing content providers");
6395 }
6396
6397 final long origId = Binder.clearCallingIdentity();
6398
6399 final int N = providers.size();
6400 for (int i=0; i<N; i++) {
6401 ContentProviderHolder src = providers.get(i);
6402 if (src == null || src.info == null || src.provider == null) {
6403 continue;
6404 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006405 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 if (DEBUG_MU)
6407 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006409 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006410 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 String names[] = dst.info.authority.split(";");
6412 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006413 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 }
6415
6416 int NL = mLaunchingProviders.size();
6417 int j;
6418 for (j=0; j<NL; j++) {
6419 if (mLaunchingProviders.get(j) == dst) {
6420 mLaunchingProviders.remove(j);
6421 j--;
6422 NL--;
6423 }
6424 }
6425 synchronized (dst) {
6426 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006427 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 dst.notifyAll();
6429 }
6430 updateOomAdjLocked(r);
6431 }
6432 }
6433
6434 Binder.restoreCallingIdentity(origId);
6435 }
6436 }
6437
6438 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006439 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006440 synchronized (mSelf) {
6441 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6442 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006443 if (providers != null) {
6444 for (int i=providers.size()-1; i>=0; i--) {
6445 ProviderInfo pi = (ProviderInfo)providers.get(i);
6446 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6447 Slog.w(TAG, "Not installing system proc provider " + pi.name
6448 + ": not system .apk");
6449 providers.remove(i);
6450 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006451 }
6452 }
6453 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006454 if (providers != null) {
6455 mSystemThread.installSystemProviders(providers);
6456 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006457
6458 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006459
6460 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 }
6462
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006463 /**
6464 * Allows app to retrieve the MIME type of a URI without having permission
6465 * to access its content provider.
6466 *
6467 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6468 *
6469 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6470 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6471 */
6472 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006473 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006474 final String name = uri.getAuthority();
6475 final long ident = Binder.clearCallingIdentity();
6476 ContentProviderHolder holder = null;
6477
6478 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006479 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006480 if (holder != null) {
6481 return holder.provider.getType(uri);
6482 }
6483 } catch (RemoteException e) {
6484 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6485 return null;
6486 } finally {
6487 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006488 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006489 }
6490 Binder.restoreCallingIdentity(ident);
6491 }
6492
6493 return null;
6494 }
6495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 // =========================================================
6497 // GLOBAL MANAGEMENT
6498 // =========================================================
6499
6500 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006501 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 String proc = customProcess != null ? customProcess : info.processName;
6503 BatteryStatsImpl.Uid.Proc ps = null;
6504 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006505 int uid = info.uid;
6506 if (isolated) {
6507 int userId = UserId.getUserId(uid);
6508 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6509 uid = 0;
6510 while (true) {
6511 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6512 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6513 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6514 }
6515 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6516 mNextIsolatedProcessUid++;
6517 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6518 // No process for this uid, use it.
6519 break;
6520 }
6521 stepsLeft--;
6522 if (stepsLeft <= 0) {
6523 return null;
6524 }
6525 }
6526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 synchronized (stats) {
6528 ps = stats.getProcessStatsLocked(info.uid, proc);
6529 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006530 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006533 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6534 ProcessRecord app;
6535 if (!isolated) {
6536 app = getProcessRecordLocked(info.processName, info.uid);
6537 } else {
6538 app = null;
6539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540
6541 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006542 app = newProcessRecordLocked(null, info, null, isolated);
6543 mProcessNames.put(info.processName, app.uid, app);
6544 if (isolated) {
6545 mIsolatedProcesses.put(app.uid, app);
6546 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006547 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549
Dianne Hackborne7f97212011-02-24 14:40:20 -08006550 // This package really, really can not be stopped.
6551 try {
6552 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006553 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006554 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006555 } catch (IllegalArgumentException e) {
6556 Slog.w(TAG, "Failed trying to unstop package "
6557 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006558 }
6559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6561 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6562 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006563 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 }
6565 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6566 mPersistentStartingProcesses.add(app);
6567 startProcessLocked(app, "added application", app.processName);
6568 }
6569
6570 return app;
6571 }
6572
6573 public void unhandledBack() {
6574 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6575 "unhandledBack()");
6576
6577 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006578 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006579 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 TAG, "Performing unhandledBack(): stack size = " + count);
6581 if (count > 1) {
6582 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006583 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6585 Binder.restoreCallingIdentity(origId);
6586 }
6587 }
6588 }
6589
6590 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006591 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006593 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 ParcelFileDescriptor pfd = null;
6595 if (cph != null) {
6596 // We record the binder invoker's uid in thread-local storage before
6597 // going to the content provider to open the file. Later, in the code
6598 // that handles all permissions checks, we look for this uid and use
6599 // that rather than the Activity Manager's own uid. The effect is that
6600 // we do the check against the caller's permissions even though it looks
6601 // to the content provider like the Activity Manager itself is making
6602 // the request.
6603 sCallerIdentity.set(new Identity(
6604 Binder.getCallingPid(), Binder.getCallingUid()));
6605 try {
6606 pfd = cph.provider.openFile(uri, "r");
6607 } catch (FileNotFoundException e) {
6608 // do nothing; pfd will be returned null
6609 } finally {
6610 // Ensure that whatever happens, we clean up the identity state
6611 sCallerIdentity.remove();
6612 }
6613
6614 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006615 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006617 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006618 }
6619 return pfd;
6620 }
6621
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006622 // Actually is sleeping or shutting down or whatever else in the future
6623 // is an inactive state.
6624 public boolean isSleeping() {
6625 return mSleeping || mShuttingDown;
6626 }
6627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 public void goingToSleep() {
6629 synchronized(this) {
6630 mSleeping = true;
6631 mWindowManager.setEventDispatching(false);
6632
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006633 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006634
6635 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006636 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006637 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6638 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006639 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 }
6641 }
6642
Dianne Hackborn55280a92009-05-07 15:53:46 -07006643 public boolean shutdown(int timeout) {
6644 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6645 != PackageManager.PERMISSION_GRANTED) {
6646 throw new SecurityException("Requires permission "
6647 + android.Manifest.permission.SHUTDOWN);
6648 }
6649
6650 boolean timedout = false;
6651
6652 synchronized(this) {
6653 mShuttingDown = true;
6654 mWindowManager.setEventDispatching(false);
6655
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006656 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006657 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006658 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006659 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006660 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006661 long delay = endTime - System.currentTimeMillis();
6662 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006663 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006664 timedout = true;
6665 break;
6666 }
6667 try {
6668 this.wait();
6669 } catch (InterruptedException e) {
6670 }
6671 }
6672 }
6673 }
6674
6675 mUsageStatsService.shutdown();
6676 mBatteryStatsService.shutdown();
6677
6678 return timedout;
6679 }
6680
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006681 public final void activitySlept(IBinder token) {
6682 if (localLOGV) Slog.v(
6683 TAG, "Activity slept: token=" + token);
6684
6685 ActivityRecord r = null;
6686
6687 final long origId = Binder.clearCallingIdentity();
6688
6689 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006690 r = mMainStack.isInStackLocked(token);
6691 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006692 mMainStack.activitySleptLocked(r);
6693 }
6694 }
6695
6696 Binder.restoreCallingIdentity(origId);
6697 }
6698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 public void wakingUp() {
6700 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 mWindowManager.setEventDispatching(true);
6702 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006703 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006704 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 }
6706 }
6707
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006708 public void stopAppSwitches() {
6709 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6710 != PackageManager.PERMISSION_GRANTED) {
6711 throw new SecurityException("Requires permission "
6712 + android.Manifest.permission.STOP_APP_SWITCHES);
6713 }
6714
6715 synchronized(this) {
6716 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6717 + APP_SWITCH_DELAY_TIME;
6718 mDidAppSwitch = false;
6719 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6720 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6721 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6722 }
6723 }
6724
6725 public void resumeAppSwitches() {
6726 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6727 != PackageManager.PERMISSION_GRANTED) {
6728 throw new SecurityException("Requires permission "
6729 + android.Manifest.permission.STOP_APP_SWITCHES);
6730 }
6731
6732 synchronized(this) {
6733 // Note that we don't execute any pending app switches... we will
6734 // let those wait until either the timeout, or the next start
6735 // activity request.
6736 mAppSwitchesAllowedTime = 0;
6737 }
6738 }
6739
6740 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6741 String name) {
6742 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6743 return true;
6744 }
6745
6746 final int perm = checkComponentPermission(
6747 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006748 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006749 if (perm == PackageManager.PERMISSION_GRANTED) {
6750 return true;
6751 }
6752
Joe Onorato8a9b2202010-02-26 18:56:32 -08006753 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006754 return false;
6755 }
6756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 public void setDebugApp(String packageName, boolean waitForDebugger,
6758 boolean persistent) {
6759 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6760 "setDebugApp()");
6761
6762 // Note that this is not really thread safe if there are multiple
6763 // callers into it at the same time, but that's not a situation we
6764 // care about.
6765 if (persistent) {
6766 final ContentResolver resolver = mContext.getContentResolver();
6767 Settings.System.putString(
6768 resolver, Settings.System.DEBUG_APP,
6769 packageName);
6770 Settings.System.putInt(
6771 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6772 waitForDebugger ? 1 : 0);
6773 }
6774
6775 synchronized (this) {
6776 if (!persistent) {
6777 mOrigDebugApp = mDebugApp;
6778 mOrigWaitForDebugger = mWaitForDebugger;
6779 }
6780 mDebugApp = packageName;
6781 mWaitForDebugger = waitForDebugger;
6782 mDebugTransient = !persistent;
6783 if (packageName != null) {
6784 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006785 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 Binder.restoreCallingIdentity(origId);
6787 }
6788 }
6789 }
6790
Siva Velusamy92a8b222012-03-09 16:24:04 -08006791 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6792 synchronized (this) {
6793 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6794 if (!isDebuggable) {
6795 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6796 throw new SecurityException("Process not debuggable: " + app.packageName);
6797 }
6798 }
6799
6800 mOpenGlTraceApp = processName;
6801 }
6802 }
6803
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006804 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6805 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6806 synchronized (this) {
6807 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6808 if (!isDebuggable) {
6809 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6810 throw new SecurityException("Process not debuggable: " + app.packageName);
6811 }
6812 }
6813 mProfileApp = processName;
6814 mProfileFile = profileFile;
6815 if (mProfileFd != null) {
6816 try {
6817 mProfileFd.close();
6818 } catch (IOException e) {
6819 }
6820 mProfileFd = null;
6821 }
6822 mProfileFd = profileFd;
6823 mProfileType = 0;
6824 mAutoStopProfiler = autoStopProfiler;
6825 }
6826 }
6827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006828 public void setAlwaysFinish(boolean enabled) {
6829 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6830 "setAlwaysFinish()");
6831
6832 Settings.System.putInt(
6833 mContext.getContentResolver(),
6834 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6835
6836 synchronized (this) {
6837 mAlwaysFinishActivities = enabled;
6838 }
6839 }
6840
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006841 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006843 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006845 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006846 }
6847 }
6848
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006849 public boolean isUserAMonkey() {
6850 // For now the fact that there is a controller implies
6851 // we have a monkey.
6852 synchronized (this) {
6853 return mController != null;
6854 }
6855 }
6856
Jeff Sharkeya4620792011-05-20 15:29:23 -07006857 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006858 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6859 "registerProcessObserver()");
6860 synchronized (this) {
6861 mProcessObservers.register(observer);
6862 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006863 }
6864
6865 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006866 synchronized (this) {
6867 mProcessObservers.unregister(observer);
6868 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006869 }
6870
Daniel Sandler69a48172010-06-23 16:29:36 -04006871 public void setImmersive(IBinder token, boolean immersive) {
6872 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006873 ActivityRecord r = mMainStack.isInStackLocked(token);
6874 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006875 throw new IllegalArgumentException();
6876 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006877 r.immersive = immersive;
6878 }
6879 }
6880
6881 public boolean isImmersive(IBinder token) {
6882 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006883 ActivityRecord r = mMainStack.isInStackLocked(token);
6884 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006885 throw new IllegalArgumentException();
6886 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006887 return r.immersive;
6888 }
6889 }
6890
6891 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006892 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006893 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006894 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006895 return (r != null) ? r.immersive : false;
6896 }
6897 }
6898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 public final void enterSafeMode() {
6900 synchronized(this) {
6901 // It only makes sense to do this before the system is ready
6902 // and started launching other packages.
6903 if (!mSystemReady) {
6904 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006905 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 } catch (RemoteException e) {
6907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 }
6909 }
6910 }
6911
Jeff Brownb09abc12011-01-13 21:08:27 -08006912 public final void showSafeModeOverlay() {
6913 View v = LayoutInflater.from(mContext).inflate(
6914 com.android.internal.R.layout.safe_mode, null);
6915 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6916 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6917 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6918 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6919 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6920 lp.format = v.getBackground().getOpacity();
6921 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6922 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6923 ((WindowManager)mContext.getSystemService(
6924 Context.WINDOW_SERVICE)).addView(v, lp);
6925 }
6926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 public void noteWakeupAlarm(IIntentSender sender) {
6928 if (!(sender instanceof PendingIntentRecord)) {
6929 return;
6930 }
6931 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6932 synchronized (stats) {
6933 if (mBatteryStatsService.isOnBattery()) {
6934 mBatteryStatsService.enforceCallingPermission();
6935 PendingIntentRecord rec = (PendingIntentRecord)sender;
6936 int MY_UID = Binder.getCallingUid();
6937 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6938 BatteryStatsImpl.Uid.Pkg pkg =
6939 stats.getPackageStatsLocked(uid, rec.key.packageName);
6940 pkg.incWakeupsLocked();
6941 }
6942 }
6943 }
6944
Dianne Hackborn64825172011-03-02 21:32:58 -08006945 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006947 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006949 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006950 // XXX Note: don't acquire main activity lock here, because the window
6951 // manager calls in with its locks held.
6952
6953 boolean killed = false;
6954 synchronized (mPidsSelfLocked) {
6955 int[] types = new int[pids.length];
6956 int worstType = 0;
6957 for (int i=0; i<pids.length; i++) {
6958 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6959 if (proc != null) {
6960 int type = proc.setAdj;
6961 types[i] = type;
6962 if (type > worstType) {
6963 worstType = type;
6964 }
6965 }
6966 }
6967
Dianne Hackborn64825172011-03-02 21:32:58 -08006968 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006970 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6971 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006972 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006974
6975 // If this is not a secure call, don't let it kill processes that
6976 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006977 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6978 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006979 }
6980
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006981 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006982 for (int i=0; i<pids.length; i++) {
6983 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6984 if (proc == null) {
6985 continue;
6986 }
6987 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006988 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07006989 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006990 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
6991 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07006993 proc.killedBackground = true;
6994 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 }
6996 }
6997 }
6998 return killed;
6999 }
7000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 public final void startRunning(String pkg, String cls, String action,
7002 String data) {
7003 synchronized(this) {
7004 if (mStartRunning) {
7005 return;
7006 }
7007 mStartRunning = true;
7008 mTopComponent = pkg != null && cls != null
7009 ? new ComponentName(pkg, cls) : null;
7010 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7011 mTopData = data;
7012 if (!mSystemReady) {
7013 return;
7014 }
7015 }
7016
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007017 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007018 }
7019
7020 private void retrieveSettings() {
7021 final ContentResolver resolver = mContext.getContentResolver();
7022 String debugApp = Settings.System.getString(
7023 resolver, Settings.System.DEBUG_APP);
7024 boolean waitForDebugger = Settings.System.getInt(
7025 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7026 boolean alwaysFinishActivities = Settings.System.getInt(
7027 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7028
7029 Configuration configuration = new Configuration();
7030 Settings.System.getConfiguration(resolver, configuration);
7031
7032 synchronized (this) {
7033 mDebugApp = mOrigDebugApp = debugApp;
7034 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7035 mAlwaysFinishActivities = alwaysFinishActivities;
7036 // This happens before any activities are started, so we can
7037 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007038 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007039 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 }
7041 }
7042
7043 public boolean testIsSystemReady() {
7044 // no need to synchronize(this) just to read & return the value
7045 return mSystemReady;
7046 }
7047
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007048 private static File getCalledPreBootReceiversFile() {
7049 File dataDir = Environment.getDataDirectory();
7050 File systemDir = new File(dataDir, "system");
7051 File fname = new File(systemDir, "called_pre_boots.dat");
7052 return fname;
7053 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007054
7055 static final int LAST_DONE_VERSION = 10000;
7056
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007057 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7058 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7059 File file = getCalledPreBootReceiversFile();
7060 FileInputStream fis = null;
7061 try {
7062 fis = new FileInputStream(file);
7063 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007064 int fvers = dis.readInt();
7065 if (fvers == LAST_DONE_VERSION) {
7066 String vers = dis.readUTF();
7067 String codename = dis.readUTF();
7068 String build = dis.readUTF();
7069 if (android.os.Build.VERSION.RELEASE.equals(vers)
7070 && android.os.Build.VERSION.CODENAME.equals(codename)
7071 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7072 int num = dis.readInt();
7073 while (num > 0) {
7074 num--;
7075 String pkg = dis.readUTF();
7076 String cls = dis.readUTF();
7077 lastDoneReceivers.add(new ComponentName(pkg, cls));
7078 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007079 }
7080 }
7081 } catch (FileNotFoundException e) {
7082 } catch (IOException e) {
7083 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7084 } finally {
7085 if (fis != null) {
7086 try {
7087 fis.close();
7088 } catch (IOException e) {
7089 }
7090 }
7091 }
7092 return lastDoneReceivers;
7093 }
7094
7095 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7096 File file = getCalledPreBootReceiversFile();
7097 FileOutputStream fos = null;
7098 DataOutputStream dos = null;
7099 try {
7100 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7101 fos = new FileOutputStream(file);
7102 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007103 dos.writeInt(LAST_DONE_VERSION);
7104 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007105 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007106 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007107 dos.writeInt(list.size());
7108 for (int i=0; i<list.size(); i++) {
7109 dos.writeUTF(list.get(i).getPackageName());
7110 dos.writeUTF(list.get(i).getClassName());
7111 }
7112 } catch (IOException e) {
7113 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7114 file.delete();
7115 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007116 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007117 if (dos != null) {
7118 try {
7119 dos.close();
7120 } catch (IOException e) {
7121 // TODO Auto-generated catch block
7122 e.printStackTrace();
7123 }
7124 }
7125 }
7126 }
7127
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007128 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 synchronized(this) {
7130 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007131 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 return;
7133 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007134
7135 // Check to see if there are any update receivers to run.
7136 if (!mDidUpdate) {
7137 if (mWaitingUpdate) {
7138 return;
7139 }
7140 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7141 List<ResolveInfo> ris = null;
7142 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007143 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007144 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007145 } catch (RemoteException e) {
7146 }
7147 if (ris != null) {
7148 for (int i=ris.size()-1; i>=0; i--) {
7149 if ((ris.get(i).activityInfo.applicationInfo.flags
7150 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7151 ris.remove(i);
7152 }
7153 }
7154 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007155
7156 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7157
7158 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007159 for (int i=0; i<ris.size(); i++) {
7160 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007161 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7162 if (lastDoneReceivers.contains(comp)) {
7163 ris.remove(i);
7164 i--;
7165 }
7166 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007167
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007168 for (int i=0; i<ris.size(); i++) {
7169 ActivityInfo ai = ris.get(i).activityInfo;
7170 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7171 doneReceivers.add(comp);
7172 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007173 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007174 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007175 finisher = new IIntentReceiver.Stub() {
7176 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007177 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007178 boolean sticky) {
7179 // The raw IIntentReceiver interface is called
7180 // with the AM lock held, so redispatch to
7181 // execute our code without the lock.
7182 mHandler.post(new Runnable() {
7183 public void run() {
7184 synchronized (ActivityManagerService.this) {
7185 mDidUpdate = true;
7186 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007187 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007188 showBootMessage(mContext.getText(
7189 R.string.android_upgrading_complete),
7190 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007191 systemReady(goingCallback);
7192 }
7193 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007194 }
7195 };
7196 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007197 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007198 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007199 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007200 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007201 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007202 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007203 mWaitingUpdate = true;
7204 }
7205 }
7206 }
7207 if (mWaitingUpdate) {
7208 return;
7209 }
7210 mDidUpdate = true;
7211 }
7212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007213 mSystemReady = true;
7214 if (!mStartRunning) {
7215 return;
7216 }
7217 }
7218
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007219 ArrayList<ProcessRecord> procsToKill = null;
7220 synchronized(mPidsSelfLocked) {
7221 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7222 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7223 if (!isAllowedWhileBooting(proc.info)){
7224 if (procsToKill == null) {
7225 procsToKill = new ArrayList<ProcessRecord>();
7226 }
7227 procsToKill.add(proc);
7228 }
7229 }
7230 }
7231
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007232 synchronized(this) {
7233 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007234 for (int i=procsToKill.size()-1; i>=0; i--) {
7235 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007236 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007237 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007238 }
7239 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007240
7241 // Now that we have cleaned up any update processes, we
7242 // are ready to start launching real processes and know that
7243 // we won't trample on them any more.
7244 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007245 }
7246
Joe Onorato8a9b2202010-02-26 18:56:32 -08007247 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007248 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 SystemClock.uptimeMillis());
7250
7251 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007252 // Make sure we have no pre-ready processes sitting around.
7253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7255 ResolveInfo ri = mContext.getPackageManager()
7256 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007257 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 CharSequence errorMsg = null;
7259 if (ri != null) {
7260 ActivityInfo ai = ri.activityInfo;
7261 ApplicationInfo app = ai.applicationInfo;
7262 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7263 mTopAction = Intent.ACTION_FACTORY_TEST;
7264 mTopData = null;
7265 mTopComponent = new ComponentName(app.packageName,
7266 ai.name);
7267 } else {
7268 errorMsg = mContext.getResources().getText(
7269 com.android.internal.R.string.factorytest_not_system);
7270 }
7271 } else {
7272 errorMsg = mContext.getResources().getText(
7273 com.android.internal.R.string.factorytest_no_action);
7274 }
7275 if (errorMsg != null) {
7276 mTopAction = null;
7277 mTopData = null;
7278 mTopComponent = null;
7279 Message msg = Message.obtain();
7280 msg.what = SHOW_FACTORY_ERROR_MSG;
7281 msg.getData().putCharSequence("msg", errorMsg);
7282 mHandler.sendMessage(msg);
7283 }
7284 }
7285 }
7286
7287 retrieveSettings();
7288
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007289 if (goingCallback != null) goingCallback.run();
7290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007291 synchronized (this) {
7292 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7293 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007294 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007295 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 if (apps != null) {
7297 int N = apps.size();
7298 int i;
7299 for (i=0; i<N; i++) {
7300 ApplicationInfo info
7301 = (ApplicationInfo)apps.get(i);
7302 if (info != null &&
7303 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007304 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007305 }
7306 }
7307 }
7308 } catch (RemoteException ex) {
7309 // pm is in same process, this will never happen.
7310 }
7311 }
7312
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007313 // Start up initial activity.
7314 mBooting = true;
7315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007316 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007317 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007318 Message msg = Message.obtain();
7319 msg.what = SHOW_UID_ERROR_MSG;
7320 mHandler.sendMessage(msg);
7321 }
7322 } catch (RemoteException e) {
7323 }
7324
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007325 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 }
7327 }
7328
Dan Egnorb7f03672009-12-09 16:22:32 -08007329 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007330 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007332 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007333 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 startAppProblemLocked(app);
7335 app.stopFreezingAllLocked();
7336 return handleAppCrashLocked(app);
7337 }
7338
Dan Egnorb7f03672009-12-09 16:22:32 -08007339 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007340 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007342 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007343 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7344 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 startAppProblemLocked(app);
7346 app.stopFreezingAllLocked();
7347 }
7348
7349 /**
7350 * Generate a process error record, suitable for attachment to a ProcessRecord.
7351 *
7352 * @param app The ProcessRecord in which the error occurred.
7353 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7354 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007355 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007356 * @param shortMsg Short message describing the crash.
7357 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007358 * @param stackTrace Full crash stack trace, may be null.
7359 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 * @return Returns a fully-formed AppErrorStateInfo record.
7361 */
7362 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007363 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007364 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007366 report.condition = condition;
7367 report.processName = app.processName;
7368 report.pid = app.pid;
7369 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007370 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 report.shortMsg = shortMsg;
7372 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007373 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007374
7375 return report;
7376 }
7377
Dan Egnor42471dd2010-01-07 17:25:22 -08007378 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 synchronized (this) {
7380 app.crashing = false;
7381 app.crashingReport = null;
7382 app.notResponding = false;
7383 app.notRespondingReport = null;
7384 if (app.anrDialog == fromDialog) {
7385 app.anrDialog = null;
7386 }
7387 if (app.waitDialog == fromDialog) {
7388 app.waitDialog = null;
7389 }
7390 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007391 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007392 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007393 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7394 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007395 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 }
7398 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007399
Dan Egnorb7f03672009-12-09 16:22:32 -08007400 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007401 if (mHeadless) {
7402 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7403 return false;
7404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007405 long now = SystemClock.uptimeMillis();
7406
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007407 Long crashTime;
7408 if (!app.isolated) {
7409 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7410 } else {
7411 crashTime = null;
7412 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007413 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007415 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007417 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007418 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007419 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7420 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007422 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007424 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 }
7426 }
7427 if (!app.persistent) {
7428 // We don't want to start this process again until the user
7429 // explicitly does so... but for persistent process, we really
7430 // need to keep it running. If a persistent process is actually
7431 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007432 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007433 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007434 if (!app.isolated) {
7435 // XXX We don't have a way to mark isolated processes
7436 // as bad, since they don't have a peristent identity.
7437 mBadProcesses.put(app.info.processName, app.uid, now);
7438 mProcessCrashTimes.remove(app.info.processName, app.uid);
7439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007441 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007442 // Don't let services in this process be restarted and potentially
7443 // annoy the user repeatedly. Unless it is persistent, since those
7444 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007445 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007446 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007447 return false;
7448 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007449 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007450 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007451 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007452 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007453 // If the top running activity is from this crashing
7454 // process, then terminate it to avoid getting in a loop.
7455 Slog.w(TAG, " Force finishing activity "
7456 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007457 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007458 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007459 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007460 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007461 // stopped, to avoid a situation where one will get
7462 // re-start our crashing activity once it gets resumed again.
7463 index--;
7464 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007465 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007466 if (r.state == ActivityState.RESUMED
7467 || r.state == ActivityState.PAUSING
7468 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007469 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007470 Slog.w(TAG, " Force finishing activity "
7471 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007472 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007473 Activity.RESULT_CANCELED, null, "crashed");
7474 }
7475 }
7476 }
7477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 }
7479
7480 // Bump up the crash count of any services currently running in the proc.
7481 if (app.services.size() != 0) {
7482 // Any services running in the application need to be placed
7483 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007484 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007485 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007486 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007487 sr.crashCount++;
7488 }
7489 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007490
7491 // If the crashing process is what we consider to be the "home process" and it has been
7492 // replaced by a third-party app, clear the package preferred activities from packages
7493 // with a home activity running in the process to prevent a repeatedly crashing app
7494 // from blocking the user to manually clear the list.
7495 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7496 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7497 Iterator it = mHomeProcess.activities.iterator();
7498 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007499 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007500 if (r.isHomeActivity) {
7501 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7502 try {
7503 ActivityThread.getPackageManager()
7504 .clearPackagePreferredActivities(r.packageName);
7505 } catch (RemoteException c) {
7506 // pm is in same process, this will never happen.
7507 }
7508 }
7509 }
7510 }
7511
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007512 if (!app.isolated) {
7513 // XXX Can't keep track of crash times for isolated processes,
7514 // because they don't have a perisistent identity.
7515 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7516 }
7517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 return true;
7519 }
7520
7521 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007522 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7523 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 skipCurrentReceiverLocked(app);
7525 }
7526
7527 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007528 for (BroadcastQueue queue : mBroadcastQueues) {
7529 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 }
7531 }
7532
Dan Egnor60d87622009-12-16 16:32:58 -08007533 /**
7534 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7535 * The application process will exit immediately after this call returns.
7536 * @param app object of the crashing app, null for the system server
7537 * @param crashInfo describing the exception
7538 */
7539 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007540 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007541 final String processName = app == null ? "system_server"
7542 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007543
7544 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007545 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007546 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007547 crashInfo.exceptionClassName,
7548 crashInfo.exceptionMessage,
7549 crashInfo.throwFileName,
7550 crashInfo.throwLineNumber);
7551
Jeff Sharkeya353d262011-10-28 11:12:06 -07007552 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007553
7554 crashApplication(r, crashInfo);
7555 }
7556
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007557 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007558 IBinder app,
7559 int violationMask,
7560 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007561 ProcessRecord r = findAppProcess(app, "StrictMode");
7562 if (r == null) {
7563 return;
7564 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007565
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007566 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007567 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007568 boolean logIt = true;
7569 synchronized (mAlreadyLoggedViolatedStacks) {
7570 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7571 logIt = false;
7572 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007573 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007574 // the relative pain numbers, without logging all
7575 // the stack traces repeatedly. We'd want to do
7576 // likewise in the client code, which also does
7577 // dup suppression, before the Binder call.
7578 } else {
7579 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7580 mAlreadyLoggedViolatedStacks.clear();
7581 }
7582 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7583 }
7584 }
7585 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007586 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007587 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007588 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007589
7590 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7591 AppErrorResult result = new AppErrorResult();
7592 synchronized (this) {
7593 final long origId = Binder.clearCallingIdentity();
7594
7595 Message msg = Message.obtain();
7596 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7597 HashMap<String, Object> data = new HashMap<String, Object>();
7598 data.put("result", result);
7599 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007600 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007601 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007602 msg.obj = data;
7603 mHandler.sendMessage(msg);
7604
7605 Binder.restoreCallingIdentity(origId);
7606 }
7607 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007608 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007609 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007610 }
7611
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007612 // Depending on the policy in effect, there could be a bunch of
7613 // these in quick succession so we try to batch these together to
7614 // minimize disk writes, number of dropbox entries, and maximize
7615 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007616 private void logStrictModeViolationToDropBox(
7617 ProcessRecord process,
7618 StrictMode.ViolationInfo info) {
7619 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007620 return;
7621 }
7622 final boolean isSystemApp = process == null ||
7623 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7624 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007625 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007626 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7627 final DropBoxManager dbox = (DropBoxManager)
7628 mContext.getSystemService(Context.DROPBOX_SERVICE);
7629
7630 // Exit early if the dropbox isn't configured to accept this report type.
7631 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7632
7633 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007634 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007635 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7636 synchronized (sb) {
7637 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007638 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007639 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7640 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007641 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7642 if (info.violationNumThisLoop != 0) {
7643 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7644 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007645 if (info.numAnimationsRunning != 0) {
7646 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7647 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007648 if (info.broadcastIntentAction != null) {
7649 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7650 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007651 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007652 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007653 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007654 if (info.numInstances != -1) {
7655 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7656 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007657 if (info.tags != null) {
7658 for (String tag : info.tags) {
7659 sb.append("Span-Tag: ").append(tag).append("\n");
7660 }
7661 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007662 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007663 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7664 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007665 }
7666 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007667
7668 // Only buffer up to ~64k. Various logging bits truncate
7669 // things at 128k.
7670 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007671 }
7672
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007673 // Flush immediately if the buffer's grown too large, or this
7674 // is a non-system app. Non-system apps are isolated with a
7675 // different tag & policy and not batched.
7676 //
7677 // Batching is useful during internal testing with
7678 // StrictMode settings turned up high. Without batching,
7679 // thousands of separate files could be created on boot.
7680 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007681 new Thread("Error dump: " + dropboxTag) {
7682 @Override
7683 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007684 String report;
7685 synchronized (sb) {
7686 report = sb.toString();
7687 sb.delete(0, sb.length());
7688 sb.trimToSize();
7689 }
7690 if (report.length() != 0) {
7691 dbox.addText(dropboxTag, report);
7692 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007693 }
7694 }.start();
7695 return;
7696 }
7697
7698 // System app batching:
7699 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007700 // An existing dropbox-writing thread is outstanding, so
7701 // we don't need to start it up. The existing thread will
7702 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007703 return;
7704 }
7705
7706 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7707 // (After this point, we shouldn't access AMS internal data structures.)
7708 new Thread("Error dump: " + dropboxTag) {
7709 @Override
7710 public void run() {
7711 // 5 second sleep to let stacks arrive and be batched together
7712 try {
7713 Thread.sleep(5000); // 5 seconds
7714 } catch (InterruptedException e) {}
7715
7716 String errorReport;
7717 synchronized (mStrictModeBuffer) {
7718 errorReport = mStrictModeBuffer.toString();
7719 if (errorReport.length() == 0) {
7720 return;
7721 }
7722 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7723 mStrictModeBuffer.trimToSize();
7724 }
7725 dbox.addText(dropboxTag, errorReport);
7726 }
7727 }.start();
7728 }
7729
Dan Egnor60d87622009-12-16 16:32:58 -08007730 /**
7731 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7732 * @param app object of the crashing app, null for the system server
7733 * @param tag reported by the caller
7734 * @param crashInfo describing the context of the error
7735 * @return true if the process should exit immediately (WTF is fatal)
7736 */
7737 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007738 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007739 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007740 final String processName = app == null ? "system_server"
7741 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007742
7743 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007744 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007745 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007746 tag, crashInfo.exceptionMessage);
7747
Jeff Sharkeya353d262011-10-28 11:12:06 -07007748 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007749
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007750 if (r != null && r.pid != Process.myPid() &&
7751 Settings.Secure.getInt(mContext.getContentResolver(),
7752 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007753 crashApplication(r, crashInfo);
7754 return true;
7755 } else {
7756 return false;
7757 }
7758 }
7759
7760 /**
7761 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7762 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7763 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007764 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007765 if (app == null) {
7766 return null;
7767 }
7768
7769 synchronized (this) {
7770 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7771 final int NA = apps.size();
7772 for (int ia=0; ia<NA; ia++) {
7773 ProcessRecord p = apps.valueAt(ia);
7774 if (p.thread != null && p.thread.asBinder() == app) {
7775 return p;
7776 }
7777 }
7778 }
7779
Dianne Hackborncb44d962011-03-10 17:02:27 -08007780 Slog.w(TAG, "Can't find mystery application for " + reason
7781 + " from pid=" + Binder.getCallingPid()
7782 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007783 return null;
7784 }
7785 }
7786
7787 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007788 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7789 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007790 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007791 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7792 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007793 // Watchdog thread ends up invoking this function (with
7794 // a null ProcessRecord) to add the stack file to dropbox.
7795 // Do not acquire a lock on this (am) in such cases, as it
7796 // could cause a potential deadlock, if and when watchdog
7797 // is invoked due to unavailability of lock on am and it
7798 // would prevent watchdog from killing system_server.
7799 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007800 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007801 return;
7802 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007803 // Note: ProcessRecord 'process' is guarded by the service
7804 // instance. (notably process.pkgList, which could otherwise change
7805 // concurrently during execution of this method)
7806 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007807 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007808 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007809 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007810 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7811 for (String pkg : process.pkgList) {
7812 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007813 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007814 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007815 if (pi != null) {
7816 sb.append(" v").append(pi.versionCode);
7817 if (pi.versionName != null) {
7818 sb.append(" (").append(pi.versionName).append(")");
7819 }
7820 }
7821 } catch (RemoteException e) {
7822 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007823 }
Dan Egnora455d192010-03-12 08:52:28 -08007824 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007825 }
Dan Egnora455d192010-03-12 08:52:28 -08007826 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007827 }
7828
7829 private static String processClass(ProcessRecord process) {
7830 if (process == null || process.pid == MY_PID) {
7831 return "system_server";
7832 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7833 return "system_app";
7834 } else {
7835 return "data_app";
7836 }
7837 }
7838
7839 /**
7840 * Write a description of an error (crash, WTF, ANR) to the drop box.
7841 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7842 * @param process which caused the error, null means the system server
7843 * @param activity which triggered the error, null if unknown
7844 * @param parent activity related to the error, null if unknown
7845 * @param subject line related to the error, null if absent
7846 * @param report in long form describing the error, null if absent
7847 * @param logFile to include in the report, null if none
7848 * @param crashInfo giving an application stack trace, null if absent
7849 */
7850 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007851 ProcessRecord process, String processName, ActivityRecord activity,
7852 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007853 final String report, final File logFile,
7854 final ApplicationErrorReport.CrashInfo crashInfo) {
7855 // NOTE -- this must never acquire the ActivityManagerService lock,
7856 // otherwise the watchdog may be prevented from resetting the system.
7857
7858 final String dropboxTag = processClass(process) + "_" + eventType;
7859 final DropBoxManager dbox = (DropBoxManager)
7860 mContext.getSystemService(Context.DROPBOX_SERVICE);
7861
7862 // Exit early if the dropbox isn't configured to accept this report type.
7863 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7864
7865 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007866 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007867 if (activity != null) {
7868 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7869 }
7870 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7871 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7872 }
7873 if (parent != null && parent != activity) {
7874 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7875 }
7876 if (subject != null) {
7877 sb.append("Subject: ").append(subject).append("\n");
7878 }
7879 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007880 if (Debug.isDebuggerConnected()) {
7881 sb.append("Debugger: Connected\n");
7882 }
Dan Egnora455d192010-03-12 08:52:28 -08007883 sb.append("\n");
7884
7885 // Do the rest in a worker thread to avoid blocking the caller on I/O
7886 // (After this point, we shouldn't access AMS internal data structures.)
7887 Thread worker = new Thread("Error dump: " + dropboxTag) {
7888 @Override
7889 public void run() {
7890 if (report != null) {
7891 sb.append(report);
7892 }
7893 if (logFile != null) {
7894 try {
7895 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7896 } catch (IOException e) {
7897 Slog.e(TAG, "Error reading " + logFile, e);
7898 }
7899 }
7900 if (crashInfo != null && crashInfo.stackTrace != null) {
7901 sb.append(crashInfo.stackTrace);
7902 }
7903
7904 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7905 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7906 if (lines > 0) {
7907 sb.append("\n");
7908
7909 // Merge several logcat streams, and take the last N lines
7910 InputStreamReader input = null;
7911 try {
7912 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7913 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7914 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7915
7916 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7917 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7918 input = new InputStreamReader(logcat.getInputStream());
7919
7920 int num;
7921 char[] buf = new char[8192];
7922 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7923 } catch (IOException e) {
7924 Slog.e(TAG, "Error running logcat", e);
7925 } finally {
7926 if (input != null) try { input.close(); } catch (IOException e) {}
7927 }
7928 }
7929
7930 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007931 }
Dan Egnora455d192010-03-12 08:52:28 -08007932 };
7933
7934 if (process == null || process.pid == MY_PID) {
7935 worker.run(); // We may be about to die -- need to run this synchronously
7936 } else {
7937 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007938 }
7939 }
7940
7941 /**
7942 * Bring up the "unexpected error" dialog box for a crashing app.
7943 * Deal with edge cases (intercepts from instrumented applications,
7944 * ActivityController, error intent receivers, that sort of thing).
7945 * @param r the application crashing
7946 * @param crashInfo describing the failure
7947 */
7948 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08007949 long timeMillis = System.currentTimeMillis();
7950 String shortMsg = crashInfo.exceptionClassName;
7951 String longMsg = crashInfo.exceptionMessage;
7952 String stackTrace = crashInfo.stackTrace;
7953 if (shortMsg != null && longMsg != null) {
7954 longMsg = shortMsg + ": " + longMsg;
7955 } else if (shortMsg != null) {
7956 longMsg = shortMsg;
7957 }
7958
Dan Egnor60d87622009-12-16 16:32:58 -08007959 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007961 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007962 try {
7963 String name = r != null ? r.processName : null;
7964 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08007965 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08007966 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007967 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 + " at watcher's request");
7969 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08007970 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 }
7972 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007973 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 }
7975 }
7976
7977 final long origId = Binder.clearCallingIdentity();
7978
7979 // If this process is running instrumentation, finish it.
7980 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007981 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08007983 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
7984 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 Bundle info = new Bundle();
7986 info.putString("shortMsg", shortMsg);
7987 info.putString("longMsg", longMsg);
7988 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
7989 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007990 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 }
7992
Dan Egnor60d87622009-12-16 16:32:58 -08007993 // If we can't identify the process or it's already exceeded its crash quota,
7994 // quit right away without showing a crash dialog.
7995 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08007997 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 }
7999
8000 Message msg = Message.obtain();
8001 msg.what = SHOW_ERROR_MSG;
8002 HashMap data = new HashMap();
8003 data.put("result", result);
8004 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 msg.obj = data;
8006 mHandler.sendMessage(msg);
8007
8008 Binder.restoreCallingIdentity(origId);
8009 }
8010
8011 int res = result.get();
8012
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008013 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008015 if (r != null && !r.isolated) {
8016 // XXX Can't keep track of crash time for isolated processes,
8017 // since they don't have a persistent identity.
8018 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 SystemClock.uptimeMillis());
8020 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008021 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008022 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008023 }
8024 }
8025
8026 if (appErrorIntent != null) {
8027 try {
8028 mContext.startActivity(appErrorIntent);
8029 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008030 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008034
8035 Intent createAppErrorIntentLocked(ProcessRecord r,
8036 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8037 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008038 if (report == null) {
8039 return null;
8040 }
8041 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8042 result.setComponent(r.errorReportReceiver);
8043 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8044 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8045 return result;
8046 }
8047
Dan Egnorb7f03672009-12-09 16:22:32 -08008048 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8049 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008050 if (r.errorReportReceiver == null) {
8051 return null;
8052 }
8053
8054 if (!r.crashing && !r.notResponding) {
8055 return null;
8056 }
8057
Dan Egnorb7f03672009-12-09 16:22:32 -08008058 ApplicationErrorReport report = new ApplicationErrorReport();
8059 report.packageName = r.info.packageName;
8060 report.installerPackageName = r.errorReportReceiver.getPackageName();
8061 report.processName = r.processName;
8062 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008063 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008064
Dan Egnorb7f03672009-12-09 16:22:32 -08008065 if (r.crashing) {
8066 report.type = ApplicationErrorReport.TYPE_CRASH;
8067 report.crashInfo = crashInfo;
8068 } else if (r.notResponding) {
8069 report.type = ApplicationErrorReport.TYPE_ANR;
8070 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008071
Dan Egnorb7f03672009-12-09 16:22:32 -08008072 report.anrInfo.activity = r.notRespondingReport.tag;
8073 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8074 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008075 }
8076
Dan Egnorb7f03672009-12-09 16:22:32 -08008077 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008078 }
8079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008081 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 // assume our apps are happy - lazy create the list
8083 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8084
8085 synchronized (this) {
8086
8087 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008088 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8089 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8091 // This one's in trouble, so we'll generate a report for it
8092 // crashes are higher priority (in case there's a crash *and* an anr)
8093 ActivityManager.ProcessErrorStateInfo report = null;
8094 if (app.crashing) {
8095 report = app.crashingReport;
8096 } else if (app.notResponding) {
8097 report = app.notRespondingReport;
8098 }
8099
8100 if (report != null) {
8101 if (errList == null) {
8102 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8103 }
8104 errList.add(report);
8105 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008106 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008107 " crashing = " + app.crashing +
8108 " notResponding = " + app.notResponding);
8109 }
8110 }
8111 }
8112 }
8113
8114 return errList;
8115 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008116
8117 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008118 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008119 if (currApp != null) {
8120 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8121 }
8122 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008123 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8124 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008125 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8126 if (currApp != null) {
8127 currApp.lru = 0;
8128 }
8129 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008130 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008131 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8132 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8133 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8134 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8135 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8136 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8137 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8138 } else {
8139 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8140 }
8141 }
8142
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008143 private void fillInProcMemInfo(ProcessRecord app,
8144 ActivityManager.RunningAppProcessInfo outInfo) {
8145 outInfo.pid = app.pid;
8146 outInfo.uid = app.info.uid;
8147 if (mHeavyWeightProcess == app) {
8148 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8149 }
8150 if (app.persistent) {
8151 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8152 }
8153 outInfo.lastTrimLevel = app.trimMemoryLevel;
8154 int adj = app.curAdj;
8155 outInfo.importance = oomAdjToImportance(adj, outInfo);
8156 outInfo.importanceReasonCode = app.adjTypeCode;
8157 }
8158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008159 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008160 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 // Lazy instantiation of list
8162 List<ActivityManager.RunningAppProcessInfo> runList = null;
8163 synchronized (this) {
8164 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008165 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8166 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8168 // Generate process state info for running application
8169 ActivityManager.RunningAppProcessInfo currApp =
8170 new ActivityManager.RunningAppProcessInfo(app.processName,
8171 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008172 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008173 if (app.adjSource instanceof ProcessRecord) {
8174 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008175 currApp.importanceReasonImportance = oomAdjToImportance(
8176 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008177 } else if (app.adjSource instanceof ActivityRecord) {
8178 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008179 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8180 }
8181 if (app.adjTarget instanceof ComponentName) {
8182 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8183 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008184 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 // + " lru=" + currApp.lru);
8186 if (runList == null) {
8187 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8188 }
8189 runList.add(currApp);
8190 }
8191 }
8192 }
8193 return runList;
8194 }
8195
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008196 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008197 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008198 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8199 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8200 if (runningApps != null && runningApps.size() > 0) {
8201 Set<String> extList = new HashSet<String>();
8202 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8203 if (app.pkgList != null) {
8204 for (String pkg : app.pkgList) {
8205 extList.add(pkg);
8206 }
8207 }
8208 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008209 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008210 for (String pkg : extList) {
8211 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008212 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008213 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8214 retList.add(info);
8215 }
8216 } catch (RemoteException e) {
8217 }
8218 }
8219 }
8220 return retList;
8221 }
8222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008224 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8225 enforceNotIsolatedCaller("getMyMemoryState");
8226 synchronized (this) {
8227 ProcessRecord proc;
8228 synchronized (mPidsSelfLocked) {
8229 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8230 }
8231 fillInProcMemInfo(proc, outInfo);
8232 }
8233 }
8234
8235 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008237 if (checkCallingPermission(android.Manifest.permission.DUMP)
8238 != PackageManager.PERMISSION_GRANTED) {
8239 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8240 + Binder.getCallingPid()
8241 + ", uid=" + Binder.getCallingUid()
8242 + " without permission "
8243 + android.Manifest.permission.DUMP);
8244 return;
8245 }
8246
8247 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008248 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008249 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008250
8251 int opti = 0;
8252 while (opti < args.length) {
8253 String opt = args[opti];
8254 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8255 break;
8256 }
8257 opti++;
8258 if ("-a".equals(opt)) {
8259 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008260 } else if ("-c".equals(opt)) {
8261 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008262 } else if ("-h".equals(opt)) {
8263 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008264 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008265 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008266 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008267 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8268 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8269 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008270 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008271 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008272 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008273 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008274 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008275 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008276 pw.println(" all: dump all activities");
8277 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008278 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008279 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8280 pw.println(" a partial substring in a component name, a");
8281 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008282 pw.println(" -a: include all available server state.");
8283 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008285 } else {
8286 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008287 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008288 }
8289
8290 // Is the caller requesting to dump a particular piece of data?
8291 if (opti < args.length) {
8292 String cmd = args[opti];
8293 opti++;
8294 if ("activities".equals(cmd) || "a".equals(cmd)) {
8295 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008296 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008298 return;
8299 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008300 String[] newArgs;
8301 String name;
8302 if (opti >= args.length) {
8303 name = null;
8304 newArgs = EMPTY_STRING_ARRAY;
8305 } else {
8306 name = args[opti];
8307 opti++;
8308 newArgs = new String[args.length - opti];
8309 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8310 args.length - opti);
8311 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008312 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008313 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008314 }
8315 return;
8316 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008317 String[] newArgs;
8318 String name;
8319 if (opti >= args.length) {
8320 name = null;
8321 newArgs = EMPTY_STRING_ARRAY;
8322 } else {
8323 name = args[opti];
8324 opti++;
8325 newArgs = new String[args.length - opti];
8326 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8327 args.length - opti);
8328 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008329 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008330 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008331 }
8332 return;
8333 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008334 String[] newArgs;
8335 String name;
8336 if (opti >= args.length) {
8337 name = null;
8338 newArgs = EMPTY_STRING_ARRAY;
8339 } else {
8340 name = args[opti];
8341 opti++;
8342 newArgs = new String[args.length - opti];
8343 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8344 args.length - opti);
8345 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008346 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008347 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008348 }
8349 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008350 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8351 synchronized (this) {
8352 dumpOomLocked(fd, pw, args, opti, true);
8353 }
8354 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008355 } else if ("provider".equals(cmd)) {
8356 String[] newArgs;
8357 String name;
8358 if (opti >= args.length) {
8359 name = null;
8360 newArgs = EMPTY_STRING_ARRAY;
8361 } else {
8362 name = args[opti];
8363 opti++;
8364 newArgs = new String[args.length - opti];
8365 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8366 }
8367 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8368 pw.println("No providers match: " + name);
8369 pw.println("Use -h for help.");
8370 }
8371 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008372 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8373 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008374 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008375 }
8376 return;
8377 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008378 String[] newArgs;
8379 String name;
8380 if (opti >= args.length) {
8381 name = null;
8382 newArgs = EMPTY_STRING_ARRAY;
8383 } else {
8384 name = args[opti];
8385 opti++;
8386 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008387 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8388 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008389 }
8390 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8391 pw.println("No services match: " + name);
8392 pw.println("Use -h for help.");
8393 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008394 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008395 } else if ("package".equals(cmd)) {
8396 String[] newArgs;
8397 if (opti >= args.length) {
8398 pw.println("package: no package name specified");
8399 pw.println("Use -h for help.");
8400 return;
8401 } else {
8402 dumpPackage = args[opti];
8403 opti++;
8404 newArgs = new String[args.length - opti];
8405 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8406 args.length - opti);
8407 args = newArgs;
8408 opti = 0;
8409 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008410 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8411 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008412 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008413 }
8414 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008415 } else {
8416 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008417 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8418 pw.println("Bad activity command, or no activities match: " + cmd);
8419 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008420 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008421 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008422 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008423 }
8424
8425 // No piece of data specified, dump everything.
8426 synchronized (this) {
8427 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008428 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008429 if (needSep) {
8430 pw.println(" ");
8431 }
8432 if (dumpAll) {
8433 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008434 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008435 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008436 if (needSep) {
8437 pw.println(" ");
8438 }
8439 if (dumpAll) {
8440 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008441 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008442 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008443 if (needSep) {
8444 pw.println(" ");
8445 }
8446 if (dumpAll) {
8447 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008448 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008449 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008450 if (needSep) {
8451 pw.println(" ");
8452 }
8453 if (dumpAll) {
8454 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008455 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008456 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008457 if (needSep) {
8458 pw.println(" ");
8459 }
8460 if (dumpAll) {
8461 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008462 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008463 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008464 }
8465 }
8466
8467 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008468 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008469 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8470 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008471 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8472 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008473 pw.println(" ");
8474 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008475 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8476 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008477 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008479 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008480 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008481 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008482 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008483 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008485 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008486 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008487 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008488 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008489 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8490 pw.println(" ");
8491 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008492 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008493 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008494 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008495 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 pw.println(" ");
8497 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008498 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008499 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008502 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008503 if (mMainStack.mPausingActivity != null) {
8504 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008505 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008506 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008507 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008508 if (dumpAll) {
8509 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8510 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008511 pw.println(" mDismissKeyguardOnNextActivity: "
8512 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008514
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008515 if (mRecentTasks.size() > 0) {
8516 pw.println();
8517 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008518
8519 final int N = mRecentTasks.size();
8520 for (int i=0; i<N; i++) {
8521 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008522 if (dumpPackage != null) {
8523 if (tr.realActivity == null ||
8524 !dumpPackage.equals(tr.realActivity)) {
8525 continue;
8526 }
8527 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8529 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008530 if (dumpAll) {
8531 mRecentTasks.get(i).dump(pw, " ");
8532 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008533 }
8534 }
8535
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008536 if (dumpAll) {
8537 pw.println(" ");
8538 pw.println(" mCurTask: " + mCurTask);
8539 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540
8541 return true;
8542 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008543
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008544 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008545 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008546 boolean needSep = false;
8547 int numPers = 0;
8548
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008549 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8550
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8553 final int NA = procs.size();
8554 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008555 ProcessRecord r = procs.valueAt(ia);
8556 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8557 continue;
8558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008559 if (!needSep) {
8560 pw.println(" All known processes:");
8561 needSep = true;
8562 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008563 pw.print(r.persistent ? " *PERS*" : " *APP*");
8564 pw.print(" UID "); pw.print(procs.keyAt(ia));
8565 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 r.dump(pw, " ");
8567 if (r.persistent) {
8568 numPers++;
8569 }
8570 }
8571 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008572 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008573
8574 if (mIsolatedProcesses.size() > 0) {
8575 if (needSep) pw.println(" ");
8576 needSep = true;
8577 pw.println(" Isolated process list (sorted by uid):");
8578 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8579 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8580 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8581 continue;
8582 }
8583 pw.println(String.format("%sIsolated #%2d: %s",
8584 " ", i, r.toString()));
8585 }
8586 }
8587
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 if (mLruProcesses.size() > 0) {
8589 if (needSep) pw.println(" ");
8590 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008591 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008592 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008593 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008594 needSep = true;
8595 }
8596
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008597 if (dumpAll) {
8598 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008599 boolean printed = false;
8600 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8601 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8602 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8603 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008604 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008605 if (!printed) {
8606 if (needSep) pw.println(" ");
8607 needSep = true;
8608 pw.println(" PID mappings:");
8609 printed = true;
8610 }
8611 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8612 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 }
8614 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008615 }
8616
8617 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008618 synchronized (mPidsSelfLocked) {
8619 boolean printed = false;
8620 for (int i=0; i<mForegroundProcesses.size(); i++) {
8621 ProcessRecord r = mPidsSelfLocked.get(
8622 mForegroundProcesses.valueAt(i).pid);
8623 if (dumpPackage != null && (r == null
8624 || !dumpPackage.equals(r.info.packageName))) {
8625 continue;
8626 }
8627 if (!printed) {
8628 if (needSep) pw.println(" ");
8629 needSep = true;
8630 pw.println(" Foreground Processes:");
8631 printed = true;
8632 }
8633 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8634 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008637 }
8638
8639 if (mPersistentStartingProcesses.size() > 0) {
8640 if (needSep) pw.println(" ");
8641 needSep = true;
8642 pw.println(" Persisent processes that are starting:");
8643 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008647 if (mRemovedProcesses.size() > 0) {
8648 if (needSep) pw.println(" ");
8649 needSep = true;
8650 pw.println(" Processes that are being removed:");
8651 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 }
8654
8655 if (mProcessesOnHold.size() > 0) {
8656 if (needSep) pw.println(" ");
8657 needSep = true;
8658 pw.println(" Processes that are on old until the system is ready:");
8659 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008660 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008663 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664
8665 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008666 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008667 long now = SystemClock.uptimeMillis();
8668 for (Map.Entry<String, SparseArray<Long>> procs
8669 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008670 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008671 SparseArray<Long> uids = procs.getValue();
8672 final int N = uids.size();
8673 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008674 int puid = uids.keyAt(i);
8675 ProcessRecord r = mProcessNames.get(pname, puid);
8676 if (dumpPackage != null && (r == null
8677 || !dumpPackage.equals(r.info.packageName))) {
8678 continue;
8679 }
8680 if (!printed) {
8681 if (needSep) pw.println(" ");
8682 needSep = true;
8683 pw.println(" Time since processes crashed:");
8684 printed = true;
8685 }
8686 pw.print(" Process "); pw.print(pname);
8687 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008688 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008689 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8690 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008691 }
8692 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008694
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008695 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008696 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697 for (Map.Entry<String, SparseArray<Long>> procs
8698 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008699 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 SparseArray<Long> uids = procs.getValue();
8701 final int N = uids.size();
8702 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008703 int puid = uids.keyAt(i);
8704 ProcessRecord r = mProcessNames.get(pname, puid);
8705 if (dumpPackage != null && (r == null
8706 || !dumpPackage.equals(r.info.packageName))) {
8707 continue;
8708 }
8709 if (!printed) {
8710 if (needSep) pw.println(" ");
8711 needSep = true;
8712 pw.println(" Bad processes:");
8713 }
8714 pw.print(" Bad process "); pw.print(pname);
8715 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716 pw.print(": crashed at time ");
8717 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 }
8719 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008721
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008722 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008724 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008725 if (dumpAll) {
8726 StringBuilder sb = new StringBuilder(128);
8727 sb.append(" mPreviousProcessVisibleTime: ");
8728 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8729 pw.println(sb);
8730 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008731 if (mHeavyWeightProcess != null) {
8732 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8733 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008734 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008735 if (dumpAll) {
8736 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008737 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008738 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008739 for (Map.Entry<String, Integer> entry
8740 : mCompatModePackages.getPackages().entrySet()) {
8741 String pkg = entry.getKey();
8742 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008743 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8744 continue;
8745 }
8746 if (!printed) {
8747 pw.println(" mScreenCompatPackages:");
8748 printed = true;
8749 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008750 pw.print(" "); pw.print(pkg); pw.print(": ");
8751 pw.print(mode); pw.println();
8752 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008753 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008754 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8756 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8757 || mOrigWaitForDebugger) {
8758 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8759 + " mDebugTransient=" + mDebugTransient
8760 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8761 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008762 if (mOpenGlTraceApp != null) {
8763 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8764 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008765 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8766 || mProfileFd != null) {
8767 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8768 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8769 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8770 + mAutoStopProfiler);
8771 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 if (mAlwaysFinishActivities || mController != null) {
8773 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8774 + " mController=" + mController);
8775 }
8776 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008779 + " mProcessesReady=" + mProcessesReady
8780 + " mSystemReady=" + mSystemReady);
8781 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 + " mBooted=" + mBooted
8783 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008784 pw.print(" mLastPowerCheckRealtime=");
8785 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8786 pw.println("");
8787 pw.print(" mLastPowerCheckUptime=");
8788 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8789 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008790 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8791 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008792 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008793 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8794 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008796
8797 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 }
8799
Dianne Hackborn287952c2010-09-22 22:34:31 -07008800 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008801 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008802 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008803 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008804 long now = SystemClock.uptimeMillis();
8805 for (int i=0; i<mProcessesToGc.size(); i++) {
8806 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008807 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8808 continue;
8809 }
8810 if (!printed) {
8811 if (needSep) pw.println(" ");
8812 needSep = true;
8813 pw.println(" Processes that are waiting to GC:");
8814 printed = true;
8815 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008816 pw.print(" Process "); pw.println(proc);
8817 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8818 pw.print(", last gced=");
8819 pw.print(now-proc.lastRequestedGc);
8820 pw.print(" ms ago, last lowMem=");
8821 pw.print(now-proc.lastLowMemory);
8822 pw.println(" ms ago");
8823
8824 }
8825 }
8826 return needSep;
8827 }
8828
8829 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8830 int opti, boolean dumpAll) {
8831 boolean needSep = false;
8832
8833 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008834 if (needSep) pw.println(" ");
8835 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008836 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008837 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008838 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008839 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8840 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8841 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8842 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8843 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008844 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008845 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008846 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008847 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008848 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008849 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008850
8851 if (needSep) pw.println(" ");
8852 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008853 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008854 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008855 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008856 needSep = true;
8857 }
8858
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008860
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008861 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008862 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008863 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008864 if (mHeavyWeightProcess != null) {
8865 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8866 }
8867
8868 return true;
8869 }
8870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008871 /**
8872 * There are three ways to call this:
8873 * - no service specified: dump all the services
8874 * - a flattened component name that matched an existing service was specified as the
8875 * first arg: dump that one service
8876 * - the first arg isn't the flattened component name of an existing service:
8877 * dump all services whose component contains the first arg as a substring
8878 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008879 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8880 int opti, boolean dumpAll) {
8881 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008882
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008883 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008884 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008885 try {
8886 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8887 for (UserInfo user : users) {
8888 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8889 services.add(r1);
8890 }
8891 }
8892 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008893 }
8894 }
8895 } else {
8896 ComponentName componentName = name != null
8897 ? ComponentName.unflattenFromString(name) : null;
8898 int objectId = 0;
8899 if (componentName == null) {
8900 // Not a '/' separated full component name; maybe an object ID?
8901 try {
8902 objectId = Integer.parseInt(name, 16);
8903 name = null;
8904 componentName = null;
8905 } catch (RuntimeException e) {
8906 }
8907 }
8908
8909 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008910 try {
8911 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8912 for (UserInfo user : users) {
8913 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8914 if (componentName != null) {
8915 if (r1.name.equals(componentName)) {
8916 services.add(r1);
8917 }
8918 } else if (name != null) {
8919 if (r1.name.flattenToString().contains(name)) {
8920 services.add(r1);
8921 }
8922 } else if (System.identityHashCode(r1) == objectId) {
8923 services.add(r1);
8924 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008925 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008926 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008927 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 }
8929 }
8930 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008931
8932 if (services.size() <= 0) {
8933 return false;
8934 }
8935
8936 boolean needSep = false;
8937 for (int i=0; i<services.size(); i++) {
8938 if (needSep) {
8939 pw.println();
8940 }
8941 needSep = true;
8942 dumpService("", fd, pw, services.get(i), args, dumpAll);
8943 }
8944 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 }
8946
8947 /**
8948 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
8949 * there is a thread associated with the service.
8950 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008951 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
8952 final ServiceRecord r, String[] args, boolean dumpAll) {
8953 String innerPrefix = prefix + " ";
8954 synchronized (this) {
8955 pw.print(prefix); pw.print("SERVICE ");
8956 pw.print(r.shortName); pw.print(" ");
8957 pw.print(Integer.toHexString(System.identityHashCode(r)));
8958 pw.print(" pid=");
8959 if (r.app != null) pw.println(r.app.pid);
8960 else pw.println("(not running)");
8961 if (dumpAll) {
8962 r.dump(pw, innerPrefix);
8963 }
8964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008966 pw.print(prefix); pw.println(" Client:");
8967 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008969 TransferPipe tp = new TransferPipe();
8970 try {
8971 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
8972 tp.setBufferPrefix(prefix + " ");
8973 tp.go(fd);
8974 } finally {
8975 tp.kill();
8976 }
8977 } catch (IOException e) {
8978 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 }
8982 }
8983 }
8984
Marco Nelissen18cb2872011-11-15 11:19:53 -08008985 /**
8986 * There are three ways to call this:
8987 * - no provider specified: dump all the providers
8988 * - a flattened component name that matched an existing provider was specified as the
8989 * first arg: dump that one provider
8990 * - the first arg isn't the flattened component name of an existing provider:
8991 * dump all providers whose component contains the first arg as a substring
8992 */
8993 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8994 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08008995 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08008996 }
8997
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008998 static class ItemMatcher {
8999 ArrayList<ComponentName> components;
9000 ArrayList<String> strings;
9001 ArrayList<Integer> objects;
9002 boolean all;
9003
9004 ItemMatcher() {
9005 all = true;
9006 }
9007
9008 void build(String name) {
9009 ComponentName componentName = ComponentName.unflattenFromString(name);
9010 if (componentName != null) {
9011 if (components == null) {
9012 components = new ArrayList<ComponentName>();
9013 }
9014 components.add(componentName);
9015 all = false;
9016 } else {
9017 int objectId = 0;
9018 // Not a '/' separated full component name; maybe an object ID?
9019 try {
9020 objectId = Integer.parseInt(name, 16);
9021 if (objects == null) {
9022 objects = new ArrayList<Integer>();
9023 }
9024 objects.add(objectId);
9025 all = false;
9026 } catch (RuntimeException e) {
9027 // Not an integer; just do string match.
9028 if (strings == null) {
9029 strings = new ArrayList<String>();
9030 }
9031 strings.add(name);
9032 all = false;
9033 }
9034 }
9035 }
9036
9037 int build(String[] args, int opti) {
9038 for (; opti<args.length; opti++) {
9039 String name = args[opti];
9040 if ("--".equals(name)) {
9041 return opti+1;
9042 }
9043 build(name);
9044 }
9045 return opti;
9046 }
9047
9048 boolean match(Object object, ComponentName comp) {
9049 if (all) {
9050 return true;
9051 }
9052 if (components != null) {
9053 for (int i=0; i<components.size(); i++) {
9054 if (components.get(i).equals(comp)) {
9055 return true;
9056 }
9057 }
9058 }
9059 if (objects != null) {
9060 for (int i=0; i<objects.size(); i++) {
9061 if (System.identityHashCode(object) == objects.get(i)) {
9062 return true;
9063 }
9064 }
9065 }
9066 if (strings != null) {
9067 String flat = comp.flattenToString();
9068 for (int i=0; i<strings.size(); i++) {
9069 if (flat.contains(strings.get(i))) {
9070 return true;
9071 }
9072 }
9073 }
9074 return false;
9075 }
9076 }
9077
Dianne Hackborn625ac272010-09-17 18:29:22 -07009078 /**
9079 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009080 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009081 * - the cmd arg isn't the flattened component name of an existing activity:
9082 * dump all activity whose component contains the cmd as a substring
9083 * - A hex number of the ActivityRecord object instance.
9084 */
9085 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9086 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009087 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009088
9089 if ("all".equals(name)) {
9090 synchronized (this) {
9091 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009092 activities.add(r1);
9093 }
9094 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009095 } else if ("top".equals(name)) {
9096 synchronized (this) {
9097 final int N = mMainStack.mHistory.size();
9098 if (N > 0) {
9099 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9100 }
9101 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009102 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009103 ItemMatcher matcher = new ItemMatcher();
9104 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009105
9106 synchronized (this) {
9107 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009108 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009109 activities.add(r1);
9110 }
9111 }
9112 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009113 }
9114
9115 if (activities.size() <= 0) {
9116 return false;
9117 }
9118
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009119 String[] newArgs = new String[args.length - opti];
9120 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9121
Dianne Hackborn30d71892010-12-11 10:37:55 -08009122 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009123 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009124 for (int i=activities.size()-1; i>=0; i--) {
9125 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009126 if (needSep) {
9127 pw.println();
9128 }
9129 needSep = true;
9130 synchronized (this) {
9131 if (lastTask != r.task) {
9132 lastTask = r.task;
9133 pw.print("TASK "); pw.print(lastTask.affinity);
9134 pw.print(" id="); pw.println(lastTask.taskId);
9135 if (dumpAll) {
9136 lastTask.dump(pw, " ");
9137 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009138 }
9139 }
9140 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009141 }
9142 return true;
9143 }
9144
9145 /**
9146 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9147 * there is a thread associated with the activity.
9148 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009149 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009150 final ActivityRecord r, String[] args, boolean dumpAll) {
9151 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009152 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009153 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9154 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9155 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009156 if (r.app != null) pw.println(r.app.pid);
9157 else pw.println("(not running)");
9158 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009159 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009160 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009161 }
9162 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009163 // flush anything that is already in the PrintWriter since the thread is going
9164 // to write to the file descriptor directly
9165 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009166 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009167 TransferPipe tp = new TransferPipe();
9168 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009169 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9170 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009171 tp.go(fd);
9172 } finally {
9173 tp.kill();
9174 }
9175 } catch (IOException e) {
9176 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009177 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009179 }
9180 }
9181 }
9182
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009183 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009184 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009185 boolean needSep = false;
9186
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009187 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009191 Iterator it = mRegisteredReceivers.values().iterator();
9192 while (it.hasNext()) {
9193 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009194 if (dumpPackage != null && (r.app == null ||
9195 !dumpPackage.equals(r.app.info.packageName))) {
9196 continue;
9197 }
9198 if (!printed) {
9199 pw.println(" Registered Receivers:");
9200 needSep = true;
9201 printed = true;
9202 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009203 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 r.dump(pw, " ");
9205 }
9206 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009207
9208 if (mReceiverResolver.dump(pw, needSep ?
9209 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9210 " ", dumpPackage, false)) {
9211 needSep = true;
9212 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009213 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009214
9215 for (BroadcastQueue q : mBroadcastQueues) {
9216 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009218
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009219 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009221 if (mStickyBroadcasts != null && dumpPackage == null) {
9222 if (needSep) {
9223 pw.println();
9224 }
9225 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009226 pw.println(" Sticky broadcasts:");
9227 StringBuilder sb = new StringBuilder(128);
9228 for (Map.Entry<String, ArrayList<Intent>> ent
9229 : mStickyBroadcasts.entrySet()) {
9230 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231 if (dumpAll) {
9232 pw.println(":");
9233 ArrayList<Intent> intents = ent.getValue();
9234 final int N = intents.size();
9235 for (int i=0; i<N; i++) {
9236 sb.setLength(0);
9237 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009238 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009239 pw.println(sb.toString());
9240 Bundle bundle = intents.get(i).getExtras();
9241 if (bundle != null) {
9242 pw.print(" ");
9243 pw.println(bundle.toString());
9244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009246 } else {
9247 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 }
9249 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009250 needSep = true;
9251 }
9252
9253 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009254 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009255 for (BroadcastQueue queue : mBroadcastQueues) {
9256 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9257 + queue.mBroadcastsScheduled);
9258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 pw.println(" mHandler:");
9260 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009262 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009263
9264 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009265 }
9266
Marco Nelissen18cb2872011-11-15 11:19:53 -08009267 /**
9268 * Prints a list of ServiceRecords (dumpsys activity services)
9269 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009270 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009271 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009274 ItemMatcher matcher = new ItemMatcher();
9275 matcher.build(args, opti);
9276
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009277 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009278 try {
9279 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9280 for (UserInfo user : users) {
9281 if (mServiceMap.getAllServices(user.id).size() > 0) {
9282 boolean printed = false;
9283 long nowReal = SystemClock.elapsedRealtime();
9284 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9285 user.id).iterator();
9286 needSep = false;
9287 while (it.hasNext()) {
9288 ServiceRecord r = it.next();
9289 if (!matcher.match(r, r.name)) {
9290 continue;
9291 }
9292 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9293 continue;
9294 }
9295 if (!printed) {
9296 pw.println(" Active services:");
9297 printed = true;
9298 }
9299 if (needSep) {
9300 pw.println();
9301 }
9302 pw.print(" * ");
9303 pw.println(r);
9304 if (dumpAll) {
9305 r.dump(pw, " ");
9306 needSep = true;
9307 } else {
9308 pw.print(" app=");
9309 pw.println(r.app);
9310 pw.print(" created=");
9311 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9312 pw.print(" started=");
9313 pw.print(r.startRequested);
9314 pw.print(" connections=");
9315 pw.println(r.connections.size());
9316 if (r.connections.size() > 0) {
9317 pw.println(" Connections:");
9318 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9319 for (int i = 0; i < clist.size(); i++) {
9320 ConnectionRecord conn = clist.get(i);
9321 pw.print(" ");
9322 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009323 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009324 pw.print(" -> ");
9325 ProcessRecord proc = conn.binding.client;
9326 pw.println(proc != null ? proc.toShortString() : "null");
9327 }
9328 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009329 }
9330 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009331 if (dumpClient && r.app != null && r.app.thread != null) {
9332 pw.println(" Client:");
9333 pw.flush();
9334 try {
9335 TransferPipe tp = new TransferPipe();
9336 try {
9337 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9338 r, args);
9339 tp.setBufferPrefix(" ");
9340 // Short timeout, since blocking here can
9341 // deadlock with the application.
9342 tp.go(fd, 2000);
9343 } finally {
9344 tp.kill();
9345 }
9346 } catch (IOException e) {
9347 pw.println(" Failure while dumping the service: " + e);
9348 } catch (RemoteException e) {
9349 pw.println(" Got a RemoteException while dumping the service");
9350 }
9351 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009352 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009353 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009354 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009357 } catch (RemoteException re) {
9358
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009360
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009361 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009362 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009363 for (int i=0; i<mPendingServices.size(); i++) {
9364 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009365 if (!matcher.match(r, r.name)) {
9366 continue;
9367 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009368 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9369 continue;
9370 }
9371 if (!printed) {
9372 if (needSep) pw.println(" ");
9373 needSep = true;
9374 pw.println(" Pending services:");
9375 printed = true;
9376 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009377 pw.print(" * Pending "); pw.println(r);
9378 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009379 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009380 needSep = true;
9381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009382
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009383 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009384 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009385 for (int i=0; i<mRestartingServices.size(); i++) {
9386 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009387 if (!matcher.match(r, r.name)) {
9388 continue;
9389 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009390 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9391 continue;
9392 }
9393 if (!printed) {
9394 if (needSep) pw.println(" ");
9395 needSep = true;
9396 pw.println(" Restarting services:");
9397 printed = true;
9398 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009399 pw.print(" * Restarting "); pw.println(r);
9400 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009401 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009402 needSep = true;
9403 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009404
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009405 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009406 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009407 for (int i=0; i<mStoppingServices.size(); i++) {
9408 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009409 if (!matcher.match(r, r.name)) {
9410 continue;
9411 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009412 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9413 continue;
9414 }
9415 if (!printed) {
9416 if (needSep) pw.println(" ");
9417 needSep = true;
9418 pw.println(" Stopping services:");
9419 printed = true;
9420 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009421 pw.print(" * Stopping "); pw.println(r);
9422 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009424 needSep = true;
9425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009426
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009427 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009428 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009429 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009430 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 = mServiceConnections.values().iterator();
9432 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009433 ArrayList<ConnectionRecord> r = it.next();
9434 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009435 ConnectionRecord cr = r.get(i);
9436 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9437 continue;
9438 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009439 if (dumpPackage != null && (cr.binding.client == null
9440 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9441 continue;
9442 }
9443 if (!printed) {
9444 if (needSep) pw.println(" ");
9445 needSep = true;
9446 pw.println(" Connection bindings to services:");
9447 printed = true;
9448 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009449 pw.print(" * "); pw.println(cr);
9450 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009452 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009453 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009454 }
9455 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009456
9457 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009458 }
9459
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009462 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009463
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009464 ItemMatcher matcher = new ItemMatcher();
9465 matcher.build(args, opti);
9466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009468
9469 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009470
9471 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009472 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009473 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009474 ContentProviderRecord r = mLaunchingProviders.get(i);
9475 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9476 continue;
9477 }
9478 if (!printed) {
9479 if (needSep) pw.println(" ");
9480 needSep = true;
9481 pw.println(" Launching content providers:");
9482 printed = true;
9483 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009485 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009486 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009487 }
9488
9489 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009490 if (needSep) pw.println();
9491 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009492 pw.println("Granted Uri Permissions:");
9493 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9494 int uid = mGrantedUriPermissions.keyAt(i);
9495 HashMap<Uri, UriPermission> perms
9496 = mGrantedUriPermissions.valueAt(i);
9497 pw.print(" * UID "); pw.print(uid);
9498 pw.println(" holds:");
9499 for (UriPermission perm : perms.values()) {
9500 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009501 if (dumpAll) {
9502 perm.dump(pw, " ");
9503 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009504 }
9505 }
9506 needSep = true;
9507 }
9508
9509 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510 }
9511
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009512 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009513 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009514 boolean needSep = false;
9515
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009516 if (mIntentSenderRecords.size() > 0) {
9517 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009518 Iterator<WeakReference<PendingIntentRecord>> it
9519 = mIntentSenderRecords.values().iterator();
9520 while (it.hasNext()) {
9521 WeakReference<PendingIntentRecord> ref = it.next();
9522 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009523 if (dumpPackage != null && (rec == null
9524 || !dumpPackage.equals(rec.key.packageName))) {
9525 continue;
9526 }
9527 if (!printed) {
9528 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9529 printed = true;
9530 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009531 needSep = true;
9532 if (rec != null) {
9533 pw.print(" * "); pw.println(rec);
9534 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009535 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009536 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009537 } else {
9538 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009539 }
9540 }
9541 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009542
9543 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 }
9545
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009547 String prefix, String label, boolean complete, boolean brief, boolean client,
9548 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009550 boolean needNL = false;
9551 final String innerPrefix = prefix + " ";
9552 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009554 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009555 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9556 continue;
9557 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009558 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009559 if (needNL) {
9560 pw.println(" ");
9561 needNL = false;
9562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 if (lastTask != r.task) {
9564 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009565 pw.print(prefix);
9566 pw.print(full ? "* " : " ");
9567 pw.println(lastTask);
9568 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009569 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009570 } else if (complete) {
9571 // Complete + brief == give a summary. Isn't that obvious?!?
9572 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009573 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009574 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009575 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009578 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9579 pw.print(" #"); pw.print(i); pw.print(": ");
9580 pw.println(r);
9581 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 r.dump(pw, innerPrefix);
9583 } else if (complete) {
9584 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009585 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 if (r.app != null) {
9587 pw.print(innerPrefix); pw.println(r.app);
9588 }
9589 }
9590 if (client && r.app != null && r.app.thread != null) {
9591 // flush anything that is already in the PrintWriter since the thread is going
9592 // to write to the file descriptor directly
9593 pw.flush();
9594 try {
9595 TransferPipe tp = new TransferPipe();
9596 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009597 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9598 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009599 // Short timeout, since blocking here can
9600 // deadlock with the application.
9601 tp.go(fd, 2000);
9602 } finally {
9603 tp.kill();
9604 }
9605 } catch (IOException e) {
9606 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9607 } catch (RemoteException e) {
9608 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9609 }
9610 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009612 }
9613 }
9614
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009615 private static String buildOomTag(String prefix, String space, int val, int base) {
9616 if (val == base) {
9617 if (space == null) return prefix;
9618 return prefix + " ";
9619 }
9620 return prefix + "+" + Integer.toString(val-base);
9621 }
9622
9623 private static final int dumpProcessList(PrintWriter pw,
9624 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009625 String prefix, String normalLabel, String persistentLabel,
9626 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009627 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009628 final int N = list.size()-1;
9629 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009630 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009631 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9632 continue;
9633 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009634 pw.println(String.format("%s%s #%2d: %s",
9635 prefix, (r.persistent ? persistentLabel : normalLabel),
9636 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 if (r.persistent) {
9638 numPers++;
9639 }
9640 }
9641 return numPers;
9642 }
9643
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009644 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009645 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009646 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009647 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009648
Dianne Hackborn905577f2011-09-07 18:31:28 -07009649 ArrayList<Pair<ProcessRecord, Integer>> list
9650 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9651 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009652 ProcessRecord r = origList.get(i);
9653 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9654 continue;
9655 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009656 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9657 }
9658
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009659 if (list.size() <= 0) {
9660 return false;
9661 }
9662
Dianne Hackborn905577f2011-09-07 18:31:28 -07009663 Comparator<Pair<ProcessRecord, Integer>> comparator
9664 = new Comparator<Pair<ProcessRecord, Integer>>() {
9665 @Override
9666 public int compare(Pair<ProcessRecord, Integer> object1,
9667 Pair<ProcessRecord, Integer> object2) {
9668 if (object1.first.setAdj != object2.first.setAdj) {
9669 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9670 }
9671 if (object1.second.intValue() != object2.second.intValue()) {
9672 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9673 }
9674 return 0;
9675 }
9676 };
9677
9678 Collections.sort(list, comparator);
9679
Dianne Hackborn287952c2010-09-22 22:34:31 -07009680 final long curRealtime = SystemClock.elapsedRealtime();
9681 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9682 final long curUptime = SystemClock.uptimeMillis();
9683 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9684
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009686 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009687 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009688 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009689 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009690 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9691 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009692 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9693 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009694 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9695 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009696 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9697 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009698 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009699 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009700 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9701 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9702 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9703 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9704 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9705 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9706 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9707 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009708 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9709 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009710 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9711 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009712 } else {
9713 oomAdj = Integer.toString(r.setAdj);
9714 }
9715 String schedGroup;
9716 switch (r.setSchedGroup) {
9717 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9718 schedGroup = "B";
9719 break;
9720 case Process.THREAD_GROUP_DEFAULT:
9721 schedGroup = "F";
9722 break;
9723 default:
9724 schedGroup = Integer.toString(r.setSchedGroup);
9725 break;
9726 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009727 String foreground;
9728 if (r.foregroundActivities) {
9729 foreground = "A";
9730 } else if (r.foregroundServices) {
9731 foreground = "S";
9732 } else {
9733 foreground = " ";
9734 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009735 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009736 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009737 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9738 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009739 if (r.adjSource != null || r.adjTarget != null) {
9740 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009741 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009742 if (r.adjTarget instanceof ComponentName) {
9743 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9744 } else if (r.adjTarget != null) {
9745 pw.print(r.adjTarget.toString());
9746 } else {
9747 pw.print("{null}");
9748 }
9749 pw.print("<=");
9750 if (r.adjSource instanceof ProcessRecord) {
9751 pw.print("Proc{");
9752 pw.print(((ProcessRecord)r.adjSource).toShortString());
9753 pw.println("}");
9754 } else if (r.adjSource != null) {
9755 pw.println(r.adjSource.toString());
9756 } else {
9757 pw.println("{null}");
9758 }
9759 }
9760 if (inclDetails) {
9761 pw.print(prefix);
9762 pw.print(" ");
9763 pw.print("oom: max="); pw.print(r.maxAdj);
9764 pw.print(" hidden="); pw.print(r.hiddenAdj);
9765 pw.print(" curRaw="); pw.print(r.curRawAdj);
9766 pw.print(" setRaw="); pw.print(r.setRawAdj);
9767 pw.print(" cur="); pw.print(r.curAdj);
9768 pw.print(" set="); pw.println(r.setAdj);
9769 pw.print(prefix);
9770 pw.print(" ");
9771 pw.print("keeping="); pw.print(r.keeping);
9772 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009773 pw.print(" empty="); pw.print(r.empty);
9774 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009775
9776 if (!r.keeping) {
9777 if (r.lastWakeTime != 0) {
9778 long wtime;
9779 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9780 synchronized (stats) {
9781 wtime = stats.getProcessWakeTime(r.info.uid,
9782 r.pid, curRealtime);
9783 }
9784 long timeUsed = wtime - r.lastWakeTime;
9785 pw.print(prefix);
9786 pw.print(" ");
9787 pw.print("keep awake over ");
9788 TimeUtils.formatDuration(realtimeSince, pw);
9789 pw.print(" used ");
9790 TimeUtils.formatDuration(timeUsed, pw);
9791 pw.print(" (");
9792 pw.print((timeUsed*100)/realtimeSince);
9793 pw.println("%)");
9794 }
9795 if (r.lastCpuTime != 0) {
9796 long timeUsed = r.curCpuTime - r.lastCpuTime;
9797 pw.print(prefix);
9798 pw.print(" ");
9799 pw.print("run cpu over ");
9800 TimeUtils.formatDuration(uptimeSince, pw);
9801 pw.print(" used ");
9802 TimeUtils.formatDuration(timeUsed, pw);
9803 pw.print(" (");
9804 pw.print((timeUsed*100)/uptimeSince);
9805 pw.println("%)");
9806 }
9807 }
9808 }
9809 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009810 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009811 }
9812
Dianne Hackbornb437e092011-08-05 17:50:29 -07009813 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 ArrayList<ProcessRecord> procs;
9815 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009816 if (args != null && args.length > start
9817 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009818 procs = new ArrayList<ProcessRecord>();
9819 int pid = -1;
9820 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009821 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009822 } catch (NumberFormatException e) {
9823
9824 }
9825 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9826 ProcessRecord proc = mLruProcesses.get(i);
9827 if (proc.pid == pid) {
9828 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009829 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009830 procs.add(proc);
9831 }
9832 }
9833 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009834 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009835 return null;
9836 }
9837 } else {
9838 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9839 }
9840 }
9841 return procs;
9842 }
9843
9844 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9845 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009846 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 if (procs == null) {
9848 return;
9849 }
9850
9851 long uptime = SystemClock.uptimeMillis();
9852 long realtime = SystemClock.elapsedRealtime();
9853 pw.println("Applications Graphics Acceleration Info:");
9854 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9855
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9857 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009858 if (r.thread != null) {
9859 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9860 pw.flush();
9861 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009862 TransferPipe tp = new TransferPipe();
9863 try {
9864 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9865 tp.go(fd);
9866 } finally {
9867 tp.kill();
9868 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009869 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009870 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009872 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009873 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009874 pw.flush();
9875 }
9876 }
9877 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009878 }
9879
Jeff Brown6754ba22011-12-14 20:20:01 -08009880 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9881 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9882 if (procs == null) {
9883 return;
9884 }
9885
9886 pw.println("Applications Database Info:");
9887
9888 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9889 ProcessRecord r = procs.get(i);
9890 if (r.thread != null) {
9891 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9892 pw.flush();
9893 try {
9894 TransferPipe tp = new TransferPipe();
9895 try {
9896 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9897 tp.go(fd);
9898 } finally {
9899 tp.kill();
9900 }
9901 } catch (IOException e) {
9902 pw.println("Failure while dumping the app: " + r);
9903 pw.flush();
9904 } catch (RemoteException e) {
9905 pw.println("Got a RemoteException while dumping the app " + r);
9906 pw.flush();
9907 }
9908 }
9909 }
9910 }
9911
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009912 final static class MemItem {
9913 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009914 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009915 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009916 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009917 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009918
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009919 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009920 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009921 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009922 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009923 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009924 }
9925 }
9926
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009927 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009928 boolean sort) {
9929 if (sort) {
9930 Collections.sort(items, new Comparator<MemItem>() {
9931 @Override
9932 public int compare(MemItem lhs, MemItem rhs) {
9933 if (lhs.pss < rhs.pss) {
9934 return 1;
9935 } else if (lhs.pss > rhs.pss) {
9936 return -1;
9937 }
9938 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009939 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009940 });
9941 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009942
9943 for (int i=0; i<items.size(); i++) {
9944 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009945 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009946 if (mi.subitems != null) {
9947 dumpMemItems(pw, prefix + " ", mi.subitems, true);
9948 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009949 }
9950 }
9951
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009952 // These are in KB.
9953 static final long[] DUMP_MEM_BUCKETS = new long[] {
9954 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
9955 120*1024, 160*1024, 200*1024,
9956 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
9957 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
9958 };
9959
Dianne Hackborn672342c2011-11-29 11:29:02 -08009960 static final void appendMemBucket(StringBuilder out, long memKB, String label,
9961 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009962 int start = label.lastIndexOf('.');
9963 if (start >= 0) start++;
9964 else start = 0;
9965 int end = label.length();
9966 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
9967 if (DUMP_MEM_BUCKETS[i] >= memKB) {
9968 long bucket = DUMP_MEM_BUCKETS[i]/1024;
9969 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009970 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009971 out.append(label, start, end);
9972 return;
9973 }
9974 }
9975 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08009976 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009977 out.append(label, start, end);
9978 }
9979
9980 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
9981 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
9982 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
9983 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
9984 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
9985 };
9986 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
9987 "System", "Persistent", "Foreground",
9988 "Visible", "Perceptible", "Heavy Weight",
9989 "Backup", "A Services", "Home", "Previous",
9990 "B Services", "Background"
9991 };
9992
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009993 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009994 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -08009995 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009996 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08009997 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -07009998
9999 int opti = 0;
10000 while (opti < args.length) {
10001 String opt = args[opti];
10002 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10003 break;
10004 }
10005 opti++;
10006 if ("-a".equals(opt)) {
10007 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010008 } else if ("--oom".equals(opt)) {
10009 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010010 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010011 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010012 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010013 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010014 pw.println("If [process] is specified it can be the name or ");
10015 pw.println("pid of a specific process to dump.");
10016 return;
10017 } else {
10018 pw.println("Unknown argument: " + opt + "; use -h for help");
10019 }
10020 }
10021
10022 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010023 if (procs == null) {
10024 return;
10025 }
10026
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010027 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010028 long uptime = SystemClock.uptimeMillis();
10029 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010030
10031 if (procs.size() == 1 || isCheckinRequest) {
10032 dumpAll = true;
10033 }
10034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010035 if (isCheckinRequest) {
10036 // short checkin version
10037 pw.println(uptime + "," + realtime);
10038 pw.flush();
10039 } else {
10040 pw.println("Applications Memory Usage (kB):");
10041 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10042 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010043
Dianne Hackbornb437e092011-08-05 17:50:29 -070010044 String[] innerArgs = new String[args.length-opti];
10045 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10046
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010047 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10048 long nativePss=0, dalvikPss=0, otherPss=0;
10049 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10050
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010051 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10052 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10053 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010054
10055 long totalPss = 0;
10056
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010057 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10058 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010059 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010060 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010061 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10062 pw.flush();
10063 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010064 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010065 if (dumpAll) {
10066 try {
10067 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10068 } catch (RemoteException e) {
10069 if (!isCheckinRequest) {
10070 pw.println("Got RemoteException!");
10071 pw.flush();
10072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010073 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010074 } else {
10075 mi = new Debug.MemoryInfo();
10076 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010077 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010078
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010079 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010080 long myTotalPss = mi.getTotalPss();
10081 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010082 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010083 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010084 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010085
10086 nativePss += mi.nativePss;
10087 dalvikPss += mi.dalvikPss;
10088 otherPss += mi.otherPss;
10089 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10090 long mem = mi.getOtherPss(j);
10091 miscPss[j] += mem;
10092 otherPss -= mem;
10093 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010094
10095 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010096 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10097 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010098 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010099 if (oomProcs[oomIndex] == null) {
10100 oomProcs[oomIndex] = new ArrayList<MemItem>();
10101 }
10102 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010103 break;
10104 }
10105 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010107 }
10108 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010109
10110 if (!isCheckinRequest && procs.size() > 1) {
10111 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10112
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010113 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10114 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10115 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010116 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010117 String label = Debug.MemoryInfo.getOtherLabel(j);
10118 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010119 }
10120
Dianne Hackbornb437e092011-08-05 17:50:29 -070010121 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10122 for (int j=0; j<oomPss.length; j++) {
10123 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010124 String label = DUMP_MEM_OOM_LABEL[j];
10125 MemItem item = new MemItem(label, label, oomPss[j],
10126 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010127 item.subitems = oomProcs[j];
10128 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010129 }
10130 }
10131
Dianne Hackborn672342c2011-11-29 11:29:02 -080010132 if (outTag != null || outStack != null) {
10133 if (outTag != null) {
10134 appendMemBucket(outTag, totalPss, "total", false);
10135 }
10136 if (outStack != null) {
10137 appendMemBucket(outStack, totalPss, "total", true);
10138 }
10139 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010140 for (int i=0; i<oomMems.size(); i++) {
10141 MemItem miCat = oomMems.get(i);
10142 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10143 continue;
10144 }
10145 if (miCat.id < ProcessList.SERVICE_ADJ
10146 || miCat.id == ProcessList.HOME_APP_ADJ
10147 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010148 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10149 outTag.append(" / ");
10150 }
10151 if (outStack != null) {
10152 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10153 if (firstLine) {
10154 outStack.append(":");
10155 firstLine = false;
10156 }
10157 outStack.append("\n\t at ");
10158 } else {
10159 outStack.append("$");
10160 }
10161 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010162 for (int j=0; j<miCat.subitems.size(); j++) {
10163 MemItem mi = miCat.subitems.get(j);
10164 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010165 if (outTag != null) {
10166 outTag.append(" ");
10167 }
10168 if (outStack != null) {
10169 outStack.append("$");
10170 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010171 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010172 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10173 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10174 }
10175 if (outStack != null) {
10176 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10177 }
10178 }
10179 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10180 outStack.append("(");
10181 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10182 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10183 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10184 outStack.append(":");
10185 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10186 }
10187 }
10188 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010189 }
10190 }
10191 }
10192 }
10193
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010194 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010195 pw.println();
10196 pw.println("Total PSS by process:");
10197 dumpMemItems(pw, " ", procMems, true);
10198 pw.println();
10199 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 pw.println("Total PSS by OOM adjustment:");
10201 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010202 if (!oomOnly) {
10203 PrintWriter out = categoryPw != null ? categoryPw : pw;
10204 out.println();
10205 out.println("Total PSS by category:");
10206 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010207 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010208 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010209 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010211 }
10212
10213 /**
10214 * Searches array of arguments for the specified string
10215 * @param args array of argument strings
10216 * @param value value to search for
10217 * @return true if the value is contained in the array
10218 */
10219 private static boolean scanArgs(String[] args, String value) {
10220 if (args != null) {
10221 for (String arg : args) {
10222 if (value.equals(arg)) {
10223 return true;
10224 }
10225 }
10226 }
10227 return false;
10228 }
10229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010230 private final void killServicesLocked(ProcessRecord app,
10231 boolean allowRestart) {
10232 // Report disconnected services.
10233 if (false) {
10234 // XXX we are letting the client link to the service for
10235 // death notifications.
10236 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010237 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010238 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010239 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010240 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010241 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010242 = r.connections.values().iterator();
10243 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010244 ArrayList<ConnectionRecord> cl = jt.next();
10245 for (int i=0; i<cl.size(); i++) {
10246 ConnectionRecord c = cl.get(i);
10247 if (c.binding.client != app) {
10248 try {
10249 //c.conn.connected(r.className, null);
10250 } catch (Exception e) {
10251 // todo: this should be asynchronous!
10252 Slog.w(TAG, "Exception thrown disconnected servce "
10253 + r.shortName
10254 + " from app " + app.processName, e);
10255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010256 }
10257 }
10258 }
10259 }
10260 }
10261 }
10262 }
10263
10264 // Clean up any connections this application has to other services.
10265 if (app.connections.size() > 0) {
10266 Iterator<ConnectionRecord> it = app.connections.iterator();
10267 while (it.hasNext()) {
10268 ConnectionRecord r = it.next();
10269 removeConnectionLocked(r, app, null);
10270 }
10271 }
10272 app.connections.clear();
10273
10274 if (app.services.size() != 0) {
10275 // Any services running in the application need to be placed
10276 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010277 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010278 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010279 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010280 synchronized (sr.stats.getBatteryStats()) {
10281 sr.stats.stopLaunchedLocked();
10282 }
10283 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010284 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010286 if (mStoppingServices.remove(sr)) {
10287 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10288 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010289
10290 boolean hasClients = sr.bindings.size() > 0;
10291 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010292 Iterator<IntentBindRecord> bindings
10293 = sr.bindings.values().iterator();
10294 while (bindings.hasNext()) {
10295 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010296 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 + ": shouldUnbind=" + b.hasBound);
10298 b.binder = null;
10299 b.requested = b.received = b.hasBound = false;
10300 }
10301 }
10302
Dianne Hackborn070783f2010-12-29 16:46:28 -080010303 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10304 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010305 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010306 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010307 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 sr.crashCount, sr.shortName, app.pid);
10309 bringDownServiceLocked(sr, true);
10310 } else if (!allowRestart) {
10311 bringDownServiceLocked(sr, true);
10312 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010313 boolean canceled = scheduleServiceRestartLocked(sr, true);
10314
10315 // Should the service remain running? Note that in the
10316 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010317 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010318 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10319 if (sr.pendingStarts.size() == 0) {
10320 sr.startRequested = false;
10321 if (!hasClients) {
10322 // Whoops, no reason to restart!
10323 bringDownServiceLocked(sr, true);
10324 }
10325 }
10326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010327 }
10328 }
10329
10330 if (!allowRestart) {
10331 app.services.clear();
10332 }
10333 }
10334
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010335 // Make sure we have no more records on the stopping list.
10336 int i = mStoppingServices.size();
10337 while (i > 0) {
10338 i--;
10339 ServiceRecord sr = mStoppingServices.get(i);
10340 if (sr.app == app) {
10341 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010342 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010343 }
10344 }
10345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010346 app.executingServices.clear();
10347 }
10348
10349 private final void removeDyingProviderLocked(ProcessRecord proc,
10350 ContentProviderRecord cpr) {
10351 synchronized (cpr) {
10352 cpr.launchingApp = null;
10353 cpr.notifyAll();
10354 }
10355
Amith Yamasani742a6712011-05-04 14:49:28 -070010356 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010357 String names[] = cpr.info.authority.split(";");
10358 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010359 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 }
10361
10362 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10363 while (cit.hasNext()) {
10364 ProcessRecord capp = cit.next();
10365 if (!capp.persistent && capp.thread != null
10366 && capp.pid != 0
10367 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010368 Slog.i(TAG, "Kill " + capp.processName
10369 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010370 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010371 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010372 capp.processName, capp.setAdj, "dying provider "
10373 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010374 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 }
10376 }
10377
10378 mLaunchingProviders.remove(cpr);
10379 }
10380
10381 /**
10382 * Main code for cleaning up a process when it has gone away. This is
10383 * called both as a result of the process dying, or directly when stopping
10384 * a process when running in single process mode.
10385 */
10386 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010387 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010388 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010389 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010390 }
10391
Dianne Hackborn36124872009-10-08 16:22:03 -070010392 mProcessesToGc.remove(app);
10393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010394 // Dismiss any open dialogs.
10395 if (app.crashDialog != null) {
10396 app.crashDialog.dismiss();
10397 app.crashDialog = null;
10398 }
10399 if (app.anrDialog != null) {
10400 app.anrDialog.dismiss();
10401 app.anrDialog = null;
10402 }
10403 if (app.waitDialog != null) {
10404 app.waitDialog.dismiss();
10405 app.waitDialog = null;
10406 }
10407
10408 app.crashing = false;
10409 app.notResponding = false;
10410
10411 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010412 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010413 app.thread = null;
10414 app.forcingToForeground = null;
10415 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010416 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010417 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010418 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010419
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010420 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010421
10422 boolean restart = false;
10423
10424 int NL = mLaunchingProviders.size();
10425
10426 // Remove published content providers.
10427 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010428 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010430 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010431 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010432 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010433
10434 // See if someone is waiting for this provider... in which
10435 // case we don't remove it, but just let it restart.
10436 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010437 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 for (; i<NL; i++) {
10439 if (mLaunchingProviders.get(i) == cpr) {
10440 restart = true;
10441 break;
10442 }
10443 }
10444 } else {
10445 i = NL;
10446 }
10447
10448 if (i >= NL) {
10449 removeDyingProviderLocked(app, cpr);
10450 NL = mLaunchingProviders.size();
10451 }
10452 }
10453 app.pubProviders.clear();
10454 }
10455
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010456 // Take care of any launching providers waiting for this process.
10457 if (checkAppInLaunchingProvidersLocked(app, false)) {
10458 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010459 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010461 // Unregister from connected content providers.
10462 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010463 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010464 while (it.hasNext()) {
10465 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10466 cpr.clients.remove(app);
10467 }
10468 app.conProviders.clear();
10469 }
10470
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010471 // At this point there may be remaining entries in mLaunchingProviders
10472 // where we were the only one waiting, so they are no longer of use.
10473 // Look for these and clean up if found.
10474 // XXX Commented out for now. Trying to figure out a way to reproduce
10475 // the actual situation to identify what is actually going on.
10476 if (false) {
10477 for (int i=0; i<NL; i++) {
10478 ContentProviderRecord cpr = (ContentProviderRecord)
10479 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010480 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010481 synchronized (cpr) {
10482 cpr.launchingApp = null;
10483 cpr.notifyAll();
10484 }
10485 }
10486 }
10487 }
10488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 skipCurrentReceiverLocked(app);
10490
10491 // Unregister any receivers.
10492 if (app.receivers.size() > 0) {
10493 Iterator<ReceiverList> it = app.receivers.iterator();
10494 while (it.hasNext()) {
10495 removeReceiverLocked(it.next());
10496 }
10497 app.receivers.clear();
10498 }
10499
Christopher Tate181fafa2009-05-14 11:12:14 -070010500 // If the app is undergoing backup, tell the backup manager about it
10501 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010502 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010503 try {
10504 IBackupManager bm = IBackupManager.Stub.asInterface(
10505 ServiceManager.getService(Context.BACKUP_SERVICE));
10506 bm.agentDisconnected(app.info.packageName);
10507 } catch (RemoteException e) {
10508 // can't happen; backup manager is local
10509 }
10510 }
10511
Jeff Sharkey287bd832011-05-28 19:36:26 -070010512 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 // If the caller is restarting this app, then leave it in its
10515 // current lists and let the caller take care of it.
10516 if (restarting) {
10517 return;
10518 }
10519
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010520 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010521 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010522 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010523 mProcessNames.remove(app.processName, app.uid);
10524 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010525 if (mHeavyWeightProcess == app) {
10526 mHeavyWeightProcess = null;
10527 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 } else if (!app.removed) {
10530 // This app is persistent, so we need to keep its record around.
10531 // If it is not already on the pending app list, add it there
10532 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10534 mPersistentStartingProcesses.add(app);
10535 restart = true;
10536 }
10537 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010538 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10539 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010540 mProcessesOnHold.remove(app);
10541
The Android Open Source Project4df24232009-03-05 14:34:35 -080010542 if (app == mHomeProcess) {
10543 mHomeProcess = null;
10544 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010545 if (app == mPreviousProcess) {
10546 mPreviousProcess = null;
10547 }
10548
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010549 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 // We have components that still need to be running in the
10551 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010552 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 startProcessLocked(app, "restart", app.processName);
10554 } else if (app.pid > 0 && app.pid != MY_PID) {
10555 // Goodbye!
10556 synchronized (mPidsSelfLocked) {
10557 mPidsSelfLocked.remove(app.pid);
10558 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10559 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010560 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 }
10562 }
10563
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010564 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10565 // Look through the content providers we are waiting to have launched,
10566 // and if any run in this process then either schedule a restart of
10567 // the process or kill the client waiting for it if this process has
10568 // gone bad.
10569 int NL = mLaunchingProviders.size();
10570 boolean restart = false;
10571 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010572 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010573 if (cpr.launchingApp == app) {
10574 if (!alwaysBad && !app.bad) {
10575 restart = true;
10576 } else {
10577 removeDyingProviderLocked(app, cpr);
10578 NL = mLaunchingProviders.size();
10579 }
10580 }
10581 }
10582 return restart;
10583 }
10584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 // =========================================================
10586 // SERVICES
10587 // =========================================================
10588
10589 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10590 ActivityManager.RunningServiceInfo info =
10591 new ActivityManager.RunningServiceInfo();
10592 info.service = r.name;
10593 if (r.app != null) {
10594 info.pid = r.app.pid;
10595 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010596 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 info.process = r.processName;
10598 info.foreground = r.isForeground;
10599 info.activeSince = r.createTime;
10600 info.started = r.startRequested;
10601 info.clientCount = r.connections.size();
10602 info.crashCount = r.crashCount;
10603 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010604 if (r.isForeground) {
10605 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10606 }
10607 if (r.startRequested) {
10608 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10609 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010610 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010611 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10612 }
10613 if (r.app != null && r.app.persistent) {
10614 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10615 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010616
10617 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10618 for (int i=0; i<connl.size(); i++) {
10619 ConnectionRecord conn = connl.get(i);
10620 if (conn.clientLabel != 0) {
10621 info.clientPackage = conn.binding.client.info.packageName;
10622 info.clientLabel = conn.clientLabel;
10623 return info;
10624 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010625 }
10626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010627 return info;
10628 }
10629
10630 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10631 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010632 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 synchronized (this) {
10634 ArrayList<ActivityManager.RunningServiceInfo> res
10635 = new ArrayList<ActivityManager.RunningServiceInfo>();
10636
Amith Yamasani742a6712011-05-04 14:49:28 -070010637 int userId = UserId.getUserId(Binder.getCallingUid());
10638 if (mServiceMap.getAllServices(userId).size() > 0) {
10639 Iterator<ServiceRecord> it
10640 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 while (it.hasNext() && res.size() < maxNum) {
10642 res.add(makeRunningServiceInfoLocked(it.next()));
10643 }
10644 }
10645
10646 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10647 ServiceRecord r = mRestartingServices.get(i);
10648 ActivityManager.RunningServiceInfo info =
10649 makeRunningServiceInfoLocked(r);
10650 info.restarting = r.nextRestartTime;
10651 res.add(info);
10652 }
10653
10654 return res;
10655 }
10656 }
10657
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010658 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010659 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010660 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010661 int userId = UserId.getUserId(Binder.getCallingUid());
10662 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010663 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010664 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10665 for (int i=0; i<conn.size(); i++) {
10666 if (conn.get(i).clientIntent != null) {
10667 return conn.get(i).clientIntent;
10668 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010669 }
10670 }
10671 }
10672 }
10673 return null;
10674 }
10675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010676 private final ServiceRecord findServiceLocked(ComponentName name,
10677 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010678 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010679 return r == token ? r : null;
10680 }
10681
10682 private final class ServiceLookupResult {
10683 final ServiceRecord record;
10684 final String permission;
10685
10686 ServiceLookupResult(ServiceRecord _record, String _permission) {
10687 record = _record;
10688 permission = _permission;
10689 }
10690 };
10691
10692 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010693 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 ServiceRecord r = null;
10695 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010696 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010697 }
10698 if (r == null) {
10699 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010700 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 }
10702
10703 if (r == null) {
10704 try {
10705 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010706 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010707 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708 ServiceInfo sInfo =
10709 rInfo != null ? rInfo.serviceInfo : null;
10710 if (sInfo == null) {
10711 return null;
10712 }
10713
10714 ComponentName name = new ComponentName(
10715 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010716 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010717 } catch (RemoteException ex) {
10718 // pm is in same process, this will never happen.
10719 }
10720 }
10721 if (r != null) {
10722 int callingPid = Binder.getCallingPid();
10723 int callingUid = Binder.getCallingUid();
10724 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010725 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010727 if (!r.exported) {
10728 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10729 + " from pid=" + callingPid
10730 + ", uid=" + callingUid
10731 + " that is not exported from uid " + r.appInfo.uid);
10732 return new ServiceLookupResult(null, "not exported from uid "
10733 + r.appInfo.uid);
10734 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010735 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 + " from pid=" + callingPid
10737 + ", uid=" + callingUid
10738 + " requires " + r.permission);
10739 return new ServiceLookupResult(null, r.permission);
10740 }
10741 return new ServiceLookupResult(r, null);
10742 }
10743 return null;
10744 }
10745
10746 private class ServiceRestarter implements Runnable {
10747 private ServiceRecord mService;
10748
10749 void setService(ServiceRecord service) {
10750 mService = service;
10751 }
10752
10753 public void run() {
10754 synchronized(ActivityManagerService.this) {
10755 performServiceRestartLocked(mService);
10756 }
10757 }
10758 }
10759
10760 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010761 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010762 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010763 if (DEBUG_SERVICE)
10764 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010765 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010767 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010768 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010770 if (r == null) {
10771 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010772 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 if (r == null) {
10775 try {
10776 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010777 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010778 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 ServiceInfo sInfo =
10780 rInfo != null ? rInfo.serviceInfo : null;
10781 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010782 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010783 ": not found");
10784 return null;
10785 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010786 if (userId > 0) {
10787 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 ComponentName name = new ComponentName(
10790 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010791 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010793 Intent.FilterComparison filter = new Intent.FilterComparison(
10794 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 ServiceRestarter res = new ServiceRestarter();
10796 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10797 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10798 synchronized (stats) {
10799 ss = stats.getServiceStatsLocked(
10800 sInfo.applicationInfo.uid, sInfo.packageName,
10801 sInfo.name);
10802 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010803 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010805 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10806 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010807
10808 // Make sure this component isn't in the pending list.
10809 int N = mPendingServices.size();
10810 for (int i=0; i<N; i++) {
10811 ServiceRecord pr = mPendingServices.get(i);
10812 if (pr.name.equals(name)) {
10813 mPendingServices.remove(i);
10814 i--;
10815 N--;
10816 }
10817 }
10818 }
10819 } catch (RemoteException ex) {
10820 // pm is in same process, this will never happen.
10821 }
10822 }
10823 if (r != null) {
10824 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010825 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010827 if (!r.exported) {
10828 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10829 + " from pid=" + callingPid
10830 + ", uid=" + callingUid
10831 + " that is not exported from uid " + r.appInfo.uid);
10832 return new ServiceLookupResult(null, "not exported from uid "
10833 + r.appInfo.uid);
10834 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010835 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010836 + " from pid=" + callingPid
10837 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 + " requires " + r.permission);
10839 return new ServiceLookupResult(null, r.permission);
10840 }
10841 return new ServiceLookupResult(r, null);
10842 }
10843 return null;
10844 }
10845
Dianne Hackborn287952c2010-09-22 22:34:31 -070010846 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10847 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10848 + why + " of " + r + " in app " + r.app);
10849 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10850 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010851 long now = SystemClock.uptimeMillis();
10852 if (r.executeNesting == 0 && r.app != null) {
10853 if (r.app.executingServices.size() == 0) {
10854 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10855 msg.obj = r.app;
10856 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10857 }
10858 r.app.executingServices.add(r);
10859 }
10860 r.executeNesting++;
10861 r.executingStart = now;
10862 }
10863
10864 private final void sendServiceArgsLocked(ServiceRecord r,
10865 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010866 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 if (N == 0) {
10868 return;
10869 }
10870
Dianne Hackborn39792d22010-08-19 18:01:52 -070010871 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010872 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010873 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010874 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10875 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010876 if (si.intent == null && N > 1) {
10877 // If somehow we got a dummy null intent in the middle,
10878 // then skip it. DO NOT skip a null intent when it is
10879 // the only one in the list -- this is to support the
10880 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010881 continue;
10882 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010883 si.deliveredTime = SystemClock.uptimeMillis();
10884 r.deliveredStarts.add(si);
10885 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010886 if (si.neededGrants != null) {
10887 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10888 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010889 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010890 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 if (!oomAdjusted) {
10892 oomAdjusted = true;
10893 updateOomAdjLocked(r.app);
10894 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010895 int flags = 0;
10896 if (si.deliveryCount > 0) {
10897 flags |= Service.START_FLAG_RETRY;
10898 }
10899 if (si.doneExecutingCount > 0) {
10900 flags |= Service.START_FLAG_REDELIVERY;
10901 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010902 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010903 } catch (RemoteException e) {
10904 // Remote process gone... we'll let the normal cleanup take
10905 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010906 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010907 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010909 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 break;
10911 }
10912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 }
10914
10915 private final boolean requestServiceBindingLocked(ServiceRecord r,
10916 IntentBindRecord i, boolean rebind) {
10917 if (r.app == null || r.app.thread == null) {
10918 // If service is not currently running, can't yet bind.
10919 return false;
10920 }
10921 if ((!i.requested || rebind) && i.apps.size() > 0) {
10922 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010923 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010924 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10925 if (!rebind) {
10926 i.requested = true;
10927 }
10928 i.hasBound = true;
10929 i.doRebind = false;
10930 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010931 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010932 return false;
10933 }
10934 }
10935 return true;
10936 }
10937
10938 private final void requestServiceBindingsLocked(ServiceRecord r) {
10939 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10940 while (bindings.hasNext()) {
10941 IntentBindRecord i = bindings.next();
10942 if (!requestServiceBindingLocked(r, i, false)) {
10943 break;
10944 }
10945 }
10946 }
10947
10948 private final void realStartServiceLocked(ServiceRecord r,
10949 ProcessRecord app) throws RemoteException {
10950 if (app.thread == null) {
10951 throw new RemoteException();
10952 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010953 if (DEBUG_MU)
10954 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010955 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010956 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070010957 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010958
10959 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010960 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010961 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010962
10963 boolean created = false;
10964 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010965 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010966 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010967 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070010969 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 synchronized (r.stats.getBatteryStats()) {
10971 r.stats.startLaunchedLocked();
10972 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070010973 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010974 app.thread.scheduleCreateService(r, r.serviceInfo,
10975 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010976 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 created = true;
10978 } finally {
10979 if (!created) {
10980 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010981 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010982 }
10983 }
10984
10985 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010986
10987 // If the service is in the started state, and there are no
10988 // pending arguments, then fake up one so its onStartCommand() will
10989 // be called.
10990 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010991 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010992 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010993 }
10994
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010995 sendServiceArgsLocked(r, true);
10996 }
10997
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010998 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
10999 boolean allowCancel) {
11000 boolean canceled = false;
11001
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011002 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011003 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011004 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011005
Dianne Hackborn070783f2010-12-29 16:46:28 -080011006 if ((r.serviceInfo.applicationInfo.flags
11007 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11008 minDuration /= 4;
11009 }
11010
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011011 // Any delivered but not yet finished starts should be put back
11012 // on the pending list.
11013 final int N = r.deliveredStarts.size();
11014 if (N > 0) {
11015 for (int i=N-1; i>=0; i--) {
11016 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011017 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011018 if (si.intent == null) {
11019 // We'll generate this again if needed.
11020 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11021 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11022 r.pendingStarts.add(0, si);
11023 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11024 dur *= 2;
11025 if (minDuration < dur) minDuration = dur;
11026 if (resetTime < dur) resetTime = dur;
11027 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011028 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011029 + r.name);
11030 canceled = true;
11031 }
11032 }
11033 r.deliveredStarts.clear();
11034 }
11035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 r.totalRestartCount++;
11037 if (r.restartDelay == 0) {
11038 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011039 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 } else {
11041 // If it has been a "reasonably long time" since the service
11042 // was started, then reset our restart duration back to
11043 // the beginning, so we don't infinitely increase the duration
11044 // on a service that just occasionally gets killed (which is
11045 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011046 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011047 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011048 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011049 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011050 if ((r.serviceInfo.applicationInfo.flags
11051 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11052 // Services in peristent processes will restart much more
11053 // quickly, since they are pretty important. (Think SystemUI).
11054 r.restartDelay += minDuration/2;
11055 } else {
11056 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11057 if (r.restartDelay < minDuration) {
11058 r.restartDelay = minDuration;
11059 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011061 }
11062 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011063
11064 r.nextRestartTime = now + r.restartDelay;
11065
11066 // Make sure that we don't end up restarting a bunch of services
11067 // all at the same time.
11068 boolean repeat;
11069 do {
11070 repeat = false;
11071 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11072 ServiceRecord r2 = mRestartingServices.get(i);
11073 if (r2 != r && r.nextRestartTime
11074 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11075 && r.nextRestartTime
11076 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11077 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11078 r.restartDelay = r.nextRestartTime - now;
11079 repeat = true;
11080 break;
11081 }
11082 }
11083 } while (repeat);
11084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011085 if (!mRestartingServices.contains(r)) {
11086 mRestartingServices.add(r);
11087 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011088
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011089 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011092 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011094 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011096 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 r.shortName, r.restartDelay);
11098
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011099 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 }
11101
11102 final void performServiceRestartLocked(ServiceRecord r) {
11103 if (!mRestartingServices.contains(r)) {
11104 return;
11105 }
11106 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11107 }
11108
11109 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11110 if (r.restartDelay == 0) {
11111 return false;
11112 }
11113 r.resetRestartCounter();
11114 mRestartingServices.remove(r);
11115 mHandler.removeCallbacks(r.restarter);
11116 return true;
11117 }
11118
11119 private final boolean bringUpServiceLocked(ServiceRecord r,
11120 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011121 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 //r.dump(" ");
11123
Dianne Hackborn36124872009-10-08 16:22:03 -070011124 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 sendServiceArgsLocked(r, false);
11126 return true;
11127 }
11128
11129 if (!whileRestarting && r.restartDelay > 0) {
11130 // If waiting for a restart, then do nothing.
11131 return true;
11132 }
11133
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011134 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011135
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011136 // We are now bringing the service up, so no longer in the
11137 // restarting state.
11138 mRestartingServices.remove(r);
11139
Dianne Hackborne7f97212011-02-24 14:40:20 -080011140 // Service is now being launched, its package can't be stopped.
11141 try {
11142 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011143 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011144 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011145 } catch (IllegalArgumentException e) {
11146 Slog.w(TAG, "Failed trying to unstop package "
11147 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011148 }
11149
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011150 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011151 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011152 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011154 if (!isolated) {
11155 app = getProcessRecordLocked(appName, r.appInfo.uid);
11156 if (DEBUG_MU)
11157 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11158 if (app != null && app.thread != null) {
11159 try {
11160 app.addPackage(r.appInfo.packageName);
11161 realStartServiceLocked(r, app);
11162 return true;
11163 } catch (RemoteException e) {
11164 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11165 }
11166
11167 // If a dead object exception was thrown -- fall through to
11168 // restart the application.
11169 }
11170 } else {
11171 // If this service runs in an isolated process, then each time
11172 // we call startProcessLocked() we will get a new isolated
11173 // process, starting another process if we are currently waiting
11174 // for a previous process to come up. To deal with this, we store
11175 // in the service any current isolated process it is running in or
11176 // waiting to have come up.
11177 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 }
11179
Dianne Hackborn36124872009-10-08 16:22:03 -070011180 // Not running -- get it started, and enqueue this service record
11181 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011182 if (app == null) {
11183 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11184 "service", r.name, false, isolated)) == null) {
11185 Slog.w(TAG, "Unable to launch app "
11186 + r.appInfo.packageName + "/"
11187 + r.appInfo.uid + " for service "
11188 + r.intent.getIntent() + ": process is bad");
11189 bringDownServiceLocked(r, true);
11190 return false;
11191 }
11192 if (isolated) {
11193 r.isolatedProc = app;
11194 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011195 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 mPendingServices.add(r);
11199 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 return true;
11202 }
11203
11204 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011205 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206 //r.dump(" ");
11207
11208 // Does it still need to run?
11209 if (!force && r.startRequested) {
11210 return;
11211 }
11212 if (r.connections.size() > 0) {
11213 if (!force) {
11214 // XXX should probably keep a count of the number of auto-create
11215 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011216 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011217 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011218 ArrayList<ConnectionRecord> cr = it.next();
11219 for (int i=0; i<cr.size(); i++) {
11220 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11221 return;
11222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011223 }
11224 }
11225 }
11226
11227 // Report to all of the connections that the service is no longer
11228 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011229 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011230 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011231 ArrayList<ConnectionRecord> c = it.next();
11232 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011233 ConnectionRecord cr = c.get(i);
11234 // There is still a connection to the service that is
11235 // being brought down. Mark it as dead.
11236 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011237 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011238 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011239 } catch (Exception e) {
11240 Slog.w(TAG, "Failure disconnecting service " + r.name +
11241 " to connection " + c.get(i).conn.asBinder() +
11242 " (in " + c.get(i).binding.client.processName + ")", e);
11243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011244 }
11245 }
11246 }
11247
11248 // Tell the service that it has been unbound.
11249 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11250 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11251 while (it.hasNext()) {
11252 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011253 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 + ": hasBound=" + ibr.hasBound);
11255 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11256 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011257 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011258 updateOomAdjLocked(r.app);
11259 ibr.hasBound = false;
11260 r.app.thread.scheduleUnbindService(r,
11261 ibr.intent.getIntent());
11262 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011263 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 + r.shortName, e);
11265 serviceDoneExecutingLocked(r, true);
11266 }
11267 }
11268 }
11269 }
11270
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011272 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 System.identityHashCode(r), r.shortName,
11274 (r.app != null) ? r.app.pid : -1);
11275
Amith Yamasani742a6712011-05-04 14:49:28 -070011276 mServiceMap.removeServiceByName(r.name, r.userId);
11277 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 r.totalRestartCount = 0;
11279 unscheduleServiceRestartLocked(r);
11280
11281 // Also make sure it is not on the pending list.
11282 int N = mPendingServices.size();
11283 for (int i=0; i<N; i++) {
11284 if (mPendingServices.get(i) == r) {
11285 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011286 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011287 i--;
11288 N--;
11289 }
11290 }
11291
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011292 r.cancelNotification();
11293 r.isForeground = false;
11294 r.foregroundId = 0;
11295 r.foregroundNoti = null;
11296
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011297 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011298 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011299 r.pendingStarts.clear();
11300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 if (r.app != null) {
11302 synchronized (r.stats.getBatteryStats()) {
11303 r.stats.stopLaunchedLocked();
11304 }
11305 r.app.services.remove(r);
11306 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011308 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 mStoppingServices.add(r);
11310 updateOomAdjLocked(r.app);
11311 r.app.thread.scheduleStopService(r);
11312 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011313 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 + r.shortName, e);
11315 serviceDoneExecutingLocked(r, true);
11316 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011317 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011319 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011320 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 }
11322 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011323 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011324 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011326
11327 if (r.bindings.size() > 0) {
11328 r.bindings.clear();
11329 }
11330
11331 if (r.restarter instanceof ServiceRestarter) {
11332 ((ServiceRestarter)r.restarter).setService(null);
11333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011334 }
11335
11336 ComponentName startServiceLocked(IApplicationThread caller,
11337 Intent service, String resolvedType,
11338 int callingPid, int callingUid) {
11339 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011340 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 + " type=" + resolvedType + " args=" + service.getExtras());
11342
11343 if (caller != null) {
11344 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11345 if (callerApp == null) {
11346 throw new SecurityException(
11347 "Unable to find app for caller " + caller
11348 + " (pid=" + Binder.getCallingPid()
11349 + ") when starting service " + service);
11350 }
11351 }
11352
11353 ServiceLookupResult res =
11354 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011355 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 if (res == null) {
11357 return null;
11358 }
11359 if (res.record == null) {
11360 return new ComponentName("!", res.permission != null
11361 ? res.permission : "private to package");
11362 }
11363 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011364 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11365 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011366 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011367 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011368 }
11369 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011370 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011371 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011372 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 r.lastActivity = SystemClock.uptimeMillis();
11374 synchronized (r.stats.getBatteryStats()) {
11375 r.stats.startRunningLocked();
11376 }
11377 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11378 return new ComponentName("!", "Service process is bad");
11379 }
11380 return r.name;
11381 }
11382 }
11383
11384 public ComponentName startService(IApplicationThread caller, Intent service,
11385 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011386 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 // Refuse possible leaked file descriptors
11388 if (service != null && service.hasFileDescriptors() == true) {
11389 throw new IllegalArgumentException("File descriptors passed in Intent");
11390 }
11391
Amith Yamasani742a6712011-05-04 14:49:28 -070011392 if (DEBUG_SERVICE)
11393 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 synchronized(this) {
11395 final int callingPid = Binder.getCallingPid();
11396 final int callingUid = Binder.getCallingUid();
11397 final long origId = Binder.clearCallingIdentity();
11398 ComponentName res = startServiceLocked(caller, service,
11399 resolvedType, callingPid, callingUid);
11400 Binder.restoreCallingIdentity(origId);
11401 return res;
11402 }
11403 }
11404
11405 ComponentName startServiceInPackage(int uid,
11406 Intent service, String resolvedType) {
11407 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011408 if (DEBUG_SERVICE)
11409 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011410 final long origId = Binder.clearCallingIdentity();
11411 ComponentName res = startServiceLocked(null, service,
11412 resolvedType, -1, uid);
11413 Binder.restoreCallingIdentity(origId);
11414 return res;
11415 }
11416 }
11417
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011418 private void stopServiceLocked(ServiceRecord service) {
11419 synchronized (service.stats.getBatteryStats()) {
11420 service.stats.stopRunningLocked();
11421 }
11422 service.startRequested = false;
11423 service.callStart = false;
11424 bringDownServiceLocked(service, false);
11425 }
11426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011427 public int stopService(IApplicationThread caller, Intent service,
11428 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011429 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011430 // Refuse possible leaked file descriptors
11431 if (service != null && service.hasFileDescriptors() == true) {
11432 throw new IllegalArgumentException("File descriptors passed in Intent");
11433 }
11434
11435 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011436 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 + " type=" + resolvedType);
11438
11439 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11440 if (caller != null && callerApp == null) {
11441 throw new SecurityException(
11442 "Unable to find app for caller " + caller
11443 + " (pid=" + Binder.getCallingPid()
11444 + ") when stopping service " + service);
11445 }
11446
11447 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011448 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11449 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011450 if (r != null) {
11451 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011452 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011453 try {
11454 stopServiceLocked(r.record);
11455 } finally {
11456 Binder.restoreCallingIdentity(origId);
11457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 return 1;
11459 }
11460 return -1;
11461 }
11462 }
11463
11464 return 0;
11465 }
11466
11467 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011468 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011469 // Refuse possible leaked file descriptors
11470 if (service != null && service.hasFileDescriptors() == true) {
11471 throw new IllegalArgumentException("File descriptors passed in Intent");
11472 }
11473
11474 IBinder ret = null;
11475
11476 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011477 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11478 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011479
11480 if (r != null) {
11481 // r.record is null if findServiceLocked() failed the caller permission check
11482 if (r.record == null) {
11483 throw new SecurityException(
11484 "Permission Denial: Accessing service " + r.record.name
11485 + " from pid=" + Binder.getCallingPid()
11486 + ", uid=" + Binder.getCallingUid()
11487 + " requires " + r.permission);
11488 }
11489 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11490 if (ib != null) {
11491 ret = ib.binder;
11492 }
11493 }
11494 }
11495
11496 return ret;
11497 }
11498
11499 public boolean stopServiceToken(ComponentName className, IBinder token,
11500 int startId) {
11501 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011502 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011503 + " " + token + " startId=" + startId);
11504 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011505 if (r != null) {
11506 if (startId >= 0) {
11507 // Asked to only stop if done with all work. Note that
11508 // to avoid leaks, we will take this as dropping all
11509 // start items up to and including this one.
11510 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11511 if (si != null) {
11512 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011513 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11514 cur.removeUriPermissionsLocked();
11515 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011516 break;
11517 }
11518 }
11519 }
11520
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011521 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011522 return false;
11523 }
11524
11525 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011526 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011527 + " is last, but have " + r.deliveredStarts.size()
11528 + " remaining args");
11529 }
11530 }
11531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532 synchronized (r.stats.getBatteryStats()) {
11533 r.stats.stopRunningLocked();
11534 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011535 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 }
11537 final long origId = Binder.clearCallingIdentity();
11538 bringDownServiceLocked(r, false);
11539 Binder.restoreCallingIdentity(origId);
11540 return true;
11541 }
11542 }
11543 return false;
11544 }
11545
11546 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011547 int id, Notification notification, boolean removeNotification) {
11548 final long origId = Binder.clearCallingIdentity();
11549 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550 synchronized(this) {
11551 ServiceRecord r = findServiceLocked(className, token);
11552 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011553 if (id != 0) {
11554 if (notification == null) {
11555 throw new IllegalArgumentException("null notification");
11556 }
11557 if (r.foregroundId != id) {
11558 r.cancelNotification();
11559 r.foregroundId = id;
11560 }
11561 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11562 r.foregroundNoti = notification;
11563 r.isForeground = true;
11564 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565 if (r.app != null) {
11566 updateServiceForegroundLocked(r.app, true);
11567 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011568 } else {
11569 if (r.isForeground) {
11570 r.isForeground = false;
11571 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011572 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011573 updateServiceForegroundLocked(r.app, true);
11574 }
11575 }
11576 if (removeNotification) {
11577 r.cancelNotification();
11578 r.foregroundId = 0;
11579 r.foregroundNoti = null;
11580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011581 }
11582 }
11583 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011584 } finally {
11585 Binder.restoreCallingIdentity(origId);
11586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 }
11588
11589 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11590 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011591 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011592 if (sr.isForeground) {
11593 anyForeground = true;
11594 break;
11595 }
11596 }
11597 if (anyForeground != proc.foregroundServices) {
11598 proc.foregroundServices = anyForeground;
11599 if (oomAdj) {
11600 updateOomAdjLocked();
11601 }
11602 }
11603 }
11604
11605 public int bindService(IApplicationThread caller, IBinder token,
11606 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011607 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011608 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 // Refuse possible leaked file descriptors
11610 if (service != null && service.hasFileDescriptors() == true) {
11611 throw new IllegalArgumentException("File descriptors passed in Intent");
11612 }
11613
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011614 checkValidCaller(Binder.getCallingUid(), userId);
11615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011617 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011618 + " type=" + resolvedType + " conn=" + connection.asBinder()
11619 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011620 if (DEBUG_MU)
11621 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11622 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11624 if (callerApp == null) {
11625 throw new SecurityException(
11626 "Unable to find app for caller " + caller
11627 + " (pid=" + Binder.getCallingPid()
11628 + ") when binding service " + service);
11629 }
11630
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011631 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011632 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011633 activity = mMainStack.isInStackLocked(token);
11634 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011635 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 return 0;
11637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011638 }
11639
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011640 int clientLabel = 0;
11641 PendingIntent clientIntent = null;
11642
11643 if (callerApp.info.uid == Process.SYSTEM_UID) {
11644 // Hacky kind of thing -- allow system stuff to tell us
11645 // what they are, so we can report this elsewhere for
11646 // others to know why certain services are running.
11647 try {
11648 clientIntent = (PendingIntent)service.getParcelableExtra(
11649 Intent.EXTRA_CLIENT_INTENT);
11650 } catch (RuntimeException e) {
11651 }
11652 if (clientIntent != null) {
11653 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11654 if (clientLabel != 0) {
11655 // There are no useful extras in the intent, trash them.
11656 // System code calling with this stuff just needs to know
11657 // this will happen.
11658 service = service.cloneFilter();
11659 }
11660 }
11661 }
11662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011663 ServiceLookupResult res =
11664 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011665 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 if (res == null) {
11667 return 0;
11668 }
11669 if (res.record == null) {
11670 return -1;
11671 }
11672 ServiceRecord s = res.record;
11673
11674 final long origId = Binder.clearCallingIdentity();
11675
11676 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011677 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011678 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011679 }
11680
11681 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11682 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011683 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684
11685 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011686 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11687 if (clist == null) {
11688 clist = new ArrayList<ConnectionRecord>();
11689 s.connections.put(binder, clist);
11690 }
11691 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 b.connections.add(c);
11693 if (activity != null) {
11694 if (activity.connections == null) {
11695 activity.connections = new HashSet<ConnectionRecord>();
11696 }
11697 activity.connections.add(c);
11698 }
11699 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011700 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11701 b.client.hasAboveClient = true;
11702 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011703 clist = mServiceConnections.get(binder);
11704 if (clist == null) {
11705 clist = new ArrayList<ConnectionRecord>();
11706 mServiceConnections.put(binder, clist);
11707 }
11708 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709
11710 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11711 s.lastActivity = SystemClock.uptimeMillis();
11712 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11713 return 0;
11714 }
11715 }
11716
11717 if (s.app != null) {
11718 // This could have made the service more important.
11719 updateOomAdjLocked(s.app);
11720 }
11721
Joe Onorato8a9b2202010-02-26 18:56:32 -080011722 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723 + ": received=" + b.intent.received
11724 + " apps=" + b.intent.apps.size()
11725 + " doRebind=" + b.intent.doRebind);
11726
11727 if (s.app != null && b.intent.received) {
11728 // Service is already running, so we can immediately
11729 // publish the connection.
11730 try {
11731 c.conn.connected(s.name, b.intent.binder);
11732 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011733 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 + " to connection " + c.conn.asBinder()
11735 + " (in " + c.binding.client.processName + ")", e);
11736 }
11737
11738 // If this is the first app connected back to this binding,
11739 // and the service had previously asked to be told when
11740 // rebound, then do so.
11741 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11742 requestServiceBindingLocked(s, b.intent, true);
11743 }
11744 } else if (!b.intent.requested) {
11745 requestServiceBindingLocked(s, b.intent, false);
11746 }
11747
11748 Binder.restoreCallingIdentity(origId);
11749 }
11750
11751 return 1;
11752 }
11753
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011754 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011755 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 IBinder binder = c.conn.asBinder();
11757 AppBindRecord b = c.binding;
11758 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011759 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11760 if (clist != null) {
11761 clist.remove(c);
11762 if (clist.size() == 0) {
11763 s.connections.remove(binder);
11764 }
11765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766 b.connections.remove(c);
11767 if (c.activity != null && c.activity != skipAct) {
11768 if (c.activity.connections != null) {
11769 c.activity.connections.remove(c);
11770 }
11771 }
11772 if (b.client != skipApp) {
11773 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011774 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11775 b.client.updateHasAboveClientLocked();
11776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011778 clist = mServiceConnections.get(binder);
11779 if (clist != null) {
11780 clist.remove(c);
11781 if (clist.size() == 0) {
11782 mServiceConnections.remove(binder);
11783 }
11784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011785
11786 if (b.connections.size() == 0) {
11787 b.intent.apps.remove(b.client);
11788 }
11789
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011790 if (!c.serviceDead) {
11791 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11792 + ": shouldUnbind=" + b.intent.hasBound);
11793 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11794 && b.intent.hasBound) {
11795 try {
11796 bumpServiceExecutingLocked(s, "unbind");
11797 updateOomAdjLocked(s.app);
11798 b.intent.hasBound = false;
11799 // Assume the client doesn't want to know about a rebind;
11800 // we will deal with that later if it asks for one.
11801 b.intent.doRebind = false;
11802 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11803 } catch (Exception e) {
11804 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11805 serviceDoneExecutingLocked(s, true);
11806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011808
11809 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11810 bringDownServiceLocked(s, false);
11811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 }
11813 }
11814
11815 public boolean unbindService(IServiceConnection connection) {
11816 synchronized (this) {
11817 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011818 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011819 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11820 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011821 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 + connection.asBinder());
11823 return false;
11824 }
11825
11826 final long origId = Binder.clearCallingIdentity();
11827
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011828 while (clist.size() > 0) {
11829 ConnectionRecord r = clist.get(0);
11830 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011831
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011832 if (r.binding.service.app != null) {
11833 // This could have made the service less important.
11834 updateOomAdjLocked(r.binding.service.app);
11835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011836 }
11837
11838 Binder.restoreCallingIdentity(origId);
11839 }
11840
11841 return true;
11842 }
11843
11844 public void publishService(IBinder token, Intent intent, IBinder service) {
11845 // Refuse possible leaked file descriptors
11846 if (intent != null && intent.hasFileDescriptors() == true) {
11847 throw new IllegalArgumentException("File descriptors passed in Intent");
11848 }
11849
11850 synchronized(this) {
11851 if (!(token instanceof ServiceRecord)) {
11852 throw new IllegalArgumentException("Invalid service token");
11853 }
11854 ServiceRecord r = (ServiceRecord)token;
11855
11856 final long origId = Binder.clearCallingIdentity();
11857
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011858 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011859 + " " + intent + ": " + service);
11860 if (r != null) {
11861 Intent.FilterComparison filter
11862 = new Intent.FilterComparison(intent);
11863 IntentBindRecord b = r.bindings.get(filter);
11864 if (b != null && !b.received) {
11865 b.binder = service;
11866 b.requested = true;
11867 b.received = true;
11868 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011869 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011870 = r.connections.values().iterator();
11871 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011872 ArrayList<ConnectionRecord> clist = it.next();
11873 for (int i=0; i<clist.size(); i++) {
11874 ConnectionRecord c = clist.get(i);
11875 if (!filter.equals(c.binding.intent.intent)) {
11876 if (DEBUG_SERVICE) Slog.v(
11877 TAG, "Not publishing to: " + c);
11878 if (DEBUG_SERVICE) Slog.v(
11879 TAG, "Bound intent: " + c.binding.intent.intent);
11880 if (DEBUG_SERVICE) Slog.v(
11881 TAG, "Published intent: " + intent);
11882 continue;
11883 }
11884 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11885 try {
11886 c.conn.connected(r.name, service);
11887 } catch (Exception e) {
11888 Slog.w(TAG, "Failure sending service " + r.name +
11889 " to connection " + c.conn.asBinder() +
11890 " (in " + c.binding.client.processName + ")", e);
11891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011892 }
11893 }
11894 }
11895 }
11896
11897 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11898
11899 Binder.restoreCallingIdentity(origId);
11900 }
11901 }
11902 }
11903
11904 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11905 // Refuse possible leaked file descriptors
11906 if (intent != null && intent.hasFileDescriptors() == true) {
11907 throw new IllegalArgumentException("File descriptors passed in Intent");
11908 }
11909
11910 synchronized(this) {
11911 if (!(token instanceof ServiceRecord)) {
11912 throw new IllegalArgumentException("Invalid service token");
11913 }
11914 ServiceRecord r = (ServiceRecord)token;
11915
11916 final long origId = Binder.clearCallingIdentity();
11917
11918 if (r != null) {
11919 Intent.FilterComparison filter
11920 = new Intent.FilterComparison(intent);
11921 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011922 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011923 + " at " + b + ": apps="
11924 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011925
11926 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011928 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 // Applications have already bound since the last
11930 // unbind, so just rebind right here.
11931 requestServiceBindingLocked(r, b, true);
11932 } else {
11933 // Note to tell the service the next time there is
11934 // a new client.
11935 b.doRebind = true;
11936 }
11937 }
11938
Per Edelberg78f9fff2010-08-30 20:01:35 +020011939 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011940
11941 Binder.restoreCallingIdentity(origId);
11942 }
11943 }
11944 }
11945
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011946 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 synchronized(this) {
11948 if (!(token instanceof ServiceRecord)) {
11949 throw new IllegalArgumentException("Invalid service token");
11950 }
11951 ServiceRecord r = (ServiceRecord)token;
11952 boolean inStopping = mStoppingServices.contains(token);
11953 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011954 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011955 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 + " with incorrect token: given " + token
11957 + ", expected " + r);
11958 return;
11959 }
11960
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011961 if (type == 1) {
11962 // This is a call from a service start... take care of
11963 // book-keeping.
11964 r.callStart = true;
11965 switch (res) {
11966 case Service.START_STICKY_COMPATIBILITY:
11967 case Service.START_STICKY: {
11968 // We are done with the associated start arguments.
11969 r.findDeliveredStart(startId, true);
11970 // Don't stop if killed.
11971 r.stopIfKilled = false;
11972 break;
11973 }
11974 case Service.START_NOT_STICKY: {
11975 // We are done with the associated start arguments.
11976 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011977 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011978 // There is no more work, and this service
11979 // doesn't want to hang around if killed.
11980 r.stopIfKilled = true;
11981 }
11982 break;
11983 }
11984 case Service.START_REDELIVER_INTENT: {
11985 // We'll keep this item until they explicitly
11986 // call stop for it, but keep track of the fact
11987 // that it was delivered.
11988 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11989 if (si != null) {
11990 si.deliveryCount = 0;
11991 si.doneExecutingCount++;
11992 // Don't stop if killed.
11993 r.stopIfKilled = true;
11994 }
11995 break;
11996 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011997 case Service.START_TASK_REMOVED_COMPLETE: {
11998 // Special processing for onTaskRemoved(). Don't
11999 // impact normal onStartCommand() processing.
12000 r.findDeliveredStart(startId, true);
12001 break;
12002 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012003 default:
12004 throw new IllegalArgumentException(
12005 "Unknown service start result: " + res);
12006 }
12007 if (res == Service.START_STICKY_COMPATIBILITY) {
12008 r.callStart = false;
12009 }
12010 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012011 if (DEBUG_MU)
12012 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12013 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 final long origId = Binder.clearCallingIdentity();
12015 serviceDoneExecutingLocked(r, inStopping);
12016 Binder.restoreCallingIdentity(origId);
12017 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012018 Slog.w(TAG, "Done executing unknown service from pid "
12019 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 }
12021 }
12022 }
12023
12024 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012025 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12026 + ": nesting=" + r.executeNesting
12027 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012028 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 r.executeNesting--;
12030 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012031 if (DEBUG_SERVICE) Slog.v(TAG,
12032 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033 r.app.executingServices.remove(r);
12034 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012035 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12036 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012037 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12038 }
12039 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012040 if (DEBUG_SERVICE) Slog.v(TAG,
12041 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012043 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 }
12045 updateOomAdjLocked(r.app);
12046 }
12047 }
12048
12049 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012050 String anrMessage = null;
12051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 synchronized(this) {
12053 if (proc.executingServices.size() == 0 || proc.thread == null) {
12054 return;
12055 }
12056 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12057 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12058 ServiceRecord timeout = null;
12059 long nextTime = 0;
12060 while (it.hasNext()) {
12061 ServiceRecord sr = it.next();
12062 if (sr.executingStart < maxTime) {
12063 timeout = sr;
12064 break;
12065 }
12066 if (sr.executingStart > nextTime) {
12067 nextTime = sr.executingStart;
12068 }
12069 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012070 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012071 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012072 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073 } else {
12074 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12075 msg.obj = proc;
12076 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12077 }
12078 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012079
12080 if (anrMessage != null) {
12081 appNotResponding(proc, null, null, anrMessage);
12082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 }
12084
12085 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012086 // BACKUP AND RESTORE
12087 // =========================================================
12088
12089 // Cause the target app to be launched if necessary and its backup agent
12090 // instantiated. The backup agent will invoke backupAgentCreated() on the
12091 // activity manager to announce its creation.
12092 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012093 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012094 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12095
12096 synchronized(this) {
12097 // !!! TODO: currently no check here that we're already bound
12098 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12099 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12100 synchronized (stats) {
12101 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12102 }
12103
Dianne Hackborne7f97212011-02-24 14:40:20 -080012104 // Backup agent is now in use, its package can't be stopped.
12105 try {
12106 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012107 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012108 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012109 } catch (IllegalArgumentException e) {
12110 Slog.w(TAG, "Failed trying to unstop package "
12111 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012112 }
12113
Christopher Tate181fafa2009-05-14 11:12:14 -070012114 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012115 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12116 ? new ComponentName(app.packageName, app.backupAgentName)
12117 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012118 // startProcessLocked() returns existing proc's record if it's already running
12119 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012120 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012121 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012122 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012123 return false;
12124 }
12125
12126 r.app = proc;
12127 mBackupTarget = r;
12128 mBackupAppName = app.packageName;
12129
Christopher Tate6fa95972009-06-05 18:43:55 -070012130 // Try not to kill the process during backup
12131 updateOomAdjLocked(proc);
12132
Christopher Tate181fafa2009-05-14 11:12:14 -070012133 // If the process is already attached, schedule the creation of the backup agent now.
12134 // If it is not yet live, this will be done when it attaches to the framework.
12135 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012136 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012137 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012138 proc.thread.scheduleCreateBackupAgent(app,
12139 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012140 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012141 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012142 }
12143 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012144 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012145 }
12146 // Invariants: at this point, the target app process exists and the application
12147 // is either already running or in the process of coming up. mBackupTarget and
12148 // mBackupAppName describe the app, so that when it binds back to the AM we
12149 // know that it's scheduled for a backup-agent operation.
12150 }
12151
12152 return true;
12153 }
12154
12155 // A backup agent has just come up
12156 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012157 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012158 + " = " + agent);
12159
12160 synchronized(this) {
12161 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012162 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012163 return;
12164 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012165 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012166
Dianne Hackborn06740692010-09-22 22:46:21 -070012167 long oldIdent = Binder.clearCallingIdentity();
12168 try {
12169 IBackupManager bm = IBackupManager.Stub.asInterface(
12170 ServiceManager.getService(Context.BACKUP_SERVICE));
12171 bm.agentConnected(agentPackageName, agent);
12172 } catch (RemoteException e) {
12173 // can't happen; the backup manager service is local
12174 } catch (Exception e) {
12175 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12176 e.printStackTrace();
12177 } finally {
12178 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012179 }
12180 }
12181
12182 // done with this agent
12183 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012184 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012185 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012186 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012187 return;
12188 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012189
12190 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012191 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012192 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012193 return;
12194 }
12195
Christopher Tate181fafa2009-05-14 11:12:14 -070012196 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012197 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012198 return;
12199 }
12200
Christopher Tate6fa95972009-06-05 18:43:55 -070012201 ProcessRecord proc = mBackupTarget.app;
12202 mBackupTarget = null;
12203 mBackupAppName = null;
12204
12205 // Not backing this app up any more; reset its OOM adjustment
12206 updateOomAdjLocked(proc);
12207
Christopher Tatec7b31e32009-06-10 15:49:30 -070012208 // If the app crashed during backup, 'thread' will be null here
12209 if (proc.thread != null) {
12210 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012211 proc.thread.scheduleDestroyBackupAgent(appInfo,
12212 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012213 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012215 e.printStackTrace();
12216 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012217 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012218 }
12219 }
12220 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012221 // BROADCASTS
12222 // =========================================================
12223
Josh Bartel7f208742010-02-25 11:01:44 -060012224 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 List cur) {
12226 final ContentResolver resolver = mContext.getContentResolver();
12227 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12228 if (list == null) {
12229 return cur;
12230 }
12231 int N = list.size();
12232 for (int i=0; i<N; i++) {
12233 Intent intent = list.get(i);
12234 if (filter.match(resolver, intent, true, TAG) >= 0) {
12235 if (cur == null) {
12236 cur = new ArrayList<Intent>();
12237 }
12238 cur.add(intent);
12239 }
12240 }
12241 return cur;
12242 }
12243
Christopher Tatef46723b2012-01-26 14:19:24 -080012244 boolean isPendingBroadcastProcessLocked(int pid) {
12245 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12246 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248
Christopher Tatef46723b2012-01-26 14:19:24 -080012249 void skipPendingBroadcastLocked(int pid) {
12250 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12251 for (BroadcastQueue queue : mBroadcastQueues) {
12252 queue.skipPendingBroadcastLocked(pid);
12253 }
12254 }
12255
12256 // The app just attached; send any pending broadcasts that it should receive
12257 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12258 boolean didSomething = false;
12259 for (BroadcastQueue queue : mBroadcastQueues) {
12260 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012261 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012262 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012263 }
12264
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012265 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012267 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012268 synchronized(this) {
12269 ProcessRecord callerApp = null;
12270 if (caller != null) {
12271 callerApp = getRecordForAppLocked(caller);
12272 if (callerApp == null) {
12273 throw new SecurityException(
12274 "Unable to find app for caller " + caller
12275 + " (pid=" + Binder.getCallingPid()
12276 + ") when registering receiver " + receiver);
12277 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012278 if (callerApp.info.uid != Process.SYSTEM_UID &&
12279 !callerApp.pkgList.contains(callerPackage)) {
12280 throw new SecurityException("Given caller package " + callerPackage
12281 + " is not running in process " + callerApp);
12282 }
12283 } else {
12284 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 }
12286
12287 List allSticky = null;
12288
12289 // Look for any matching sticky broadcasts...
12290 Iterator actions = filter.actionsIterator();
12291 if (actions != null) {
12292 while (actions.hasNext()) {
12293 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012294 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 }
12296 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012297 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012298 }
12299
12300 // The first sticky in the list is returned directly back to
12301 // the client.
12302 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12303
Joe Onorato8a9b2202010-02-26 18:56:32 -080012304 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305 + ": " + sticky);
12306
12307 if (receiver == null) {
12308 return sticky;
12309 }
12310
12311 ReceiverList rl
12312 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12313 if (rl == null) {
12314 rl = new ReceiverList(this, callerApp,
12315 Binder.getCallingPid(),
12316 Binder.getCallingUid(), receiver);
12317 if (rl.app != null) {
12318 rl.app.receivers.add(rl);
12319 } else {
12320 try {
12321 receiver.asBinder().linkToDeath(rl, 0);
12322 } catch (RemoteException e) {
12323 return sticky;
12324 }
12325 rl.linkedToDeath = true;
12326 }
12327 mRegisteredReceivers.put(receiver.asBinder(), rl);
12328 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012329 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012330 rl.add(bf);
12331 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012332 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012333 }
12334 mReceiverResolver.addFilter(bf);
12335
12336 // Enqueue broadcasts for all existing stickies that match
12337 // this filter.
12338 if (allSticky != null) {
12339 ArrayList receivers = new ArrayList();
12340 receivers.add(bf);
12341
12342 int N = allSticky.size();
12343 for (int i=0; i<N; i++) {
12344 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012345 BroadcastQueue queue = broadcastQueueForIntent(intent);
12346 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012347 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012348 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012349 queue.enqueueParallelBroadcastLocked(r);
12350 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012351 }
12352 }
12353
12354 return sticky;
12355 }
12356 }
12357
12358 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012359 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360
Christopher Tatef46723b2012-01-26 14:19:24 -080012361 final long origId = Binder.clearCallingIdentity();
12362 try {
12363 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012364
Christopher Tatef46723b2012-01-26 14:19:24 -080012365 synchronized(this) {
12366 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012367 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012368 if (rl != null) {
12369 if (rl.curBroadcast != null) {
12370 BroadcastRecord r = rl.curBroadcast;
12371 final boolean doNext = finishReceiverLocked(
12372 receiver.asBinder(), r.resultCode, r.resultData,
12373 r.resultExtras, r.resultAbort, true);
12374 if (doNext) {
12375 doTrim = true;
12376 r.queue.processNextBroadcast(false);
12377 }
12378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012379
Christopher Tatef46723b2012-01-26 14:19:24 -080012380 if (rl.app != null) {
12381 rl.app.receivers.remove(rl);
12382 }
12383 removeReceiverLocked(rl);
12384 if (rl.linkedToDeath) {
12385 rl.linkedToDeath = false;
12386 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12387 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
12389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390
Christopher Tatef46723b2012-01-26 14:19:24 -080012391 // If we actually concluded any broadcasts, we might now be able
12392 // to trim the recipients' apps from our working set
12393 if (doTrim) {
12394 trimApplications();
12395 return;
12396 }
12397
12398 } finally {
12399 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012401 }
12402
12403 void removeReceiverLocked(ReceiverList rl) {
12404 mRegisteredReceivers.remove(rl.receiver.asBinder());
12405 int N = rl.size();
12406 for (int i=0; i<N; i++) {
12407 mReceiverResolver.removeFilter(rl.get(i));
12408 }
12409 }
12410
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012411 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12412 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12413 ProcessRecord r = mLruProcesses.get(i);
12414 if (r.thread != null) {
12415 try {
12416 r.thread.dispatchPackageBroadcast(cmd, packages);
12417 } catch (RemoteException ex) {
12418 }
12419 }
12420 }
12421 }
12422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012423 private final int broadcastIntentLocked(ProcessRecord callerApp,
12424 String callerPackage, Intent intent, String resolvedType,
12425 IIntentReceiver resultTo, int resultCode, String resultData,
12426 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012427 boolean ordered, boolean sticky, int callingPid, int callingUid,
12428 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 intent = new Intent(intent);
12430
Dianne Hackborne7f97212011-02-24 14:40:20 -080012431 // By default broadcasts do not go to stopped apps.
12432 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12433
Joe Onorato8a9b2202010-02-26 18:56:32 -080012434 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
12436 + " ordered=" + ordered);
12437 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012438 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 }
12440
12441 // Handle special intents: if this broadcast is from the package
12442 // manager about a package being removed, we need to remove all of
12443 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012444 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012446 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12447 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012448 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449 || uidRemoved) {
12450 if (checkComponentPermission(
12451 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012452 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012453 == PackageManager.PERMISSION_GRANTED) {
12454 if (uidRemoved) {
12455 final Bundle intentExtras = intent.getExtras();
12456 final int uid = intentExtras != null
12457 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12458 if (uid >= 0) {
12459 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12460 synchronized (bs) {
12461 bs.removeUidStatsLocked(uid);
12462 }
12463 }
12464 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012465 // If resources are unvailble just force stop all
12466 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012467 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012468 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12469 if (list != null && (list.length > 0)) {
12470 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012471 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012472 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012473 sendPackageBroadcastLocked(
12474 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012475 }
12476 } else {
12477 Uri data = intent.getData();
12478 String ssp;
12479 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12480 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12481 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012482 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12483 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012484 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012485 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012486 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12487 new String[] {ssp});
12488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012489 }
12490 }
12491 }
12492 } else {
12493 String msg = "Permission Denial: " + intent.getAction()
12494 + " broadcast from " + callerPackage + " (pid=" + callingPid
12495 + ", uid=" + callingUid + ")"
12496 + " requires "
12497 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012498 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012499 throw new SecurityException(msg);
12500 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012501
12502 // Special case for adding a package: by default turn on compatibility
12503 // mode.
12504 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012505 Uri data = intent.getData();
12506 String ssp;
12507 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12508 mCompatModePackages.handlePackageAddedLocked(ssp,
12509 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012511 }
12512
12513 /*
12514 * If this is the time zone changed action, queue up a message that will reset the timezone
12515 * of all currently running processes. This message will get queued up before the broadcast
12516 * happens.
12517 */
12518 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12519 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12520 }
12521
Robert Greenwalt03595d02010-11-02 14:08:23 -070012522 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12523 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12524 }
12525
Robert Greenwalt434203a2010-10-11 16:00:27 -070012526 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12527 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12528 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12529 }
12530
Dianne Hackborn854060af2009-07-09 18:14:31 -070012531 /*
12532 * Prevent non-system code (defined here to be non-persistent
12533 * processes) from sending protected broadcasts.
12534 */
12535 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12536 || callingUid == Process.SHELL_UID || callingUid == 0) {
12537 // Always okay.
12538 } else if (callerApp == null || !callerApp.persistent) {
12539 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012540 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012541 intent.getAction())) {
12542 String msg = "Permission Denial: not allowed to send broadcast "
12543 + intent.getAction() + " from pid="
12544 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012545 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012546 throw new SecurityException(msg);
12547 }
12548 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012549 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012550 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012551 }
12552 }
12553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 // Add to the sticky list if requested.
12555 if (sticky) {
12556 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12557 callingPid, callingUid)
12558 != PackageManager.PERMISSION_GRANTED) {
12559 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12560 + callingPid + ", uid=" + callingUid
12561 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012562 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012563 throw new SecurityException(msg);
12564 }
12565 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012566 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012568 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012569 }
12570 if (intent.getComponent() != null) {
12571 throw new SecurityException(
12572 "Sticky broadcasts can't target a specific component");
12573 }
12574 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12575 if (list == null) {
12576 list = new ArrayList<Intent>();
12577 mStickyBroadcasts.put(intent.getAction(), list);
12578 }
12579 int N = list.size();
12580 int i;
12581 for (i=0; i<N; i++) {
12582 if (intent.filterEquals(list.get(i))) {
12583 // This sticky already exists, replace it.
12584 list.set(i, new Intent(intent));
12585 break;
12586 }
12587 }
12588 if (i >= N) {
12589 list.add(new Intent(intent));
12590 }
12591 }
12592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012593 // Figure out who all will receive this broadcast.
12594 List receivers = null;
12595 List<BroadcastFilter> registeredReceivers = null;
12596 try {
12597 if (intent.getComponent() != null) {
12598 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012599 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012600 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012601 if (ai != null) {
12602 receivers = new ArrayList();
12603 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012604 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012605 receivers.add(ri);
12606 }
12607 } else {
12608 // Need to resolve the intent to interested receivers...
12609 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12610 == 0) {
12611 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012612 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012613 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012614 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012615 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12616 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 }
12618 } catch (RemoteException ex) {
12619 // pm is in same process, this will never happen.
12620 }
12621
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012622 final boolean replacePending =
12623 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12624
Joe Onorato8a9b2202010-02-26 18:56:32 -080012625 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012626 + " replacePending=" + replacePending);
12627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012628 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12629 if (!ordered && NR > 0) {
12630 // If we are not serializing this broadcast, then send the
12631 // registered receivers separately so they don't wait for the
12632 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012633 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12634 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012635 callerPackage, callingPid, callingUid, requiredPermission,
12636 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012637 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012638 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012639 TAG, "Enqueueing parallel broadcast " + r);
12640 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012641 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012642 queue.enqueueParallelBroadcastLocked(r);
12643 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 registeredReceivers = null;
12646 NR = 0;
12647 }
12648
12649 // Merge into one list.
12650 int ir = 0;
12651 if (receivers != null) {
12652 // A special case for PACKAGE_ADDED: do not allow the package
12653 // being added to see this broadcast. This prevents them from
12654 // using this as a back door to get run as soon as they are
12655 // installed. Maybe in the future we want to have a special install
12656 // broadcast or such for apps, but we'd like to deliberately make
12657 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012658 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012659 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12660 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12661 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012662 Uri data = intent.getData();
12663 if (data != null) {
12664 String pkgName = data.getSchemeSpecificPart();
12665 if (pkgName != null) {
12666 skipPackages = new String[] { pkgName };
12667 }
12668 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012669 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012670 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012672 if (skipPackages != null && (skipPackages.length > 0)) {
12673 for (String skipPackage : skipPackages) {
12674 if (skipPackage != null) {
12675 int NT = receivers.size();
12676 for (int it=0; it<NT; it++) {
12677 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12678 if (curt.activityInfo.packageName.equals(skipPackage)) {
12679 receivers.remove(it);
12680 it--;
12681 NT--;
12682 }
12683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012684 }
12685 }
12686 }
12687
12688 int NT = receivers != null ? receivers.size() : 0;
12689 int it = 0;
12690 ResolveInfo curt = null;
12691 BroadcastFilter curr = null;
12692 while (it < NT && ir < NR) {
12693 if (curt == null) {
12694 curt = (ResolveInfo)receivers.get(it);
12695 }
12696 if (curr == null) {
12697 curr = registeredReceivers.get(ir);
12698 }
12699 if (curr.getPriority() >= curt.priority) {
12700 // Insert this broadcast record into the final list.
12701 receivers.add(it, curr);
12702 ir++;
12703 curr = null;
12704 it++;
12705 NT++;
12706 } else {
12707 // Skip to the next ResolveInfo in the final list.
12708 it++;
12709 curt = null;
12710 }
12711 }
12712 }
12713 while (ir < NR) {
12714 if (receivers == null) {
12715 receivers = new ArrayList();
12716 }
12717 receivers.add(registeredReceivers.get(ir));
12718 ir++;
12719 }
12720
12721 if ((receivers != null && receivers.size() > 0)
12722 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012723 BroadcastQueue queue = broadcastQueueForIntent(intent);
12724 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012726 receivers, resultTo, resultCode, resultData, map, ordered,
12727 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012728 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012729 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012730 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012731 if (DEBUG_BROADCAST) {
12732 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012733 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012734 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012735 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012736 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012737 queue.enqueueOrderedBroadcastLocked(r);
12738 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 }
12741
Dianne Hackborna4972e92012-03-14 10:38:05 -070012742 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012743 }
12744
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012745 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012746 // Refuse possible leaked file descriptors
12747 if (intent != null && intent.hasFileDescriptors() == true) {
12748 throw new IllegalArgumentException("File descriptors passed in Intent");
12749 }
12750
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012751 int flags = intent.getFlags();
12752
12753 if (!mProcessesReady) {
12754 // if the caller really truly claims to know what they're doing, go
12755 // ahead and allow the broadcast without launching any receivers
12756 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12757 intent = new Intent(intent);
12758 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12759 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12760 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12761 + " before boot completion");
12762 throw new IllegalStateException("Cannot broadcast before boot completed");
12763 }
12764 }
12765
12766 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12767 throw new IllegalArgumentException(
12768 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12769 }
12770
12771 return intent;
12772 }
12773
12774 public final int broadcastIntent(IApplicationThread caller,
12775 Intent intent, String resolvedType, IIntentReceiver resultTo,
12776 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012777 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012778 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012779 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012780 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012782 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12783 final int callingPid = Binder.getCallingPid();
12784 final int callingUid = Binder.getCallingUid();
12785 final long origId = Binder.clearCallingIdentity();
12786 int res = broadcastIntentLocked(callerApp,
12787 callerApp != null ? callerApp.info.packageName : null,
12788 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012789 resultCode, resultData, map, requiredPermission, serialized, sticky,
12790 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012791 Binder.restoreCallingIdentity(origId);
12792 return res;
12793 }
12794 }
12795
12796 int broadcastIntentInPackage(String packageName, int uid,
12797 Intent intent, String resolvedType, IIntentReceiver resultTo,
12798 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012799 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012801 intent = verifyBroadcastLocked(intent);
12802
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 final long origId = Binder.clearCallingIdentity();
12804 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12805 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012806 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807 Binder.restoreCallingIdentity(origId);
12808 return res;
12809 }
12810 }
12811
Amith Yamasani742a6712011-05-04 14:49:28 -070012812 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12813 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 // Refuse possible leaked file descriptors
12815 if (intent != null && intent.hasFileDescriptors() == true) {
12816 throw new IllegalArgumentException("File descriptors passed in Intent");
12817 }
12818
12819 synchronized(this) {
12820 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12821 != PackageManager.PERMISSION_GRANTED) {
12822 String msg = "Permission Denial: unbroadcastIntent() from pid="
12823 + Binder.getCallingPid()
12824 + ", uid=" + Binder.getCallingUid()
12825 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012826 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012827 throw new SecurityException(msg);
12828 }
12829 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12830 if (list != null) {
12831 int N = list.size();
12832 int i;
12833 for (i=0; i<N; i++) {
12834 if (intent.filterEquals(list.get(i))) {
12835 list.remove(i);
12836 break;
12837 }
12838 }
12839 }
12840 }
12841 }
12842
12843 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12844 String resultData, Bundle resultExtras, boolean resultAbort,
12845 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012846 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12847 if (r == null) {
12848 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012849 return false;
12850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012851
Christopher Tatef46723b2012-01-26 14:19:24 -080012852 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12853 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012854 }
12855
12856 public void finishReceiver(IBinder who, int resultCode, String resultData,
12857 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012858 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012859
12860 // Refuse possible leaked file descriptors
12861 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12862 throw new IllegalArgumentException("File descriptors passed in Bundle");
12863 }
12864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012866 try {
12867 boolean doNext = false;
12868 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869
Christopher Tatef46723b2012-01-26 14:19:24 -080012870 synchronized(this) {
12871 r = broadcastRecordForReceiverLocked(who);
12872 if (r != null) {
12873 doNext = r.queue.finishReceiverLocked(r, resultCode,
12874 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012876 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012877
Christopher Tatef46723b2012-01-26 14:19:24 -080012878 if (doNext) {
12879 r.queue.processNextBroadcast(false);
12880 }
12881 trimApplications();
12882 } finally {
12883 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012887 // =========================================================
12888 // INSTRUMENTATION
12889 // =========================================================
12890
12891 public boolean startInstrumentation(ComponentName className,
12892 String profileFile, int flags, Bundle arguments,
12893 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012894 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012895 // Refuse possible leaked file descriptors
12896 if (arguments != null && arguments.hasFileDescriptors()) {
12897 throw new IllegalArgumentException("File descriptors passed in Bundle");
12898 }
12899
12900 synchronized(this) {
12901 InstrumentationInfo ii = null;
12902 ApplicationInfo ai = null;
12903 try {
12904 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012905 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012907 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012908 } catch (PackageManager.NameNotFoundException e) {
12909 }
12910 if (ii == null) {
12911 reportStartInstrumentationFailure(watcher, className,
12912 "Unable to find instrumentation info for: " + className);
12913 return false;
12914 }
12915 if (ai == null) {
12916 reportStartInstrumentationFailure(watcher, className,
12917 "Unable to find instrumentation target package: " + ii.targetPackage);
12918 return false;
12919 }
12920
12921 int match = mContext.getPackageManager().checkSignatures(
12922 ii.targetPackage, ii.packageName);
12923 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12924 String msg = "Permission Denial: starting instrumentation "
12925 + className + " from pid="
12926 + Binder.getCallingPid()
12927 + ", uid=" + Binder.getCallingPid()
12928 + " not allowed because package " + ii.packageName
12929 + " does not have a signature matching the target "
12930 + ii.targetPackage;
12931 reportStartInstrumentationFailure(watcher, className, msg);
12932 throw new SecurityException(msg);
12933 }
12934
Amith Yamasani483f3b02012-03-13 16:08:00 -070012935 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012936 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012937 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012938 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012939 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012941 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 app.instrumentationProfileFile = profileFile;
12943 app.instrumentationArguments = arguments;
12944 app.instrumentationWatcher = watcher;
12945 app.instrumentationResultClass = className;
12946 Binder.restoreCallingIdentity(origId);
12947 }
12948
12949 return true;
12950 }
12951
12952 /**
12953 * Report errors that occur while attempting to start Instrumentation. Always writes the
12954 * error to the logs, but if somebody is watching, send the report there too. This enables
12955 * the "am" command to report errors with more information.
12956 *
12957 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
12958 * @param cn The component name of the instrumentation.
12959 * @param report The error report.
12960 */
12961 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
12962 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012963 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964 try {
12965 if (watcher != null) {
12966 Bundle results = new Bundle();
12967 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
12968 results.putString("Error", report);
12969 watcher.instrumentationStatus(cn, -1, results);
12970 }
12971 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012972 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 }
12974 }
12975
12976 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
12977 if (app.instrumentationWatcher != null) {
12978 try {
12979 // NOTE: IInstrumentationWatcher *must* be oneway here
12980 app.instrumentationWatcher.instrumentationFinished(
12981 app.instrumentationClass,
12982 resultCode,
12983 results);
12984 } catch (RemoteException e) {
12985 }
12986 }
12987 app.instrumentationWatcher = null;
12988 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012989 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012990 app.instrumentationProfileFile = null;
12991 app.instrumentationArguments = null;
12992
Amith Yamasani483f3b02012-03-13 16:08:00 -070012993 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 }
12995
12996 public void finishInstrumentation(IApplicationThread target,
12997 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012998 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012999 // Refuse possible leaked file descriptors
13000 if (results != null && results.hasFileDescriptors()) {
13001 throw new IllegalArgumentException("File descriptors passed in Intent");
13002 }
13003
13004 synchronized(this) {
13005 ProcessRecord app = getRecordForAppLocked(target);
13006 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013007 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013008 return;
13009 }
13010 final long origId = Binder.clearCallingIdentity();
13011 finishInstrumentationLocked(app, resultCode, results);
13012 Binder.restoreCallingIdentity(origId);
13013 }
13014 }
13015
13016 // =========================================================
13017 // CONFIGURATION
13018 // =========================================================
13019
13020 public ConfigurationInfo getDeviceConfigurationInfo() {
13021 ConfigurationInfo config = new ConfigurationInfo();
13022 synchronized (this) {
13023 config.reqTouchScreen = mConfiguration.touchscreen;
13024 config.reqKeyboardType = mConfiguration.keyboard;
13025 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013026 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13027 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13029 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013030 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13031 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13033 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013034 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 }
13036 return config;
13037 }
13038
13039 public Configuration getConfiguration() {
13040 Configuration ci;
13041 synchronized(this) {
13042 ci = new Configuration(mConfiguration);
13043 }
13044 return ci;
13045 }
13046
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013047 public void updatePersistentConfiguration(Configuration values) {
13048 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13049 "updateConfiguration()");
13050 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13051 "updateConfiguration()");
13052 if (values == null) {
13053 throw new NullPointerException("Configuration must not be null");
13054 }
13055
13056 synchronized(this) {
13057 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013058 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013059 Binder.restoreCallingIdentity(origId);
13060 }
13061 }
13062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 public void updateConfiguration(Configuration values) {
13064 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13065 "updateConfiguration()");
13066
13067 synchronized(this) {
13068 if (values == null && mWindowManager != null) {
13069 // sentinel: fetch the current configuration from the window manager
13070 values = mWindowManager.computeNewConfiguration();
13071 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013072
13073 if (mWindowManager != null) {
13074 mProcessList.applyDisplaySize(mWindowManager);
13075 }
13076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013077 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013078 if (values != null) {
13079 Settings.System.clearConfiguration(values);
13080 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013081 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013082 Binder.restoreCallingIdentity(origId);
13083 }
13084 }
13085
13086 /**
13087 * Do either or both things: (1) change the current configuration, and (2)
13088 * make sure the given activity is running with the (now) current
13089 * configuration. Returns true if the activity has been left running, or
13090 * false if <var>starting</var> is being destroyed to match the new
13091 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013092 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013093 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013094 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013095 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013096 // do nothing if we are headless
13097 if (mHeadless) return true;
13098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 int changes = 0;
13100
13101 boolean kept = true;
13102
13103 if (values != null) {
13104 Configuration newConfig = new Configuration(mConfiguration);
13105 changes = newConfig.updateFrom(values);
13106 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013107 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013108 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013109 }
13110
Doug Zongker2bec3d42009-12-04 12:52:44 -080013111 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013112
Dianne Hackborn813075a62011-11-14 17:45:19 -080013113 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 saveLocaleLocked(values.locale,
13115 !values.locale.equals(mConfiguration.locale),
13116 values.userSetLocale);
13117 }
13118
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013119 mConfigurationSeq++;
13120 if (mConfigurationSeq <= 0) {
13121 mConfigurationSeq = 1;
13122 }
13123 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013124 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013125 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013126
13127 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013128
13129 // TODO: If our config changes, should we auto dismiss any currently
13130 // showing dialogs?
13131 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013132
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013133 AttributeCache ac = AttributeCache.instance();
13134 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013135 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013138 // Make sure all resources in our process are updated
13139 // right now, so that anyone who is going to retrieve
13140 // resource values after we return will be sure to get
13141 // the new ones. This is especially important during
13142 // boot, where the first config change needs to guarantee
13143 // all resources have that config before following boot
13144 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013145 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013146
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013147 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013148 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013149 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013150 mHandler.sendMessage(msg);
13151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013153 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13154 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 try {
13156 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013157 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013158 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013159 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 }
13161 } catch (Exception e) {
13162 }
13163 }
13164 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013165 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13166 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013168 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013169 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13170 broadcastIntentLocked(null, null,
13171 new Intent(Intent.ACTION_LOCALE_CHANGED),
13172 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013173 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013175 }
13176 }
13177
13178 if (changes != 0 && starting == null) {
13179 // If the configuration changed, and the caller is not already
13180 // in the process of starting an activity, then find the top
13181 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013182 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013183 }
13184
13185 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013186 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013187 // And we need to make sure at this point that all other activities
13188 // are made visible with the correct configuration.
13189 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190 }
13191
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013192 if (values != null && mWindowManager != null) {
13193 mWindowManager.setNewConfiguration(mConfiguration);
13194 }
13195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 return kept;
13197 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013198
13199 /**
13200 * Decide based on the configuration whether we should shouw the ANR,
13201 * crash, etc dialogs. The idea is that if there is no affordnace to
13202 * press the on-screen buttons, we shouldn't show the dialog.
13203 *
13204 * A thought: SystemUI might also want to get told about this, the Power
13205 * dialog / global actions also might want different behaviors.
13206 */
13207 private static final boolean shouldShowDialogs(Configuration config) {
13208 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13209 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013211
13212 /**
13213 * Save the locale. You must be inside a synchronized (this) block.
13214 */
13215 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13216 if(isDiff) {
13217 SystemProperties.set("user.language", l.getLanguage());
13218 SystemProperties.set("user.region", l.getCountry());
13219 }
13220
13221 if(isPersist) {
13222 SystemProperties.set("persist.sys.language", l.getLanguage());
13223 SystemProperties.set("persist.sys.country", l.getCountry());
13224 SystemProperties.set("persist.sys.localevar", l.getVariant());
13225 }
13226 }
13227
13228 // =========================================================
13229 // LIFETIME MANAGEMENT
13230 // =========================================================
13231
Christopher Tatef46723b2012-01-26 14:19:24 -080013232 // Returns which broadcast queue the app is the current [or imminent] receiver
13233 // on, or 'null' if the app is not an active broadcast recipient.
13234 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13235 BroadcastRecord r = app.curReceiver;
13236 if (r != null) {
13237 return r.queue;
13238 }
13239
13240 // It's not the current receiver, but it might be starting up to become one
13241 synchronized (this) {
13242 for (BroadcastQueue queue : mBroadcastQueues) {
13243 r = queue.mPendingBroadcast;
13244 if (r != null && r.curApp == app) {
13245 // found it; report which queue it's in
13246 return queue;
13247 }
13248 }
13249 }
13250
13251 return null;
13252 }
13253
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013254 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013255 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013257 // This adjustment has already been computed. If we are calling
13258 // from the top, we may have already computed our adjustment with
13259 // an earlier hidden adjustment that isn't really for us... if
13260 // so, use the new hidden adjustment.
13261 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013262 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013263 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013264 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265 }
13266
13267 if (app.thread == null) {
13268 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013269 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013270 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013271 }
13272
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013273 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13274 app.adjSource = null;
13275 app.adjTarget = null;
13276 app.empty = false;
13277 app.hidden = false;
13278
13279 final int activitiesSize = app.activities.size();
13280
Dianne Hackborn7d608422011-08-07 16:24:18 -070013281 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013282 // The max adjustment doesn't allow this app to be anything
13283 // below foreground, so it is not worth doing work for it.
13284 app.adjType = "fixed";
13285 app.adjSeq = mAdjSeq;
13286 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013287 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013288 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013289 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013290 // System process can do UI, and when they do we want to have
13291 // them trim their memory after the user leaves the UI. To
13292 // facilitate this, here we need to determine whether or not it
13293 // is currently showing UI.
13294 app.systemNoUi = true;
13295 if (app == TOP_APP) {
13296 app.systemNoUi = false;
13297 } else if (activitiesSize > 0) {
13298 for (int j = 0; j < activitiesSize; j++) {
13299 final ActivityRecord r = app.activities.get(j);
13300 if (r.visible) {
13301 app.systemNoUi = false;
13302 break;
13303 }
13304 }
13305 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013306 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013307 }
13308
13309 final boolean hadForegroundActivities = app.foregroundActivities;
13310
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013311 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013312 app.keeping = false;
13313 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314
The Android Open Source Project4df24232009-03-05 14:34:35 -080013315 // Determine the importance of the process, starting with most
13316 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013317 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013318 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013319 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013320 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013321 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013322 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013323 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013324 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013325 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013326 } else if (app.instrumentationClass != null) {
13327 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013328 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013329 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013330 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013331 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013333 // counts as being in the foreground for OOM killer purposes.
13334 // It's placed in a sched group based on the nature of the
13335 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013336 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013337 schedGroup = (queue == mFgBroadcastQueue)
13338 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013339 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 } else if (app.executingServices.size() > 0) {
13341 // An app that is currently executing a service callback also
13342 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013343 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013344 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013345 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013346 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013347 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013348 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013349 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013350 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013351 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013352 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013353 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013354 // A very not-needed process. If this is lower in the lru list,
13355 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013356 adj = hiddenAdj;
13357 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013358 app.hidden = true;
13359 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013360 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013362
13363 // Examine all activities if not already foreground.
13364 if (!app.foregroundActivities && activitiesSize > 0) {
13365 for (int j = 0; j < activitiesSize; j++) {
13366 final ActivityRecord r = app.activities.get(j);
13367 if (r.visible) {
13368 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013369 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13370 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013371 app.adjType = "visible";
13372 }
13373 schedGroup = Process.THREAD_GROUP_DEFAULT;
13374 app.hidden = false;
13375 app.foregroundActivities = true;
13376 break;
13377 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13378 || r.state == ActivityState.STOPPING) {
13379 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013380 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13381 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013382 app.adjType = "stopping";
13383 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013384 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013385 app.foregroundActivities = true;
13386 }
13387 }
13388 }
13389
Dianne Hackborn7d608422011-08-07 16:24:18 -070013390 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013391 if (app.foregroundServices) {
13392 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013393 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013394 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013395 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013396 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013397 } else if (app.forcingToForeground != null) {
13398 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013399 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013400 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013401 app.adjType = "force-foreground";
13402 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013403 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013404 }
13405 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013406
Dianne Hackborn7d608422011-08-07 16:24:18 -070013407 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013408 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013409 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013410 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013411 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013412 app.adjType = "heavy";
13413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013414
Dianne Hackborn7d608422011-08-07 16:24:18 -070013415 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013416 // This process is hosting what we currently consider to be the
13417 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013418 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013419 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013420 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013421 app.adjType = "home";
13422 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013423
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013424 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13425 && app.activities.size() > 0) {
13426 // This was the previous process that showed UI to the user.
13427 // We want to try to keep it around more aggressively, to give
13428 // a good experience around switching between two apps.
13429 adj = ProcessList.PREVIOUS_APP_ADJ;
13430 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13431 app.hidden = false;
13432 app.adjType = "previous";
13433 }
13434
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013435 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13436 + " reason=" + app.adjType);
13437
The Android Open Source Project4df24232009-03-05 14:34:35 -080013438 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013439 // there are applications dependent on our services or providers, but
13440 // this gives us a baseline and makes sure we don't get into an
13441 // infinite recursion.
13442 app.adjSeq = mAdjSeq;
13443 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013444
Christopher Tate6fa95972009-06-05 18:43:55 -070013445 if (mBackupTarget != null && app == mBackupTarget.app) {
13446 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013447 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013448 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013449 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013450 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013451 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013452 }
13453 }
13454
Dianne Hackborn7d608422011-08-07 16:24:18 -070013455 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013456 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013457 final long now = SystemClock.uptimeMillis();
13458 // This process is more important if the top activity is
13459 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013460 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013461 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013462 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013463 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013464 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013465 // If this process has shown some UI, let it immediately
13466 // go to the LRU list because it may be pretty heavy with
13467 // UI stuff. We'll tag it with a label just to help
13468 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013469 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013470 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013472 } else {
13473 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13474 // This service has seen some activity within
13475 // recent memory, so we will keep its process ahead
13476 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013477 if (adj > ProcessList.SERVICE_ADJ) {
13478 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013479 app.adjType = "started-services";
13480 app.hidden = false;
13481 }
13482 }
13483 // If we have let the service slide into the background
13484 // state, still have some text describing what it is doing
13485 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013486 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013487 app.adjType = "started-bg-services";
13488 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013489 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013490 // Don't kill this process because it is doing work; it
13491 // has said it is doing work.
13492 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013493 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013494 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013495 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013496 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013497 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013498 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013499 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013500 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013501 // XXX should compute this based on the max of
13502 // all connected clients.
13503 ConnectionRecord cr = clist.get(i);
13504 if (cr.binding.client == app) {
13505 // Binding to ourself is not interesting.
13506 continue;
13507 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013508 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013509 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013510 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013511 int myHiddenAdj = hiddenAdj;
13512 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013513 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013514 myHiddenAdj = client.hiddenAdj;
13515 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013516 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013517 }
13518 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013519 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013520 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013521 String adjType = null;
13522 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13523 // Not doing bind OOM management, so treat
13524 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013525 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013526 // If this process has shown some UI, let it immediately
13527 // go to the LRU list because it may be pretty heavy with
13528 // UI stuff. We'll tag it with a label just to help
13529 // debug and understand what is going on.
13530 if (adj > clientAdj) {
13531 adjType = "bound-bg-ui-services";
13532 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013533 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013534 clientAdj = adj;
13535 } else {
13536 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13537 // This service has not seen activity within
13538 // recent memory, so allow it to drop to the
13539 // LRU list if there is no other reason to keep
13540 // it around. We'll also tag it with a label just
13541 // to help debug and undertand what is going on.
13542 if (adj > clientAdj) {
13543 adjType = "bound-bg-services";
13544 }
13545 clientAdj = adj;
13546 }
13547 }
13548 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013549 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013550 // If this process has recently shown UI, and
13551 // the process that is binding to it is less
13552 // important than being visible, then we don't
13553 // care about the binding as much as we care
13554 // about letting this process get into the LRU
13555 // list to be killed and restarted if needed for
13556 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013557 if (app.hasShownUi && app != mHomeProcess
13558 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013559 adjType = "bound-bg-ui-services";
13560 } else {
13561 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13562 |Context.BIND_IMPORTANT)) != 0) {
13563 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013564 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13565 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13566 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13567 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13568 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013569 adj = clientAdj;
13570 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013571 app.pendingUiClean = true;
13572 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13573 adj = ProcessList.VISIBLE_APP_ADJ;
13574 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013575 }
13576 if (!client.hidden) {
13577 app.hidden = false;
13578 }
13579 if (client.keeping) {
13580 app.keeping = true;
13581 }
13582 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013583 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013584 }
13585 if (adjType != null) {
13586 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013587 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13588 .REASON_SERVICE_IN_USE;
13589 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013590 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013591 app.adjTarget = s.name;
13592 }
13593 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13594 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13595 schedGroup = Process.THREAD_GROUP_DEFAULT;
13596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013597 }
13598 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013599 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13600 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013601 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013602 (a.visible || a.state == ActivityState.RESUMED
13603 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013604 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013605 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13606 schedGroup = Process.THREAD_GROUP_DEFAULT;
13607 }
13608 app.hidden = false;
13609 app.adjType = "service";
13610 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13611 .REASON_SERVICE_IN_USE;
13612 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013613 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013614 app.adjTarget = s.name;
13615 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013617 }
13618 }
13619 }
13620 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013621
Dianne Hackborn287952c2010-09-22 22:34:31 -070013622 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013623 // would like to avoid killing it unless it would prevent the current
13624 // application from running. By default we put the process in
13625 // with the rest of the background processes; as we scan through
13626 // its services we may bump it up from there.
13627 if (adj > hiddenAdj) {
13628 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013629 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013630 app.adjType = "bg-services";
13631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013632 }
13633
Dianne Hackborn7d608422011-08-07 16:24:18 -070013634 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013635 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013636 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013637 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013638 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013639 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013640 if (cpr.clients.size() != 0) {
13641 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013642 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013644 if (client == app) {
13645 // Being our own client is not interesting.
13646 continue;
13647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013648 int myHiddenAdj = hiddenAdj;
13649 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013650 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 myHiddenAdj = client.hiddenAdj;
13652 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013653 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013654 }
13655 }
13656 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013657 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013658 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013659 if (app.hasShownUi && app != mHomeProcess
13660 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013661 app.adjType = "bg-ui-provider";
13662 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013663 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13664 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013665 app.adjType = "provider";
13666 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013667 if (!client.hidden) {
13668 app.hidden = false;
13669 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013670 if (client.keeping) {
13671 app.keeping = true;
13672 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013673 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13674 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013675 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013676 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013677 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013678 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013679 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13680 schedGroup = Process.THREAD_GROUP_DEFAULT;
13681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013682 }
13683 }
13684 // If the provider has external (non-framework) process
13685 // dependencies, ensure that its adjustment is at least
13686 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013687 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013688 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13689 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013690 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013691 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013692 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013693 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013694 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 }
13696 }
13697 }
13698 }
13699
13700 app.curRawAdj = adj;
13701
Joe Onorato8a9b2202010-02-26 18:56:32 -080013702 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013703 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13704 if (adj > app.maxAdj) {
13705 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013706 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013707 schedGroup = Process.THREAD_GROUP_DEFAULT;
13708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013709 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013710 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013711 app.keeping = true;
13712 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013713
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013714 if (app.hasAboveClient) {
13715 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13716 // then we need to drop its adjustment to be lower than the service's
13717 // in order to honor the request. We want to drop it by one adjustment
13718 // level... but there is special meaning applied to various levels so
13719 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013720 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013721 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013722 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13723 adj = ProcessList.VISIBLE_APP_ADJ;
13724 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13725 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13726 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13727 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013728 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013729 adj++;
13730 }
13731 }
13732
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013733 if (adj == ProcessList.SERVICE_ADJ) {
13734 if (doingAll) {
13735 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13736 mNewNumServiceProcs++;
13737 }
13738 if (app.serviceb) {
13739 adj = ProcessList.SERVICE_B_ADJ;
13740 }
13741 } else {
13742 app.serviceb = false;
13743 }
13744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013745 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013746 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013747
13748 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013749 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13750 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013751 }
13752
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013753 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013754 }
13755
13756 /**
13757 * Ask a given process to GC right now.
13758 */
13759 final void performAppGcLocked(ProcessRecord app) {
13760 try {
13761 app.lastRequestedGc = SystemClock.uptimeMillis();
13762 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013763 if (app.reportLowMemory) {
13764 app.reportLowMemory = false;
13765 app.thread.scheduleLowMemory();
13766 } else {
13767 app.thread.processInBackground();
13768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013769 }
13770 } catch (Exception e) {
13771 // whatever.
13772 }
13773 }
13774
13775 /**
13776 * Returns true if things are idle enough to perform GCs.
13777 */
Josh Bartel7f208742010-02-25 11:01:44 -060013778 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013779 boolean processingBroadcasts = false;
13780 for (BroadcastQueue q : mBroadcastQueues) {
13781 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13782 processingBroadcasts = true;
13783 }
13784 }
13785 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013786 && (mSleeping || (mMainStack.mResumedActivity != null &&
13787 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013788 }
13789
13790 /**
13791 * Perform GCs on all processes that are waiting for it, but only
13792 * if things are idle.
13793 */
13794 final void performAppGcsLocked() {
13795 final int N = mProcessesToGc.size();
13796 if (N <= 0) {
13797 return;
13798 }
Josh Bartel7f208742010-02-25 11:01:44 -060013799 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013800 while (mProcessesToGc.size() > 0) {
13801 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013802 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013803 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13804 <= SystemClock.uptimeMillis()) {
13805 // To avoid spamming the system, we will GC processes one
13806 // at a time, waiting a few seconds between each.
13807 performAppGcLocked(proc);
13808 scheduleAppGcsLocked();
13809 return;
13810 } else {
13811 // It hasn't been long enough since we last GCed this
13812 // process... put it in the list to wait for its time.
13813 addProcessToGcListLocked(proc);
13814 break;
13815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 }
13817 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013818
13819 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013820 }
13821 }
13822
13823 /**
13824 * If all looks good, perform GCs on all processes waiting for them.
13825 */
13826 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013827 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013828 performAppGcsLocked();
13829 return;
13830 }
13831 // Still not idle, wait some more.
13832 scheduleAppGcsLocked();
13833 }
13834
13835 /**
13836 * Schedule the execution of all pending app GCs.
13837 */
13838 final void scheduleAppGcsLocked() {
13839 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013840
13841 if (mProcessesToGc.size() > 0) {
13842 // Schedule a GC for the time to the next process.
13843 ProcessRecord proc = mProcessesToGc.get(0);
13844 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13845
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013846 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013847 long now = SystemClock.uptimeMillis();
13848 if (when < (now+GC_TIMEOUT)) {
13849 when = now + GC_TIMEOUT;
13850 }
13851 mHandler.sendMessageAtTime(msg, when);
13852 }
13853 }
13854
13855 /**
13856 * Add a process to the array of processes waiting to be GCed. Keeps the
13857 * list in sorted order by the last GC time. The process can't already be
13858 * on the list.
13859 */
13860 final void addProcessToGcListLocked(ProcessRecord proc) {
13861 boolean added = false;
13862 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13863 if (mProcessesToGc.get(i).lastRequestedGc <
13864 proc.lastRequestedGc) {
13865 added = true;
13866 mProcessesToGc.add(i+1, proc);
13867 break;
13868 }
13869 }
13870 if (!added) {
13871 mProcessesToGc.add(0, proc);
13872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013873 }
13874
13875 /**
13876 * Set up to ask a process to GC itself. This will either do it
13877 * immediately, or put it on the list of processes to gc the next
13878 * time things are idle.
13879 */
13880 final void scheduleAppGcLocked(ProcessRecord app) {
13881 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013882 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 return;
13884 }
13885 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013886 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887 scheduleAppGcsLocked();
13888 }
13889 }
13890
Dianne Hackborn287952c2010-09-22 22:34:31 -070013891 final void checkExcessivePowerUsageLocked(boolean doKills) {
13892 updateCpuStatsNow();
13893
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013894 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013895 boolean doWakeKills = doKills;
13896 boolean doCpuKills = doKills;
13897 if (mLastPowerCheckRealtime == 0) {
13898 doWakeKills = false;
13899 }
13900 if (mLastPowerCheckUptime == 0) {
13901 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013902 }
13903 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013904 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013905 }
13906 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013907 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13908 final long curUptime = SystemClock.uptimeMillis();
13909 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13910 mLastPowerCheckRealtime = curRealtime;
13911 mLastPowerCheckUptime = curUptime;
13912 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13913 doWakeKills = false;
13914 }
13915 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13916 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013917 }
13918 int i = mLruProcesses.size();
13919 while (i > 0) {
13920 i--;
13921 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013922 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013923 long wtime;
13924 synchronized (stats) {
13925 wtime = stats.getProcessWakeTime(app.info.uid,
13926 app.pid, curRealtime);
13927 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013928 long wtimeUsed = wtime - app.lastWakeTime;
13929 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13930 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013931 StringBuilder sb = new StringBuilder(128);
13932 sb.append("Wake for ");
13933 app.toShortString(sb);
13934 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013935 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013936 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013937 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013938 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013939 sb.append((wtimeUsed*100)/realtimeSince);
13940 sb.append("%)");
13941 Slog.i(TAG, sb.toString());
13942 sb.setLength(0);
13943 sb.append("CPU for ");
13944 app.toShortString(sb);
13945 sb.append(": over ");
13946 TimeUtils.formatDuration(uptimeSince, sb);
13947 sb.append(" used ");
13948 TimeUtils.formatDuration(cputimeUsed, sb);
13949 sb.append(" (");
13950 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013951 sb.append("%)");
13952 Slog.i(TAG, sb.toString());
13953 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013954 // If a process has held a wake lock for more
13955 // than 50% of the time during this period,
13956 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013957 if (doWakeKills && realtimeSince > 0
13958 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13959 synchronized (stats) {
13960 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13961 realtimeSince, wtimeUsed);
13962 }
13963 Slog.w(TAG, "Excessive wake lock in " + app.processName
13964 + " (pid " + app.pid + "): held " + wtimeUsed
13965 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013966 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13967 app.processName, app.setAdj, "excessive wake lock");
13968 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013969 } else if (doCpuKills && uptimeSince > 0
13970 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13971 synchronized (stats) {
13972 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13973 uptimeSince, cputimeUsed);
13974 }
13975 Slog.w(TAG, "Excessive CPU in " + app.processName
13976 + " (pid " + app.pid + "): used " + cputimeUsed
13977 + " during " + uptimeSince);
13978 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13979 app.processName, app.setAdj, "excessive cpu");
13980 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013981 } else {
13982 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013983 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013984 }
13985 }
13986 }
13987 }
13988
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013989 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013990 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013991 app.hiddenAdj = hiddenAdj;
13992
13993 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013994 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013995 }
13996
Dianne Hackborn287952c2010-09-22 22:34:31 -070013997 final boolean wasKeeping = app.keeping;
13998
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013999 boolean success = true;
14000
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014001 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014002
Jeff Brown10e89712011-07-08 18:52:57 -070014003 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014004 if (false) {
14005 // Removing for now. Forcing GCs is not so useful anymore
14006 // with Dalvik, and the new memory level hint facility is
14007 // better for what we need to do these days.
14008 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14009 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14010 // If this app is transitioning from foreground to
14011 // non-foreground, have it do a gc.
14012 scheduleAppGcLocked(app);
14013 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14014 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14015 // Likewise do a gc when an app is moving in to the
14016 // background (such as a service stopping).
14017 scheduleAppGcLocked(app);
14018 }
Jeff Brown10e89712011-07-08 18:52:57 -070014019 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014020
Jeff Brown10e89712011-07-08 18:52:57 -070014021 if (wasKeeping && !app.keeping) {
14022 // This app is no longer something we want to keep. Note
14023 // its current wake lock time to later know to kill it if
14024 // it is not behaving well.
14025 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14026 synchronized (stats) {
14027 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14028 app.pid, SystemClock.elapsedRealtime());
14029 }
14030 app.lastCpuTime = app.curCpuTime;
14031 }
14032
14033 app.setRawAdj = app.curRawAdj;
14034 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014035
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014036 if (app.curAdj != app.setAdj) {
14037 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014038 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014039 TAG, "Set " + app.pid + " " + app.processName +
14040 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014041 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014042 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014043 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014044 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014045 }
14046 }
14047 if (app.setSchedGroup != app.curSchedGroup) {
14048 app.setSchedGroup = app.curSchedGroup;
14049 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14050 "Setting process group of " + app.processName
14051 + " to " + app.curSchedGroup);
14052 if (app.waitingToKill != null &&
14053 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14054 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14055 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14056 app.processName, app.setAdj, app.waitingToKill);
14057 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014058 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014059 } else {
14060 if (true) {
14061 long oldId = Binder.clearCallingIdentity();
14062 try {
14063 Process.setProcessGroup(app.pid, app.curSchedGroup);
14064 } catch (Exception e) {
14065 Slog.w(TAG, "Failed setting process group of " + app.pid
14066 + " to " + app.curSchedGroup);
14067 e.printStackTrace();
14068 } finally {
14069 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014070 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014071 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014072 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014073 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014074 app.thread.setSchedulingGroup(app.curSchedGroup);
14075 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014076 }
14077 }
14078 }
14079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014080 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014081 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 }
14083
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014084 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014085 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014086 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014087 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014088 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014089 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014090 }
14091 }
14092 return resumedActivity;
14093 }
14094
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014095 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014096 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014097 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14098 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014099 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14100 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014101
14102 mAdjSeq++;
14103
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014104 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014105 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14106 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014107 if (nowHidden != wasHidden) {
14108 // Changed to/from hidden state, so apps after it in the LRU
14109 // list may also be changed.
14110 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014111 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014112 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014113 }
14114
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014115 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014116 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014117 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14118
14119 if (false) {
14120 RuntimeException e = new RuntimeException();
14121 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014122 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014123 }
14124
14125 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014126 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014127
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014128 // Let's determine how many processes we have running vs.
14129 // how many slots we have for background processes; we may want
14130 // to put multiple processes in a slot of there are enough of
14131 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014132 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014133 int factor = (mLruProcesses.size()-4)/numSlots;
14134 if (factor < 1) factor = 1;
14135 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014136 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014137
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014138 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014139 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014140 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014141 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014142 while (i > 0) {
14143 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014144 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014145 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014146 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14147 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014148 && app.curAdj == curHiddenAdj) {
14149 step++;
14150 if (step >= factor) {
14151 step = 0;
14152 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014154 }
14155 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014156 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014157 numHidden++;
14158 if (numHidden > mProcessLimit) {
14159 Slog.i(TAG, "No longer want " + app.processName
14160 + " (pid " + app.pid + "): hidden #" + numHidden);
14161 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14162 app.processName, app.setAdj, "too many background");
14163 app.killedBackground = true;
14164 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014165 }
14166 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014167 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14168 // If this is an isolated process, and there are no
14169 // services running in it, then the process is no longer
14170 // needed. We agressively kill these because we can by
14171 // definition not re-use the same process again, and it is
14172 // good to avoid having whatever code was running in them
14173 // left sitting around after no longer needed.
14174 Slog.i(TAG, "Isolated process " + app.processName
14175 + " (pid " + app.pid + ") no longer needed");
14176 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14177 app.processName, app.setAdj, "isolated not needed");
14178 app.killedBackground = true;
14179 Process.killProcessQuiet(app.pid);
14180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014181 }
14182 }
14183
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014184 mNumServiceProcs = mNewNumServiceProcs;
14185
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014186 // Now determine the memory trimming level of background processes.
14187 // Unfortunately we need to start at the back of the list to do this
14188 // properly. We only do this if the number of background apps we
14189 // are managing to keep around is less than half the maximum we desire;
14190 // if we are keeping a good number around, we'll let them use whatever
14191 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014192 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014193 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014194 factor = numHidden/3;
14195 int minFactor = 2;
14196 if (mHomeProcess != null) minFactor++;
14197 if (mPreviousProcess != null) minFactor++;
14198 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014199 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014200 int fgTrimLevel;
14201 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14202 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14203 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14204 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14205 } else {
14206 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14207 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014208 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014209 for (i=0; i<N; i++) {
14210 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014211 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14212 && app.curAdj != ProcessList.SERVICE_B_ADJ
14213 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014214 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14215 try {
14216 app.thread.scheduleTrimMemory(curLevel);
14217 } catch (RemoteException e) {
14218 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014219 if (false) {
14220 // For now we won't do this; our memory trimming seems
14221 // to be good enough at this point that destroying
14222 // activities causes more harm than good.
14223 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14224 && app != mHomeProcess && app != mPreviousProcess) {
14225 // For these apps we will also finish their activities
14226 // to help them free memory.
14227 mMainStack.destroyActivitiesLocked(app, false, "trim");
14228 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014229 }
14230 }
14231 app.trimMemoryLevel = curLevel;
14232 step++;
14233 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014234 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014235 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014236 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14237 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014238 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014239 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14240 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014241 break;
14242 }
14243 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014244 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014245 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014246 && app.thread != null) {
14247 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014248 app.thread.scheduleTrimMemory(
14249 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014250 } catch (RemoteException e) {
14251 }
14252 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014253 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014254 } else {
14255 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14256 && app.pendingUiClean) {
14257 // If this application is now in the background and it
14258 // had done UI, then give it the special trim level to
14259 // have it free UI resources.
14260 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14261 if (app.trimMemoryLevel < level && app.thread != null) {
14262 try {
14263 app.thread.scheduleTrimMemory(level);
14264 } catch (RemoteException e) {
14265 }
14266 }
14267 app.pendingUiClean = false;
14268 }
14269 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014270 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014271 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014272 } catch (RemoteException e) {
14273 }
14274 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014275 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014276 }
14277 }
14278 } else {
14279 final int N = mLruProcesses.size();
14280 for (i=0; i<N; i++) {
14281 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014282 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014283 && app.pendingUiClean) {
14284 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14285 && app.thread != null) {
14286 try {
14287 app.thread.scheduleTrimMemory(
14288 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14289 } catch (RemoteException e) {
14290 }
14291 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014292 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014293 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014294 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014295 }
14296 }
14297
14298 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014299 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014301 }
14302
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014303 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014304 synchronized (this) {
14305 int i;
14306
14307 // First remove any unused application processes whose package
14308 // has been removed.
14309 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14310 final ProcessRecord app = mRemovedProcesses.get(i);
14311 if (app.activities.size() == 0
14312 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014313 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014314 TAG, "Exiting empty application process "
14315 + app.processName + " ("
14316 + (app.thread != null ? app.thread.asBinder() : null)
14317 + ")\n");
14318 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014319 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14320 app.processName, app.setAdj, "empty");
14321 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 } else {
14323 try {
14324 app.thread.scheduleExit();
14325 } catch (Exception e) {
14326 // Ignore exceptions.
14327 }
14328 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014329 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014330 mRemovedProcesses.remove(i);
14331
14332 if (app.persistent) {
14333 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014334 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014335 }
14336 }
14337 }
14338 }
14339
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014340 // Now update the oom adj for all processes.
14341 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014342 }
14343 }
14344
14345 /** This method sends the specified signal to each of the persistent apps */
14346 public void signalPersistentProcesses(int sig) throws RemoteException {
14347 if (sig != Process.SIGNAL_USR1) {
14348 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14349 }
14350
14351 synchronized (this) {
14352 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14353 != PackageManager.PERMISSION_GRANTED) {
14354 throw new SecurityException("Requires permission "
14355 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14356 }
14357
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014358 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14359 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014360 if (r.thread != null && r.persistent) {
14361 Process.sendSignal(r.pid, sig);
14362 }
14363 }
14364 }
14365 }
14366
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014367 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14368 if (proc == null || proc == mProfileProc) {
14369 proc = mProfileProc;
14370 path = mProfileFile;
14371 profileType = mProfileType;
14372 clearProfilerLocked();
14373 }
14374 if (proc == null) {
14375 return;
14376 }
14377 try {
14378 proc.thread.profilerControl(false, path, null, profileType);
14379 } catch (RemoteException e) {
14380 throw new IllegalStateException("Process disappeared");
14381 }
14382 }
14383
14384 private void clearProfilerLocked() {
14385 if (mProfileFd != null) {
14386 try {
14387 mProfileFd.close();
14388 } catch (IOException e) {
14389 }
14390 }
14391 mProfileApp = null;
14392 mProfileProc = null;
14393 mProfileFile = null;
14394 mProfileType = 0;
14395 mAutoStopProfiler = false;
14396 }
14397
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014398 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014399 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014400
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014401 try {
14402 synchronized (this) {
14403 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14404 // its own permission.
14405 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14406 != PackageManager.PERMISSION_GRANTED) {
14407 throw new SecurityException("Requires permission "
14408 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014409 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014410
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014411 if (start && fd == null) {
14412 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014413 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014414
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014415 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014416 if (process != null) {
14417 try {
14418 int pid = Integer.parseInt(process);
14419 synchronized (mPidsSelfLocked) {
14420 proc = mPidsSelfLocked.get(pid);
14421 }
14422 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014423 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014424
14425 if (proc == null) {
14426 HashMap<String, SparseArray<ProcessRecord>> all
14427 = mProcessNames.getMap();
14428 SparseArray<ProcessRecord> procs = all.get(process);
14429 if (procs != null && procs.size() > 0) {
14430 proc = procs.valueAt(0);
14431 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014432 }
14433 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014434
14435 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014436 throw new IllegalArgumentException("Unknown process: " + process);
14437 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014438
14439 if (start) {
14440 stopProfilerLocked(null, null, 0);
14441 setProfileApp(proc.info, proc.processName, path, fd, false);
14442 mProfileProc = proc;
14443 mProfileType = profileType;
14444 try {
14445 fd = fd.dup();
14446 } catch (IOException e) {
14447 fd = null;
14448 }
14449 proc.thread.profilerControl(start, path, fd, profileType);
14450 fd = null;
14451 mProfileFd = null;
14452 } else {
14453 stopProfilerLocked(proc, path, profileType);
14454 if (fd != null) {
14455 try {
14456 fd.close();
14457 } catch (IOException e) {
14458 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014459 }
14460 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014461
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014462 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014463 }
14464 } catch (RemoteException e) {
14465 throw new IllegalStateException("Process disappeared");
14466 } finally {
14467 if (fd != null) {
14468 try {
14469 fd.close();
14470 } catch (IOException e) {
14471 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014472 }
14473 }
14474 }
Andy McFadden824c5102010-07-09 16:26:57 -070014475
14476 public boolean dumpHeap(String process, boolean managed,
14477 String path, ParcelFileDescriptor fd) throws RemoteException {
14478
14479 try {
14480 synchronized (this) {
14481 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14482 // its own permission (same as profileControl).
14483 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14484 != PackageManager.PERMISSION_GRANTED) {
14485 throw new SecurityException("Requires permission "
14486 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14487 }
14488
14489 if (fd == null) {
14490 throw new IllegalArgumentException("null fd");
14491 }
14492
14493 ProcessRecord proc = null;
14494 try {
14495 int pid = Integer.parseInt(process);
14496 synchronized (mPidsSelfLocked) {
14497 proc = mPidsSelfLocked.get(pid);
14498 }
14499 } catch (NumberFormatException e) {
14500 }
14501
14502 if (proc == null) {
14503 HashMap<String, SparseArray<ProcessRecord>> all
14504 = mProcessNames.getMap();
14505 SparseArray<ProcessRecord> procs = all.get(process);
14506 if (procs != null && procs.size() > 0) {
14507 proc = procs.valueAt(0);
14508 }
14509 }
14510
14511 if (proc == null || proc.thread == null) {
14512 throw new IllegalArgumentException("Unknown process: " + process);
14513 }
14514
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014515 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14516 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014517 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14518 throw new SecurityException("Process not debuggable: " + proc);
14519 }
14520 }
14521
14522 proc.thread.dumpHeap(managed, path, fd);
14523 fd = null;
14524 return true;
14525 }
14526 } catch (RemoteException e) {
14527 throw new IllegalStateException("Process disappeared");
14528 } finally {
14529 if (fd != null) {
14530 try {
14531 fd.close();
14532 } catch (IOException e) {
14533 }
14534 }
14535 }
14536 }
14537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014538 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14539 public void monitor() {
14540 synchronized (this) { }
14541 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014542
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014543 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014544 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14545 ProcessRecord processRecord = mLruProcesses.get(i);
14546 try {
14547 if (processRecord.thread != null) {
14548 processRecord.thread.setCoreSettings(settings);
14549 }
14550 } catch (RemoteException re) {
14551 /* ignore */
14552 }
14553 }
14554 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014555
14556 // Multi-user methods
14557
Amith Yamasani742a6712011-05-04 14:49:28 -070014558 private int mCurrentUserId;
14559 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014560 private ArrayList<UserListener> mUserListeners = new ArrayList<UserListener>(3);
14561
14562 public interface UserListener {
14563 public void onUserChanged(int userId);
14564
14565 public void onUserAdded(int userId);
14566
14567 public void onUserRemoved(int userId);
14568
14569 public void onUserLoggedOut(int userId);
14570 }
14571
14572 public void addUserListener(UserListener listener) {
14573 synchronized (this) {
14574 if (!mUserListeners.contains(listener)) {
14575 mUserListeners.add(listener);
14576 }
14577 }
14578 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014579
14580 public boolean switchUser(int userId) {
14581 final int callingUid = Binder.getCallingUid();
14582 if (callingUid != 0 && callingUid != Process.myUid()) {
14583 Slog.e(TAG, "Trying to switch user from unauthorized app");
14584 return false;
14585 }
14586 if (mCurrentUserId == userId)
14587 return true;
14588
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014589 ArrayList<UserListener> listeners;
14590
Amith Yamasani742a6712011-05-04 14:49:28 -070014591 synchronized (this) {
14592 // Check if user is already logged in, otherwise check if user exists first before
14593 // adding to the list of logged in users.
14594 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14595 if (!userExists(userId)) {
14596 return false;
14597 }
14598 mLoggedInUsers.append(userId, userId);
14599 }
14600
14601 mCurrentUserId = userId;
14602 boolean haveActivities = mMainStack.switchUser(userId);
14603 if (!haveActivities) {
14604 startHomeActivityLocked(userId);
14605 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014606
14607 listeners = (ArrayList<UserListener>) mUserListeners.clone();
14608 }
14609 // Inform the listeners
14610 for (UserListener listener : listeners) {
14611 listener.onUserChanged(userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070014612 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014613 return true;
14614 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014615
14616 private boolean userExists(int userId) {
14617 try {
14618 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
14619 for (UserInfo user : users) {
14620 if (user.id == userId) {
14621 return true;
14622 }
14623 }
14624 } catch (RemoteException re) {
14625 // Won't happen, in same process
14626 }
14627
14628 return false;
14629 }
14630
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014631 private void checkValidCaller(int uid, int userId) {
14632 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14633
14634 throw new SecurityException("Caller uid=" + uid
14635 + " is not privileged to communicate with user=" + userId);
14636 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014637
14638 private int applyUserId(int uid, int userId) {
14639 return UserId.getUid(userId, uid);
14640 }
14641
14642 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014643 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014644 ApplicationInfo newInfo = new ApplicationInfo(info);
14645 newInfo.uid = applyUserId(info.uid, userId);
14646 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14647 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14648 + info.packageName;
14649 }
14650 return newInfo;
14651 }
14652
14653 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014654 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014655 || userId < 1) {
14656 return aInfo;
14657 }
14658
14659 ActivityInfo info = new ActivityInfo(aInfo);
14660 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14661 return info;
14662 }
14663
14664 static class ServiceMap {
14665
14666 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14667 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14668 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14669 mServicesByIntentPerUser = new SparseArray<
14670 HashMap<Intent.FilterComparison, ServiceRecord>>();
14671
14672 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14673 // TODO: Deal with global services
14674 if (DEBUG_MU)
14675 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14676 return getServices(callingUser).get(name);
14677 }
14678
14679 ServiceRecord getServiceByName(ComponentName name) {
14680 return getServiceByName(name, -1);
14681 }
14682
14683 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14684 // TODO: Deal with global services
14685 if (DEBUG_MU)
14686 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14687 return getServicesByIntent(callingUser).get(filter);
14688 }
14689
14690 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14691 return getServiceByIntent(filter, -1);
14692 }
14693
14694 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14695 // TODO: Deal with global services
14696 getServices(callingUser).put(name, value);
14697 }
14698
14699 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14700 ServiceRecord value) {
14701 // TODO: Deal with global services
14702 getServicesByIntent(callingUser).put(filter, value);
14703 }
14704
14705 void removeServiceByName(ComponentName name, int callingUser) {
14706 // TODO: Deal with global services
14707 ServiceRecord removed = getServices(callingUser).remove(name);
14708 if (DEBUG_MU)
14709 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14710 + " removed=" + removed);
14711 }
14712
14713 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14714 // TODO: Deal with global services
14715 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14716 if (DEBUG_MU)
14717 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14718 + " removed=" + removed);
14719 }
14720
14721 Collection<ServiceRecord> getAllServices(int callingUser) {
14722 // TODO: Deal with global services
14723 return getServices(callingUser).values();
14724 }
14725
14726 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14727 HashMap map = mServicesByNamePerUser.get(callingUser);
14728 if (map == null) {
14729 map = new HashMap<ComponentName, ServiceRecord>();
14730 mServicesByNamePerUser.put(callingUser, map);
14731 }
14732 return map;
14733 }
14734
14735 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14736 int callingUser) {
14737 HashMap map = mServicesByIntentPerUser.get(callingUser);
14738 if (map == null) {
14739 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14740 mServicesByIntentPerUser.put(callingUser, map);
14741 }
14742 return map;
14743 }
14744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014745}