blob: 33250b8b6c15143bdff113dc9f1cd957ede3cf5c [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;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070065import android.content.IIntentReceiver;
66import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070067import android.content.Intent;
68import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070069import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.content.pm.ActivityInfo;
71import android.content.pm.ApplicationInfo;
72import android.content.pm.ConfigurationInfo;
73import android.content.pm.IPackageDataObserver;
74import android.content.pm.IPackageManager;
75import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080076import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070078import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070079import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.content.pm.ProviderInfo;
81import android.content.pm.ResolveInfo;
82import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070083import android.content.pm.UserInfo;
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;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800116import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700117import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700119import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import 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.ref.WeakReference;
144import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700145import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700146import java.util.Collections;
147import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148import java.util.HashMap;
149import java.util.HashSet;
150import java.util.Iterator;
151import java.util.List;
152import java.util.Locale;
153import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700154import java.util.Map.Entry;
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
Justin Kohbc52ca22012-03-29 15:11:44 -0700906 if (mShowDialogs) {
907 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700908 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700909 d.show();
910 proc.anrDialog = d;
911 } else {
912 // Just kill the app if there is no dialog to be shown.
913 killAppAtUsersRequest(proc, null);
914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700916
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700917 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700919 case SHOW_STRICT_MODE_VIOLATION_MSG: {
920 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
921 synchronized (ActivityManagerService.this) {
922 ProcessRecord proc = (ProcessRecord) data.get("app");
923 if (proc == null) {
924 Slog.e(TAG, "App not found when showing strict mode dialog.");
925 break;
926 }
927 if (proc.crashDialog != null) {
928 Slog.e(TAG, "App already has strict mode dialog: " + proc);
929 return;
930 }
931 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700932 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700933 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
934 d.show();
935 proc.crashDialog = d;
936 } else {
937 // The device is asleep, so just pretend that the user
938 // saw a crash dialog and hit "force quit".
939 res.set(0);
940 }
941 }
942 ensureBootCompleted();
943 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800944 case SHOW_FACTORY_ERROR_MSG: {
945 Dialog d = new FactoryErrorDialog(
946 mContext, msg.getData().getCharSequence("msg"));
947 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700948 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800949 } break;
950 case UPDATE_CONFIGURATION_MSG: {
951 final ContentResolver resolver = mContext.getContentResolver();
952 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
953 } break;
954 case GC_BACKGROUND_PROCESSES_MSG: {
955 synchronized (ActivityManagerService.this) {
956 performAppGcsIfAppropriateLocked();
957 }
958 } break;
959 case WAIT_FOR_DEBUGGER_MSG: {
960 synchronized (ActivityManagerService.this) {
961 ProcessRecord app = (ProcessRecord)msg.obj;
962 if (msg.arg1 != 0) {
963 if (!app.waitedForDebugger) {
964 Dialog d = new AppWaitingForDebuggerDialog(
965 ActivityManagerService.this,
966 mContext, app);
967 app.waitDialog = d;
968 app.waitedForDebugger = true;
969 d.show();
970 }
971 } else {
972 if (app.waitDialog != null) {
973 app.waitDialog.dismiss();
974 app.waitDialog = null;
975 }
976 }
977 }
978 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700980 if (mDidDexOpt) {
981 mDidDexOpt = false;
982 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
983 nmsg.obj = msg.obj;
984 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
985 return;
986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 serviceTimeout((ProcessRecord)msg.obj);
988 } break;
989 case UPDATE_TIME_ZONE: {
990 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800991 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
992 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 if (r.thread != null) {
994 try {
995 r.thread.updateTimeZone();
996 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999 }
1000 }
1001 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001002 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001003 case CLEAR_DNS_CACHE: {
1004 synchronized (ActivityManagerService.this) {
1005 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1006 ProcessRecord r = mLruProcesses.get(i);
1007 if (r.thread != null) {
1008 try {
1009 r.thread.clearDnsCache();
1010 } catch (RemoteException ex) {
1011 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1012 }
1013 }
1014 }
1015 }
1016 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001017 case UPDATE_HTTP_PROXY: {
1018 ProxyProperties proxy = (ProxyProperties)msg.obj;
1019 String host = "";
1020 String port = "";
1021 String exclList = "";
1022 if (proxy != null) {
1023 host = proxy.getHost();
1024 port = Integer.toString(proxy.getPort());
1025 exclList = proxy.getExclusionList();
1026 }
1027 synchronized (ActivityManagerService.this) {
1028 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1029 ProcessRecord r = mLruProcesses.get(i);
1030 if (r.thread != null) {
1031 try {
1032 r.thread.setHttpProxy(host, port, exclList);
1033 } catch (RemoteException ex) {
1034 Slog.w(TAG, "Failed to update http proxy for: " +
1035 r.info.processName);
1036 }
1037 }
1038 }
1039 }
1040 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001042 String title = "System UIDs Inconsistent";
1043 String text = "UIDs on the system are inconsistent, you need to wipe your"
1044 + " data partition or your device will be unstable.";
1045 Log.e(TAG, title + ": " + text);
1046 if (mShowDialogs) {
1047 // XXX This is a temporary dialog, no need to localize.
1048 AlertDialog d = new BaseErrorDialog(mContext);
1049 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1050 d.setCancelable(false);
1051 d.setTitle(title);
1052 d.setMessage(text);
1053 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1054 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1055 mUidAlert = d;
1056 d.show();
1057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 } break;
1059 case IM_FEELING_LUCKY_MSG: {
1060 if (mUidAlert != null) {
1061 mUidAlert.dismiss();
1062 mUidAlert = null;
1063 }
1064 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001066 if (mDidDexOpt) {
1067 mDidDexOpt = false;
1068 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1069 nmsg.obj = msg.obj;
1070 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1071 return;
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 ProcessRecord app = (ProcessRecord)msg.obj;
1074 synchronized (ActivityManagerService.this) {
1075 processStartTimedOutLocked(app);
1076 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001077 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001078 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1079 synchronized (ActivityManagerService.this) {
1080 doPendingActivityLaunchesLocked(true);
1081 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001082 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001083 case KILL_APPLICATION_MSG: {
1084 synchronized (ActivityManagerService.this) {
1085 int uid = msg.arg1;
1086 boolean restart = (msg.arg2 == 1);
1087 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001088 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1089 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001090 }
1091 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001092 case FINALIZE_PENDING_INTENT_MSG: {
1093 ((PendingIntentRecord)msg.obj).completeFinalize();
1094 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001095 case POST_HEAVY_NOTIFICATION_MSG: {
1096 INotificationManager inm = NotificationManager.getService();
1097 if (inm == null) {
1098 return;
1099 }
1100
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001101 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001102 ProcessRecord process = root.app;
1103 if (process == null) {
1104 return;
1105 }
1106
1107 try {
1108 Context context = mContext.createPackageContext(process.info.packageName, 0);
1109 String text = mContext.getString(R.string.heavy_weight_notification,
1110 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1111 Notification notification = new Notification();
1112 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1113 notification.when = 0;
1114 notification.flags = Notification.FLAG_ONGOING_EVENT;
1115 notification.tickerText = text;
1116 notification.defaults = 0; // please be quiet
1117 notification.sound = null;
1118 notification.vibrate = null;
1119 notification.setLatestEventInfo(context, text,
1120 mContext.getText(R.string.heavy_weight_notification_detail),
1121 PendingIntent.getActivity(mContext, 0, root.intent,
1122 PendingIntent.FLAG_CANCEL_CURRENT));
1123
1124 try {
1125 int[] outId = new int[1];
1126 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1127 notification, outId);
1128 } catch (RuntimeException e) {
1129 Slog.w(ActivityManagerService.TAG,
1130 "Error showing notification for heavy-weight app", e);
1131 } catch (RemoteException e) {
1132 }
1133 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001134 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001135 }
1136 } break;
1137 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1138 INotificationManager inm = NotificationManager.getService();
1139 if (inm == null) {
1140 return;
1141 }
1142 try {
1143 inm.cancelNotification("android",
1144 R.string.heavy_weight_notification);
1145 } catch (RuntimeException e) {
1146 Slog.w(ActivityManagerService.TAG,
1147 "Error canceling notification for service", e);
1148 } catch (RemoteException e) {
1149 }
1150 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001151 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1152 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001153 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001154 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001155 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1156 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001157 }
1158 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001159 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1160 synchronized (ActivityManagerService.this) {
1161 ActivityRecord ar = (ActivityRecord)msg.obj;
1162 if (mCompatModeDialog != null) {
1163 if (mCompatModeDialog.mAppInfo.packageName.equals(
1164 ar.info.applicationInfo.packageName)) {
1165 return;
1166 }
1167 mCompatModeDialog.dismiss();
1168 mCompatModeDialog = null;
1169 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001170 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001171 if (mCompatModePackages.getPackageAskCompatModeLocked(
1172 ar.packageName)) {
1173 int mode = mCompatModePackages.computeCompatModeLocked(
1174 ar.info.applicationInfo);
1175 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1176 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1177 mCompatModeDialog = new CompatModeDialog(
1178 ActivityManagerService.this, mContext,
1179 ar.info.applicationInfo);
1180 mCompatModeDialog.show();
1181 }
1182 }
1183 }
1184 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001185 break;
1186 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001187 case DISPATCH_FOREGROUND_ACTIVITIES_CHANGED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001188 final int pid = msg.arg1;
1189 final int uid = msg.arg2;
1190 final boolean foregroundActivities = (Boolean) msg.obj;
1191 dispatchForegroundActivitiesChanged(pid, uid, foregroundActivities);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001192 break;
1193 }
1194 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001195 final int pid = msg.arg1;
1196 final int uid = msg.arg2;
1197 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001198 break;
1199 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001200 case REPORT_MEM_USAGE: {
1201 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1202 if (!isDebuggable) {
1203 return;
1204 }
1205 synchronized (ActivityManagerService.this) {
1206 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001207 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1208 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001209 // avoid spamming.
1210 return;
1211 }
1212 mLastMemUsageReportTime = now;
1213 }
1214 Thread thread = new Thread() {
1215 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001216 StringBuilder dropBuilder = new StringBuilder(1024);
1217 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001218 StringWriter oomSw = new StringWriter();
1219 PrintWriter oomPw = new PrintWriter(oomSw);
1220 StringWriter catSw = new StringWriter();
1221 PrintWriter catPw = new PrintWriter(catSw);
1222 String[] emptyArgs = new String[] { };
1223 StringBuilder tag = new StringBuilder(128);
1224 StringBuilder stack = new StringBuilder(128);
1225 tag.append("Low on memory -- ");
1226 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1227 tag, stack);
1228 dropBuilder.append(stack);
1229 dropBuilder.append('\n');
1230 dropBuilder.append('\n');
1231 String oomString = oomSw.toString();
1232 dropBuilder.append(oomString);
1233 dropBuilder.append('\n');
1234 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001235 try {
1236 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1237 "procrank", });
1238 final InputStreamReader converter = new InputStreamReader(
1239 proc.getInputStream());
1240 BufferedReader in = new BufferedReader(converter);
1241 String line;
1242 while (true) {
1243 line = in.readLine();
1244 if (line == null) {
1245 break;
1246 }
1247 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001248 logBuilder.append(line);
1249 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001250 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001251 dropBuilder.append(line);
1252 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001253 }
1254 converter.close();
1255 } catch (IOException e) {
1256 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001257 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001258 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001259 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001260 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001261 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001262 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001263 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001264 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001265 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001266 addErrorToDropBox("lowmem", null, "system_server", null,
1267 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001268 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001269 synchronized (ActivityManagerService.this) {
1270 long now = SystemClock.uptimeMillis();
1271 if (mLastMemUsageReportTime < now) {
1272 mLastMemUsageReportTime = now;
1273 }
1274 }
1275 }
1276 };
1277 thread.start();
1278 break;
1279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 }
1282 };
1283
1284 public static void setSystemProcess() {
1285 try {
1286 ActivityManagerService m = mSelf;
1287
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001288 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001290 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001291 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 if (MONITOR_CPU_USAGE) {
1293 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 ServiceManager.addService("permission", new PermissionController(m));
1296
1297 ApplicationInfo info =
1298 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001299 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001300 mSystemThread.installSystemApplicationInfo(info);
1301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 synchronized (mSelf) {
1303 ProcessRecord app = mSelf.newProcessRecordLocked(
1304 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001305 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001307 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001308 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001309 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 synchronized (mSelf.mPidsSelfLocked) {
1311 mSelf.mPidsSelfLocked.put(app.pid, app);
1312 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001313 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
1315 } catch (PackageManager.NameNotFoundException e) {
1316 throw new RuntimeException(
1317 "Unable to find android system package", e);
1318 }
1319 }
1320
1321 public void setWindowManager(WindowManagerService wm) {
1322 mWindowManager = wm;
1323 }
1324
1325 public static final Context main(int factoryTest) {
1326 AThread thr = new AThread();
1327 thr.start();
1328
1329 synchronized (thr) {
1330 while (thr.mService == null) {
1331 try {
1332 thr.wait();
1333 } catch (InterruptedException e) {
1334 }
1335 }
1336 }
1337
1338 ActivityManagerService m = thr.mService;
1339 mSelf = m;
1340 ActivityThread at = ActivityThread.systemMain();
1341 mSystemThread = at;
1342 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001343 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 m.mContext = context;
1345 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001346 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347
1348 m.mBatteryStatsService.publish(context);
1349 m.mUsageStatsService.publish(context);
1350
1351 synchronized (thr) {
1352 thr.mReady = true;
1353 thr.notifyAll();
1354 }
1355
1356 m.startRunning(null, null, null, null);
1357
1358 return context;
1359 }
1360
1361 public static ActivityManagerService self() {
1362 return mSelf;
1363 }
1364
1365 static class AThread extends Thread {
1366 ActivityManagerService mService;
1367 boolean mReady = false;
1368
1369 public AThread() {
1370 super("ActivityManager");
1371 }
1372
1373 public void run() {
1374 Looper.prepare();
1375
1376 android.os.Process.setThreadPriority(
1377 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001378 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379
1380 ActivityManagerService m = new ActivityManagerService();
1381
1382 synchronized (this) {
1383 mService = m;
1384 notifyAll();
1385 }
1386
1387 synchronized (this) {
1388 while (!mReady) {
1389 try {
1390 wait();
1391 } catch (InterruptedException e) {
1392 }
1393 }
1394 }
1395
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001396 // For debug builds, log event loop stalls to dropbox for analysis.
1397 if (StrictMode.conditionallyEnableDebugLogging()) {
1398 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 Looper.loop();
1402 }
1403 }
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 static class MemBinder extends Binder {
1406 ActivityManagerService mActivityManagerService;
1407 MemBinder(ActivityManagerService activityManagerService) {
1408 mActivityManagerService = activityManagerService;
1409 }
1410
1411 @Override
1412 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001413 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1414 != PackageManager.PERMISSION_GRANTED) {
1415 pw.println("Permission Denial: can't dump meminfo from from pid="
1416 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1417 + " without permission " + android.Manifest.permission.DUMP);
1418 return;
1419 }
1420
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001421 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001422 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
1424 }
1425
Chet Haase9c1e23b2011-03-24 10:51:31 -07001426 static class GraphicsBinder extends Binder {
1427 ActivityManagerService mActivityManagerService;
1428 GraphicsBinder(ActivityManagerService activityManagerService) {
1429 mActivityManagerService = activityManagerService;
1430 }
1431
1432 @Override
1433 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001434 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1435 != PackageManager.PERMISSION_GRANTED) {
1436 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1437 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1438 + " without permission " + android.Manifest.permission.DUMP);
1439 return;
1440 }
1441
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001442 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001443 }
1444 }
1445
Jeff Brown6754ba22011-12-14 20:20:01 -08001446 static class DbBinder extends Binder {
1447 ActivityManagerService mActivityManagerService;
1448 DbBinder(ActivityManagerService activityManagerService) {
1449 mActivityManagerService = activityManagerService;
1450 }
1451
1452 @Override
1453 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1454 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1455 != PackageManager.PERMISSION_GRANTED) {
1456 pw.println("Permission Denial: can't dump dbinfo from from pid="
1457 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1458 + " without permission " + android.Manifest.permission.DUMP);
1459 return;
1460 }
1461
1462 mActivityManagerService.dumpDbInfo(fd, pw, args);
1463 }
1464 }
1465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 static class CpuBinder extends Binder {
1467 ActivityManagerService mActivityManagerService;
1468 CpuBinder(ActivityManagerService activityManagerService) {
1469 mActivityManagerService = activityManagerService;
1470 }
1471
1472 @Override
1473 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001474 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1475 != PackageManager.PERMISSION_GRANTED) {
1476 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1477 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1478 + " without permission " + android.Manifest.permission.DUMP);
1479 return;
1480 }
1481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001483 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1484 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1485 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487 }
1488 }
1489
1490 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001491 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001492
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001493 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1494 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1495 mBroadcastQueues[0] = mFgBroadcastQueue;
1496 mBroadcastQueues[1] = mBgBroadcastQueue;
1497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 File dataDir = Environment.getDataDirectory();
1499 File systemDir = new File(dataDir, "system");
1500 systemDir.mkdirs();
1501 mBatteryStatsService = new BatteryStatsService(new File(
1502 systemDir, "batterystats.bin").toString());
1503 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001504 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001505 mOnBattery = DEBUG_POWER ? true
1506 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001507 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001509 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001510 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001511 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512
Jack Palevichb90d28c2009-07-22 15:35:24 -07001513 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1514 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1515
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001516 mConfiguration.setToDefaults();
1517 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001518 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 mProcessStats.init();
1520
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001521 mCompatModePackages = new CompatModePackages(this, systemDir);
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 // Add ourself to the Watchdog monitors.
1524 Watchdog.getInstance().addMonitor(this);
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 mProcessStatsThread = new Thread("ProcessStats") {
1527 public void run() {
1528 while (true) {
1529 try {
1530 try {
1531 synchronized(this) {
1532 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001533 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 // + ", write delay=" + nextWriteDelay);
1537 if (nextWriteDelay < nextCpuDelay) {
1538 nextCpuDelay = nextWriteDelay;
1539 }
1540 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001541 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 this.wait(nextCpuDelay);
1543 }
1544 }
1545 } catch (InterruptedException e) {
1546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 updateCpuStatsNow();
1548 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001549 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 }
1552 }
1553 };
1554 mProcessStatsThread.start();
1555 }
1556
1557 @Override
1558 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1559 throws RemoteException {
1560 try {
1561 return super.onTransact(code, data, reply, flags);
1562 } catch (RuntimeException e) {
1563 // The activity manager only throws security exceptions, so let's
1564 // log all others.
1565 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001566 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
1568 throw e;
1569 }
1570 }
1571
1572 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001573 final long now = SystemClock.uptimeMillis();
1574 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1575 return;
1576 }
1577 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1578 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 mProcessStatsThread.notify();
1580 }
1581 }
1582 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 void updateCpuStatsNow() {
1585 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001586 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 final long now = SystemClock.uptimeMillis();
1588 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001591 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1592 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 haveNewCpuStats = true;
1594 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001595 //Slog.i(TAG, mProcessStats.printCurrentState());
1596 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 // + mProcessStats.getTotalCpuPercent() + "%");
1598
Joe Onorato8a9b2202010-02-26 18:56:32 -08001599 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 if ("true".equals(SystemProperties.get("events.cpu"))) {
1601 int user = mProcessStats.getLastUserTime();
1602 int system = mProcessStats.getLastSystemTime();
1603 int iowait = mProcessStats.getLastIoWaitTime();
1604 int irq = mProcessStats.getLastIrqTime();
1605 int softIrq = mProcessStats.getLastSoftIrqTime();
1606 int idle = mProcessStats.getLastIdleTime();
1607
1608 int total = user + system + iowait + irq + softIrq + idle;
1609 if (total == 0) total = 1;
1610
Doug Zongker2bec3d42009-12-04 12:52:44 -08001611 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 ((user+system+iowait+irq+softIrq) * 100) / total,
1613 (user * 100) / total,
1614 (system * 100) / total,
1615 (iowait * 100) / total,
1616 (irq * 100) / total,
1617 (softIrq * 100) / total);
1618 }
1619 }
1620
Amith Yamasanie43530a2009-08-21 13:11:37 -07001621 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001622 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001623 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 synchronized(mPidsSelfLocked) {
1625 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001626 if (mOnBattery) {
1627 int perc = bstats.startAddingCpuLocked();
1628 int totalUTime = 0;
1629 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001630 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001632 ProcessStats.Stats st = mProcessStats.getStats(i);
1633 if (!st.working) {
1634 continue;
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001637 int otherUTime = (st.rel_utime*perc)/100;
1638 int otherSTime = (st.rel_stime*perc)/100;
1639 totalUTime += otherUTime;
1640 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if (pr != null) {
1642 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001643 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1644 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001645 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001646 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001647 } else {
1648 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001649 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001650 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001651 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1652 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001653 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 }
1656 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001657 bstats.finishAddingCpuLocked(perc, totalUTime,
1658 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 }
1660 }
1661 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1664 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001665 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 }
1668 }
1669 }
1670
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001671 @Override
1672 public void batteryNeedsCpuUpdate() {
1673 updateCpuStatsNow();
1674 }
1675
1676 @Override
1677 public void batteryPowerChanged(boolean onBattery) {
1678 // When plugging in, update the CPU stats first before changing
1679 // the plug state.
1680 updateCpuStatsNow();
1681 synchronized (this) {
1682 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001683 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001684 }
1685 }
1686 }
1687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 /**
1689 * Initialize the application bind args. These are passed to each
1690 * process when the bindApplication() IPC is sent to the process. They're
1691 * lazily setup to make sure the services are running when they're asked for.
1692 */
1693 private HashMap<String, IBinder> getCommonServicesLocked() {
1694 if (mAppBindArgs == null) {
1695 mAppBindArgs = new HashMap<String, IBinder>();
1696
1697 // Setup the application init args
1698 mAppBindArgs.put("package", ServiceManager.getService("package"));
1699 mAppBindArgs.put("window", ServiceManager.getService("window"));
1700 mAppBindArgs.put(Context.ALARM_SERVICE,
1701 ServiceManager.getService(Context.ALARM_SERVICE));
1702 }
1703 return mAppBindArgs;
1704 }
1705
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 if (mFocusedActivity != r) {
1708 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001709 if (r != null) {
1710 mWindowManager.setFocusedApp(r.appToken, true);
1711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
1714
Dianne Hackborn906497c2010-05-10 15:57:38 -07001715 private final void updateLruProcessInternalLocked(ProcessRecord app,
1716 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001718 int lrui = mLruProcesses.indexOf(app);
1719 if (lrui >= 0) mLruProcesses.remove(lrui);
1720
1721 int i = mLruProcesses.size()-1;
1722 int skipTop = 0;
1723
Dianne Hackborn906497c2010-05-10 15:57:38 -07001724 app.lruSeq = mLruSeq;
1725
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001726 // compute the new weight for this process.
1727 if (updateActivityTime) {
1728 app.lastActivityTime = SystemClock.uptimeMillis();
1729 }
1730 if (app.activities.size() > 0) {
1731 // If this process has activities, we more strongly want to keep
1732 // it around.
1733 app.lruWeight = app.lastActivityTime;
1734 } else if (app.pubProviders.size() > 0) {
1735 // If this process contains content providers, we want to keep
1736 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001737 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001738 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001739 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001740 } else {
1741 // If this process doesn't have activities, we less strongly
1742 // want to keep it around, and generally want to avoid getting
1743 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001744 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001745 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001746 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001747 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001748
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001749 while (i >= 0) {
1750 ProcessRecord p = mLruProcesses.get(i);
1751 // If this app shouldn't be in front of the first N background
1752 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001753 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001754 skipTop--;
1755 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 mLruProcesses.add(i+1, app);
1758 break;
1759 }
1760 i--;
1761 }
1762 if (i < 0) {
1763 mLruProcesses.add(0, app);
1764 }
1765
Dianne Hackborn906497c2010-05-10 15:57:38 -07001766 // If the app is currently using a content provider or service,
1767 // bump those processes as well.
1768 if (app.connections.size() > 0) {
1769 for (ConnectionRecord cr : app.connections) {
1770 if (cr.binding != null && cr.binding.service != null
1771 && cr.binding.service.app != null
1772 && cr.binding.service.app.lruSeq != mLruSeq) {
1773 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1774 updateActivityTime, i+1);
1775 }
1776 }
1777 }
1778 if (app.conProviders.size() > 0) {
1779 for (ContentProviderRecord cpr : app.conProviders.keySet()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07001780 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1781 updateLruProcessInternalLocked(cpr.proc, oomAdj,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001782 updateActivityTime, i+1);
1783 }
1784 }
1785 }
1786
Joe Onorato8a9b2202010-02-26 18:56:32 -08001787 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (oomAdj) {
1789 updateOomAdjLocked();
1790 }
1791 }
1792
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001794 boolean oomAdj, boolean updateActivityTime) {
1795 mLruSeq++;
1796 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1797 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001798
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001799 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 String processName, int uid) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001801 // Temporary hack to make Settings run per user
1802 if (uid == Process.SYSTEM_UID && !processName.equals("com.android.settings")) {
1803 // The system gets to run in any process. If there are multiple
1804 // processes with the same uid, just pick the first (this
1805 // should never happen).
1806 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1807 processName);
1808 return procs != null ? procs.valueAt(0) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Amith Yamasani742a6712011-05-04 14:49:28 -07001810 // uid = applyUserId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 ProcessRecord proc = mProcessNames.get(processName, uid);
1812 return proc;
1813 }
1814
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001816 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001817 try {
1818 if (pm.performDexOpt(packageName)) {
1819 mDidDexOpt = true;
1820 }
1821 } catch (RemoteException e) {
1822 }
1823 }
1824
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001825 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 int transit = mWindowManager.getPendingAppTransition();
1827 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1828 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1829 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1830 }
1831
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001832 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001834 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1835 boolean isolated) {
1836 ProcessRecord app;
1837 if (!isolated) {
1838 app = getProcessRecordLocked(processName, info.uid);
1839 } else {
1840 // If this is an isolated process, it can't re-use an existing process.
1841 app = null;
1842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 // We don't have to do anything more if:
1844 // (1) There is an existing application record; and
1845 // (2) The caller doesn't think it is dead, OR there is no thread
1846 // object attached to it so we know it couldn't have crashed; and
1847 // (3) There is a pid assigned to it, so it is either starting or
1848 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001849 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 + " app=" + app + " knownToBeDead=" + knownToBeDead
1851 + " thread=" + (app != null ? app.thread : null)
1852 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001853 if (app != null && app.pid > 0) {
1854 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001855 // We already have the app running, or are waiting for it to
1856 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001857 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001858 // If this is a new package in the process, add the package to the list
1859 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001860 return app;
1861 } else {
1862 // An application record is attached to a previous process,
1863 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001864 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001865 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 String hostingNameStr = hostingName != null
1870 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001871
1872 if (!isolated) {
1873 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1874 // If we are in the background, then check to see if this process
1875 // is bad. If so, we will just silently fail.
1876 if (mBadProcesses.get(info.processName, info.uid) != null) {
1877 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1878 + "/" + info.processName);
1879 return null;
1880 }
1881 } else {
1882 // When the user is explicitly starting a process, then clear its
1883 // crash count so that we won't make it bad until they see at
1884 // least one crash dialog again, and make the process good again
1885 // if it had been bad.
1886 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001887 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001888 mProcessCrashTimes.remove(info.processName, info.uid);
1889 if (mBadProcesses.get(info.processName, info.uid) != null) {
1890 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1891 info.processName);
1892 mBadProcesses.remove(info.processName, info.uid);
1893 if (app != null) {
1894 app.bad = false;
1895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897 }
1898 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001901 app = newProcessRecordLocked(null, info, processName, isolated);
1902 if (app == null) {
1903 Slog.w(TAG, "Failed making new process record for "
1904 + processName + "/" + info.uid + " isolated=" + isolated);
1905 return null;
1906 }
1907 mProcessNames.put(processName, app.uid, app);
1908 if (isolated) {
1909 mIsolatedProcesses.put(app.uid, app);
1910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 } else {
1912 // If this is a new package in the process, add the package to the list
1913 app.addPackage(info.packageName);
1914 }
1915
1916 // If the system is not ready yet, then hold off on starting this
1917 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001918 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001919 && !isAllowedWhileBooting(info)
1920 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 if (!mProcessesOnHold.contains(app)) {
1922 mProcessesOnHold.add(app);
1923 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001924 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 return app;
1926 }
1927
1928 startProcessLocked(app, hostingType, hostingNameStr);
1929 return (app.pid != 0) ? app : null;
1930 }
1931
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001932 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1933 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1934 }
1935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 private final void startProcessLocked(ProcessRecord app,
1937 String hostingType, String hostingNameStr) {
1938 if (app.pid > 0 && app.pid != MY_PID) {
1939 synchronized (mPidsSelfLocked) {
1940 mPidsSelfLocked.remove(app.pid);
1941 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1942 }
1943 app.pid = 0;
1944 }
1945
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001946 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1947 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 mProcessesOnHold.remove(app);
1949
1950 updateCpuStats();
1951
1952 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1953 mProcDeaths[0] = 0;
1954
1955 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001956 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001959 if (!app.isolated) {
1960 try {
1961 gids = mContext.getPackageManager().getPackageGids(
1962 app.info.packageName);
1963 } catch (PackageManager.NameNotFoundException e) {
1964 Slog.w(TAG, "Unable to retrieve gids", e);
1965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
1967 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
1968 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
1969 && mTopComponent != null
1970 && app.processName.equals(mTopComponent.getPackageName())) {
1971 uid = 0;
1972 }
1973 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
1974 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
1975 uid = 0;
1976 }
1977 }
1978 int debugFlags = 0;
1979 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
1980 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07001981 // Also turn on CheckJNI for debuggable apps. It's quite
1982 // awkward to turn on otherwise.
1983 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08001985 // Run the app in safe mode if its manifest requests so or the
1986 // system is booted in safe mode.
1987 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
1988 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08001989 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
1990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
1992 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
1993 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07001994 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
1995 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
1996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 if ("1".equals(SystemProperties.get("debug.assert"))) {
1998 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
1999 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002000
2001 // Start the process. It will either succeed and return a result containing
2002 // the PID of the new process, or else throw a RuntimeException.
2003 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002004 app.processName, uid, uid, gids, debugFlags,
2005 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2008 synchronized (bs) {
2009 if (bs.isOnBattery()) {
2010 app.batteryStats.incStartsLocked();
2011 }
2012 }
2013
Jeff Brown3f9dd282011-07-08 20:02:19 -07002014 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 app.processName, hostingType,
2016 hostingNameStr != null ? hostingNameStr : "");
2017
2018 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002019 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 }
2021
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002022 StringBuilder buf = mStringBuilder;
2023 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 buf.append("Start proc ");
2025 buf.append(app.processName);
2026 buf.append(" for ");
2027 buf.append(hostingType);
2028 if (hostingNameStr != null) {
2029 buf.append(" ");
2030 buf.append(hostingNameStr);
2031 }
2032 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002033 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 buf.append(" uid=");
2035 buf.append(uid);
2036 buf.append(" gids={");
2037 if (gids != null) {
2038 for (int gi=0; gi<gids.length; gi++) {
2039 if (gi != 0) buf.append(", ");
2040 buf.append(gids[gi]);
2041
2042 }
2043 }
2044 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002045 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002046 app.pid = startResult.pid;
2047 app.usingWrapper = startResult.usingWrapper;
2048 app.removed = false;
2049 synchronized (mPidsSelfLocked) {
2050 this.mPidsSelfLocked.put(startResult.pid, app);
2051 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2052 msg.obj = app;
2053 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2054 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056 } catch (RuntimeException e) {
2057 // XXX do better error recovery.
2058 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002059 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002063 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 if (resumed) {
2065 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2066 } else {
2067 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2068 }
2069 }
2070
Amith Yamasani742a6712011-05-04 14:49:28 -07002071 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002072 if (mHeadless) {
2073 // Added because none of the other calls to ensureBootCompleted seem to fire
2074 // when running headless.
2075 ensureBootCompleted();
2076 return false;
2077 }
2078
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002079 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2080 && mTopAction == null) {
2081 // We are running in factory test mode, but unable to find
2082 // the factory test app, so just sit around displaying the
2083 // error message and don't try to start anything.
2084 return false;
2085 }
2086 Intent intent = new Intent(
2087 mTopAction,
2088 mTopData != null ? Uri.parse(mTopData) : null);
2089 intent.setComponent(mTopComponent);
2090 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2091 intent.addCategory(Intent.CATEGORY_HOME);
2092 }
2093 ActivityInfo aInfo =
2094 intent.resolveActivityInfo(mContext.getPackageManager(),
2095 STOCK_PM_FLAGS);
2096 if (aInfo != null) {
2097 intent.setComponent(new ComponentName(
2098 aInfo.applicationInfo.packageName, aInfo.name));
2099 // Don't do this if the home app is currently being
2100 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002101 aInfo = new ActivityInfo(aInfo);
2102 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002103 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2104 aInfo.applicationInfo.uid);
2105 if (app == null || app.instrumentationClass == null) {
2106 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002107 mMainStack.startActivityLocked(null, intent, null, aInfo,
2108 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002109 }
2110 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002111
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002112 return true;
2113 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002114
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002115 /**
2116 * Starts the "new version setup screen" if appropriate.
2117 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002118 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002119 // Only do this once per boot.
2120 if (mCheckedForSetup) {
2121 return;
2122 }
2123
2124 // We will show this screen if the current one is a different
2125 // version than the last one shown, and we are not running in
2126 // low-level factory test mode.
2127 final ContentResolver resolver = mContext.getContentResolver();
2128 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2129 Settings.Secure.getInt(resolver,
2130 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2131 mCheckedForSetup = true;
2132
2133 // See if we should be showing the platform update setup UI.
2134 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2135 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2136 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2137
2138 // We don't allow third party apps to replace this.
2139 ResolveInfo ri = null;
2140 for (int i=0; ris != null && i<ris.size(); i++) {
2141 if ((ris.get(i).activityInfo.applicationInfo.flags
2142 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2143 ri = ris.get(i);
2144 break;
2145 }
2146 }
2147
2148 if (ri != null) {
2149 String vers = ri.activityInfo.metaData != null
2150 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2151 : null;
2152 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2153 vers = ri.activityInfo.applicationInfo.metaData.getString(
2154 Intent.METADATA_SETUP_VERSION);
2155 }
2156 String lastVers = Settings.Secure.getString(
2157 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2158 if (vers != null && !vers.equals(lastVers)) {
2159 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2160 intent.setComponent(new ComponentName(
2161 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002162 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2163 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002164 }
2165 }
2166 }
2167 }
2168
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002169 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002170 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002171 }
2172
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002173 void enforceNotIsolatedCaller(String caller) {
2174 if (UserId.isIsolated(Binder.getCallingUid())) {
2175 throw new SecurityException("Isolated process not allowed to call " + caller);
2176 }
2177 }
2178
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002179 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002180 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002181 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002182 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2183 }
2184 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002185
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002186 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002187 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2188 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002189 synchronized (this) {
2190 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2191 }
2192 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002193
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002194 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002195 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002196 synchronized (this) {
2197 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2198 }
2199 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002200
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002201 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002202 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2203 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002204 synchronized (this) {
2205 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002206 }
2207 }
2208
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002209 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002210 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002211 synchronized (this) {
2212 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2213 }
2214 }
2215
2216 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002217 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2218 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002219 synchronized (this) {
2220 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2221 }
2222 }
2223
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002224 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002225 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002226
2227 final int identHash = System.identityHashCode(r);
2228 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230
Jeff Sharkeya4620792011-05-20 15:29:23 -07002231 private void dispatchForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
2232 int i = mProcessObservers.beginBroadcast();
2233 while (i > 0) {
2234 i--;
2235 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2236 if (observer != null) {
2237 try {
2238 observer.onForegroundActivitiesChanged(pid, uid, foregroundActivities);
2239 } catch (RemoteException e) {
2240 }
2241 }
2242 }
2243 mProcessObservers.finishBroadcast();
2244 }
2245
2246 private void dispatchProcessDied(int pid, int uid) {
2247 int i = mProcessObservers.beginBroadcast();
2248 while (i > 0) {
2249 i--;
2250 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2251 if (observer != null) {
2252 try {
2253 observer.onProcessDied(pid, uid);
2254 } catch (RemoteException e) {
2255 }
2256 }
2257 }
2258 mProcessObservers.finishBroadcast();
2259 }
2260
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002262 final int N = mPendingActivityLaunches.size();
2263 if (N <= 0) {
2264 return;
2265 }
2266 for (int i=0; i<N; i++) {
2267 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002268 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002269 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002270 }
2271 mPendingActivityLaunches.clear();
2272 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002273
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002274 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002275 Intent intent, String resolvedType, IBinder resultTo,
2276 String resultWho, int requestCode, int startFlags,
2277 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002278 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002279 int userId = 0;
2280 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2281 // Requesting home, set the identity to the current user
2282 // HACK!
2283 userId = mCurrentUserId;
2284 } else {
2285 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2286 // the current user's userId
2287 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2288 userId = 0;
2289 } else {
2290 userId = Binder.getOrigCallingUser();
2291 }
2292 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002293 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002294 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2295 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002296 }
2297
2298 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002299 Intent intent, String resolvedType, IBinder resultTo,
2300 String resultWho, int requestCode, int startFlags, String profileFile,
2301 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002302 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002303 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002304 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002305 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002306 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2307 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002308 return res;
2309 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002310
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002311 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002312 Intent intent, String resolvedType, IBinder resultTo,
2313 String resultWho, int requestCode, int startFlags, Configuration config,
2314 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002315 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002316 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002317 resultTo, resultWho, requestCode, startFlags,
2318 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002319 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002320 }
2321
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002322 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002323 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002324 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002325 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002326 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002327 // Refuse possible leaked file descriptors
2328 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2329 throw new IllegalArgumentException("File descriptors passed in Intent");
2330 }
2331
2332 IIntentSender sender = intent.getTarget();
2333 if (!(sender instanceof PendingIntentRecord)) {
2334 throw new IllegalArgumentException("Bad PendingIntent object");
2335 }
2336
2337 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002338
2339 synchronized (this) {
2340 // If this is coming from the currently resumed activity, it is
2341 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002342 if (mMainStack.mResumedActivity != null
2343 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002344 Binder.getCallingUid()) {
2345 mAppSwitchesAllowedTime = 0;
2346 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002347 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002348 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2349 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002350 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002351 }
2352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002354 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 // Refuse possible leaked file descriptors
2356 if (intent != null && intent.hasFileDescriptors() == true) {
2357 throw new IllegalArgumentException("File descriptors passed in Intent");
2358 }
2359
2360 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002361 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2362 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002363 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002364 return false;
2365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 if (r.app == null || r.app.thread == null) {
2367 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002368 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 return false;
2370 }
2371 intent = new Intent(intent);
2372 // The caller is not allowed to change the data.
2373 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2374 // And we are resetting to find the next component...
2375 intent.setComponent(null);
2376
2377 ActivityInfo aInfo = null;
2378 try {
2379 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002380 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002382 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2383 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384
2385 // Look for the original activity in the list...
2386 final int N = resolves != null ? resolves.size() : 0;
2387 for (int i=0; i<N; i++) {
2388 ResolveInfo rInfo = resolves.get(i);
2389 if (rInfo.activityInfo.packageName.equals(r.packageName)
2390 && rInfo.activityInfo.name.equals(r.info.name)) {
2391 // We found the current one... the next matching is
2392 // after it.
2393 i++;
2394 if (i<N) {
2395 aInfo = resolves.get(i).activityInfo;
2396 }
2397 break;
2398 }
2399 }
2400 } catch (RemoteException e) {
2401 }
2402
2403 if (aInfo == null) {
2404 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002405 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 return false;
2407 }
2408
2409 intent.setComponent(new ComponentName(
2410 aInfo.applicationInfo.packageName, aInfo.name));
2411 intent.setFlags(intent.getFlags()&~(
2412 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2413 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2414 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2415 Intent.FLAG_ACTIVITY_NEW_TASK));
2416
2417 // Okay now we need to start the new activity, replacing the
2418 // currently running activity. This is a little tricky because
2419 // we want to start the new one as if the current one is finished,
2420 // but not finish the current one first so that there is no flicker.
2421 // And thus...
2422 final boolean wasFinishing = r.finishing;
2423 r.finishing = true;
2424
2425 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002426 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 final String resultWho = r.resultWho;
2428 final int requestCode = r.requestCode;
2429 r.resultTo = null;
2430 if (resultTo != null) {
2431 resultTo.removeResultsLocked(r, resultWho, requestCode);
2432 }
2433
2434 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002435 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002436 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2437 resultWho, requestCode, -1, r.launchedFromUid, 0,
2438 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 Binder.restoreCallingIdentity(origId);
2440
2441 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002442 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 return false;
2444 }
2445 return true;
2446 }
2447 }
2448
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002449 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002451 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002452
2453 // This is so super not safe, that only the system (or okay root)
2454 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002455 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002456 final int callingUid = Binder.getCallingUid();
2457 if (callingUid != 0 && callingUid != Process.myUid()) {
2458 throw new SecurityException(
2459 "startActivityInPackage only available to the system");
2460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461
Amith Yamasani742a6712011-05-04 14:49:28 -07002462 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 resultTo, resultWho, requestCode, startFlags,
2464 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002465 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002466 }
2467
2468 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002470 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002471 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002473 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002474 }
2475
2476 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2478 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002479
2480 // This is so super not safe, that only the system (or okay root)
2481 // can do it.
2482 final int callingUid = Binder.getCallingUid();
2483 if (callingUid != 0 && callingUid != Process.myUid()) {
2484 throw new SecurityException(
2485 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002487 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002488 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002489 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002494 // Quick case: check if the top-most recent task is the same.
2495 if (N > 0 && mRecentTasks.get(0) == task) {
2496 return;
2497 }
2498 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 for (int i=0; i<N; i++) {
2500 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002501 if (task.userId == tr.userId
2502 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2503 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 mRecentTasks.remove(i);
2505 i--;
2506 N--;
2507 if (task.intent == null) {
2508 // If the new recent task we are adding is not fully
2509 // specified, then replace it with the existing recent task.
2510 task = tr;
2511 }
2512 }
2513 }
2514 if (N >= MAX_RECENT_TASKS) {
2515 mRecentTasks.remove(N-1);
2516 }
2517 mRecentTasks.add(0, task);
2518 }
2519
2520 public void setRequestedOrientation(IBinder token,
2521 int requestedOrientation) {
2522 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002523 ActivityRecord r = mMainStack.isInStackLocked(token);
2524 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 return;
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002528 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002530 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002531 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 if (config != null) {
2533 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002534 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002535 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 }
2537 }
2538 Binder.restoreCallingIdentity(origId);
2539 }
2540 }
2541
2542 public int getRequestedOrientation(IBinder token) {
2543 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002544 ActivityRecord r = mMainStack.isInStackLocked(token);
2545 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2547 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002548 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 }
2550 }
2551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 /**
2553 * This is the internal entry point for handling Activity.finish().
2554 *
2555 * @param token The Binder token referencing the Activity we want to finish.
2556 * @param resultCode Result code, if any, from this Activity.
2557 * @param resultData Result data (Intent), if any, from this Activity.
2558 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002559 * @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 -08002560 */
2561 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2562 // Refuse possible leaked file descriptors
2563 if (resultData != null && resultData.hasFileDescriptors() == true) {
2564 throw new IllegalArgumentException("File descriptors passed in Intent");
2565 }
2566
2567 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002568 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 if (next != null) {
2572 // ask watcher if this is allowed
2573 boolean resumeOK = true;
2574 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002575 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002577 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579
2580 if (!resumeOK) {
2581 return false;
2582 }
2583 }
2584 }
2585 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 resultData, "app-request");
2588 Binder.restoreCallingIdentity(origId);
2589 return res;
2590 }
2591 }
2592
Dianne Hackborn860755f2010-06-03 18:47:52 -07002593 public final void finishHeavyWeightApp() {
2594 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2595 != PackageManager.PERMISSION_GRANTED) {
2596 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2597 + Binder.getCallingPid()
2598 + ", uid=" + Binder.getCallingUid()
2599 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2600 Slog.w(TAG, msg);
2601 throw new SecurityException(msg);
2602 }
2603
2604 synchronized(this) {
2605 if (mHeavyWeightProcess == null) {
2606 return;
2607 }
2608
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002609 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002610 mHeavyWeightProcess.activities);
2611 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002612 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002613 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002614 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002615 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002617 null, "finish-heavy");
2618 }
2619 }
2620 }
2621
2622 mHeavyWeightProcess = null;
2623 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2624 }
2625 }
2626
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002627 public void crashApplication(int uid, int initialPid, String packageName,
2628 String message) {
2629 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2630 != PackageManager.PERMISSION_GRANTED) {
2631 String msg = "Permission Denial: crashApplication() from pid="
2632 + Binder.getCallingPid()
2633 + ", uid=" + Binder.getCallingUid()
2634 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2635 Slog.w(TAG, msg);
2636 throw new SecurityException(msg);
2637 }
2638
2639 synchronized(this) {
2640 ProcessRecord proc = null;
2641
2642 // Figure out which process to kill. We don't trust that initialPid
2643 // still has any relation to current pids, so must scan through the
2644 // list.
2645 synchronized (mPidsSelfLocked) {
2646 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2647 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002648 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002649 continue;
2650 }
2651 if (p.pid == initialPid) {
2652 proc = p;
2653 break;
2654 }
2655 for (String str : p.pkgList) {
2656 if (str.equals(packageName)) {
2657 proc = p;
2658 }
2659 }
2660 }
2661 }
2662
2663 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002664 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002665 + " initialPid=" + initialPid
2666 + " packageName=" + packageName);
2667 return;
2668 }
2669
2670 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002671 if (proc.pid == Process.myPid()) {
2672 Log.w(TAG, "crashApplication: trying to crash self!");
2673 return;
2674 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002675 long ident = Binder.clearCallingIdentity();
2676 try {
2677 proc.thread.scheduleCrash(message);
2678 } catch (RemoteException e) {
2679 }
2680 Binder.restoreCallingIdentity(ident);
2681 }
2682 }
2683 }
2684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 public final void finishSubActivity(IBinder token, String resultWho,
2686 int requestCode) {
2687 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002688 ActivityRecord self = mMainStack.isInStackLocked(token);
2689 if (self == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 return;
2691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692
2693 final long origId = Binder.clearCallingIdentity();
2694
2695 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002696 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2697 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002698 if (r.resultTo == self && r.requestCode == requestCode) {
2699 if ((r.resultWho == null && resultWho == null) ||
2700 (r.resultWho != null && r.resultWho.equals(resultWho))) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002701 mMainStack.finishActivityLocked(r, i,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 Activity.RESULT_CANCELED, null, "request-sub");
2703 }
2704 }
2705 }
2706
2707 Binder.restoreCallingIdentity(origId);
2708 }
2709 }
2710
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002711 public boolean willActivityBeVisible(IBinder token) {
2712 synchronized(this) {
2713 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002714 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2715 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002716 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002717 return true;
2718 }
2719 if (r.fullscreen && !r.finishing) {
2720 return false;
2721 }
2722 }
2723 return true;
2724 }
2725 }
2726
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002727 public void overridePendingTransition(IBinder token, String packageName,
2728 int enterAnim, int exitAnim) {
2729 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002730 ActivityRecord self = mMainStack.isInStackLocked(token);
2731 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002732 return;
2733 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002734
2735 final long origId = Binder.clearCallingIdentity();
2736
2737 if (self.state == ActivityState.RESUMED
2738 || self.state == ActivityState.PAUSING) {
2739 mWindowManager.overridePendingAppTransition(packageName,
2740 enterAnim, exitAnim);
2741 }
2742
2743 Binder.restoreCallingIdentity(origId);
2744 }
2745 }
2746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002747 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 * Main function for removing an existing process from the activity manager
2749 * as a result of that process going away. Clears out all connections
2750 * to the process.
2751 */
2752 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002753 boolean restarting, boolean allowRestart) {
2754 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002756 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002757 }
2758
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002759 if (mProfileProc == app) {
2760 clearProfilerLocked();
2761 }
2762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002764 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2765 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2766 mMainStack.mPausingActivity = null;
2767 }
2768 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2769 mMainStack.mLastPausedActivity = null;
2770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771
2772 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774
2775 boolean atTop = true;
2776 boolean hasVisibleActivities = false;
2777
2778 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002779 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002780 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 TAG, "Removing app " + app + " from history with " + i + " entries");
2782 while (i > 0) {
2783 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002784 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002785 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2787 if (r.app == app) {
2788 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002789 if (ActivityStack.DEBUG_ADD_REMOVE) {
2790 RuntimeException here = new RuntimeException("here");
2791 here.fillInStackTrace();
2792 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2793 + ": haveState=" + r.haveState
2794 + " stateNotNeeded=" + r.stateNotNeeded
2795 + " finishing=" + r.finishing
2796 + " state=" + r.state, here);
2797 }
2798 if (!r.finishing) {
2799 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002800 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2801 System.identityHashCode(r),
2802 r.task.taskId, r.shortComponentName,
2803 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002804 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002805 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806
2807 } else {
2808 // We have the current state for this activity, so
2809 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002810 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 TAG, "Keeping entry, setting app to null");
2812 if (r.visible) {
2813 hasVisibleActivities = true;
2814 }
2815 r.app = null;
2816 r.nowVisible = false;
2817 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002818 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2819 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 r.icicle = null;
2821 }
2822 }
2823
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002824 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826 atTop = false;
2827 }
2828
2829 app.activities.clear();
2830
2831 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002832 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 + " running instrumentation " + app.instrumentationClass);
2834 Bundle info = new Bundle();
2835 info.putString("shortMsg", "Process crashed.");
2836 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2837 }
2838
2839 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 // If there was nothing to resume, and we are not already
2842 // restarting this process, but there is a visible activity that
2843 // is hosted by the process... then make sure all visible
2844 // activities are running, taking care of restarting this
2845 // process.
2846 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 }
2849 }
2850 }
2851 }
2852
2853 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2854 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002856 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2857 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2859 return i;
2860 }
2861 }
2862 return -1;
2863 }
2864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002865 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 IApplicationThread thread) {
2867 if (thread == null) {
2868 return null;
2869 }
2870
2871 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002872 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 }
2874
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002875 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 IApplicationThread thread) {
2877
2878 mProcDeaths[0]++;
2879
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002880 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2881 synchronized (stats) {
2882 stats.noteProcessDiedLocked(app.info.uid, pid);
2883 }
2884
Magnus Edlund7bb25812010-02-24 15:45:06 +01002885 // Clean up already done if the process has been re-started.
2886 if (app.pid == pid && app.thread != null &&
2887 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002888 if (!app.killedBackground) {
2889 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2890 + ") has died.");
2891 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002892 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002893 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002894 TAG, "Dying app: " + app + ", pid: " + pid
2895 + ", thread: " + thread.asBinder());
2896 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002897 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002898
2899 if (doLowMem) {
2900 // If there are no longer any background processes running,
2901 // and the app that died was not running instrumentation,
2902 // then tell everyone we are now low on memory.
2903 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002904 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2905 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002906 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 haveBg = true;
2908 break;
2909 }
2910 }
2911
2912 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002913 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002914 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002915 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2916 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002917 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002918 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2919 // The low memory report is overriding any current
2920 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002921 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002922 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002923 rec.lastRequestedGc = 0;
2924 } else {
2925 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002927 rec.reportLowMemory = true;
2928 rec.lastLowMemory = now;
2929 mProcessesToGc.remove(rec);
2930 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07002933 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002934 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
2936 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01002937 } else if (app.pid != pid) {
2938 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002939 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01002940 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08002941 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08002942 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002943 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 + thread.asBinder());
2945 }
2946 }
2947
Dan Egnor42471dd2010-01-07 17:25:22 -08002948 /**
2949 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07002950 * @param clearTraces causes the dump file to be erased prior to the new
2951 * traces being written, if true; when false, the new traces will be
2952 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002953 * @param firstPids of dalvik VM processes to dump stack traces for first
2954 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08002955 * @return file containing stack traces, or null if no dump file is configured
2956 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002957 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
2958 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002959 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
2960 if (tracesPath == null || tracesPath.length() == 0) {
2961 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
Dan Egnor42471dd2010-01-07 17:25:22 -08002963
2964 File tracesFile = new File(tracesPath);
2965 try {
2966 File tracesDir = tracesFile.getParentFile();
2967 if (!tracesDir.exists()) tracesFile.mkdirs();
2968 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
2969
Christopher Tate6ee412d2010-05-28 12:01:56 -07002970 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08002971 tracesFile.createNewFile();
2972 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
2973 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002974 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08002975 return null;
2976 }
2977
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002978 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
2979 return tracesFile;
2980 }
2981
2982 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
2983 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08002984 // Use a FileObserver to detect when traces finish writing.
2985 // The order of traces is considered important to maintain for legibility.
2986 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
2987 public synchronized void onEvent(int event, String path) { notify(); }
2988 };
2989
2990 try {
2991 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07002992
2993 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07002994 if (firstPids != null) {
2995 try {
2996 int num = firstPids.size();
2997 for (int i = 0; i < num; i++) {
2998 synchronized (observer) {
2999 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3000 observer.wait(200); // Wait for write-close, give up after 200msec
3001 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003002 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003003 } catch (InterruptedException e) {
3004 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003005 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003006 }
3007
3008 // Next measure CPU usage.
3009 if (processStats != null) {
3010 processStats.init();
3011 System.gc();
3012 processStats.update();
3013 try {
3014 synchronized (processStats) {
3015 processStats.wait(500); // measure over 1/2 second.
3016 }
3017 } catch (InterruptedException e) {
3018 }
3019 processStats.update();
3020
3021 // We'll take the stack crawls of just the top apps using CPU.
3022 final int N = processStats.countWorkingStats();
3023 int numProcs = 0;
3024 for (int i=0; i<N && numProcs<5; i++) {
3025 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3026 if (lastPids.indexOfKey(stats.pid) >= 0) {
3027 numProcs++;
3028 try {
3029 synchronized (observer) {
3030 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3031 observer.wait(200); // Wait for write-close, give up after 200msec
3032 }
3033 } catch (InterruptedException e) {
3034 Log.wtf(TAG, e);
3035 }
3036
3037 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003038 }
3039 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003040
Dan Egnor42471dd2010-01-07 17:25:22 -08003041 } finally {
3042 observer.stopWatching();
3043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003044 }
3045
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003046 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003047 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003048 return;
3049 }
3050 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3051 if (tracesPath == null || tracesPath.length() == 0) {
3052 return;
3053 }
3054
3055 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3056 StrictMode.allowThreadDiskWrites();
3057 try {
3058 final File tracesFile = new File(tracesPath);
3059 final File tracesDir = tracesFile.getParentFile();
3060 final File tracesTmp = new File(tracesDir, "__tmp__");
3061 try {
3062 if (!tracesDir.exists()) tracesFile.mkdirs();
3063 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3064
3065 if (tracesFile.exists()) {
3066 tracesTmp.delete();
3067 tracesFile.renameTo(tracesTmp);
3068 }
3069 StringBuilder sb = new StringBuilder();
3070 Time tobj = new Time();
3071 tobj.set(System.currentTimeMillis());
3072 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3073 sb.append(": ");
3074 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3075 sb.append(" since ");
3076 sb.append(msg);
3077 FileOutputStream fos = new FileOutputStream(tracesFile);
3078 fos.write(sb.toString().getBytes());
3079 if (app == null) {
3080 fos.write("\n*** No application process!".getBytes());
3081 }
3082 fos.close();
3083 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3084 } catch (IOException e) {
3085 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3086 return;
3087 }
3088
3089 if (app != null) {
3090 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3091 firstPids.add(app.pid);
3092 dumpStackTraces(tracesPath, firstPids, null, null);
3093 }
3094
3095 File lastTracesFile = null;
3096 File curTracesFile = null;
3097 for (int i=9; i>=0; i--) {
3098 String name = String.format("slow%02d.txt", i);
3099 curTracesFile = new File(tracesDir, name);
3100 if (curTracesFile.exists()) {
3101 if (lastTracesFile != null) {
3102 curTracesFile.renameTo(lastTracesFile);
3103 } else {
3104 curTracesFile.delete();
3105 }
3106 }
3107 lastTracesFile = curTracesFile;
3108 }
3109 tracesFile.renameTo(curTracesFile);
3110 if (tracesTmp.exists()) {
3111 tracesTmp.renameTo(tracesFile);
3112 }
3113 } finally {
3114 StrictMode.setThreadPolicy(oldPolicy);
3115 }
3116 }
3117
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003118 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3119 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003120 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3121 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3122
Dianne Hackborn287952c2010-09-22 22:34:31 -07003123 if (mController != null) {
3124 try {
3125 // 0 == continue, -1 = kill process immediately
3126 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3127 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3128 } catch (RemoteException e) {
3129 mController = null;
3130 }
3131 }
3132
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003133 long anrTime = SystemClock.uptimeMillis();
3134 if (MONITOR_CPU_USAGE) {
3135 updateCpuStatsNow();
3136 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003137
3138 synchronized (this) {
3139 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3140 if (mShuttingDown) {
3141 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3142 return;
3143 } else if (app.notResponding) {
3144 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3145 return;
3146 } else if (app.crashing) {
3147 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3148 return;
3149 }
3150
3151 // In case we come through here for the same app before completing
3152 // this one, mark as anring now so we will bail out.
3153 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003154
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003155 // Log the ANR to the event log.
3156 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3157 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003158
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003159 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003160 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003161
3162 int parentPid = app.pid;
3163 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003164 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003165
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003166 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003167
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003168 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3169 ProcessRecord r = mLruProcesses.get(i);
3170 if (r != null && r.thread != null) {
3171 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003172 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3173 if (r.persistent) {
3174 firstPids.add(pid);
3175 } else {
3176 lastPids.put(pid, Boolean.TRUE);
3177 }
3178 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
3181 }
3182
Dan Egnor42471dd2010-01-07 17:25:22 -08003183 // Log the ANR to the main log.
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003184 StringBuilder info = mStringBuilder;
3185 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003186 info.append("ANR in ").append(app.processName);
3187 if (activity != null && activity.shortComponentName != null) {
3188 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003189 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003190 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003192 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003194 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003195 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197
Dianne Hackborn287952c2010-09-22 22:34:31 -07003198 final ProcessStats processStats = new ProcessStats(true);
3199
3200 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3201
Dan Egnor42471dd2010-01-07 17:25:22 -08003202 String cpuInfo = null;
3203 if (MONITOR_CPU_USAGE) {
3204 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003205 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003206 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003207 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003208 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003209 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003212 info.append(processStats.printCurrentState(anrTime));
3213
Joe Onorato8a9b2202010-02-26 18:56:32 -08003214 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003215 if (tracesFile == null) {
3216 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3217 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3218 }
3219
Jeff Sharkeya353d262011-10-28 11:12:06 -07003220 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3221 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003222
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003223 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003225 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3226 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003228 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3229 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003232 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 }
3234 }
3235
Dan Egnor42471dd2010-01-07 17:25:22 -08003236 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3237 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3238 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003239
3240 synchronized (this) {
3241 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003242 Slog.w(TAG, "Killing " + app + ": background ANR");
3243 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3244 app.processName, app.setAdj, "background ANR");
3245 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246 return;
3247 }
3248
3249 // Set the app's notResponding state, and look up the errorReportReceiver
3250 makeAppNotRespondingLocked(app,
3251 activity != null ? activity.shortComponentName : null,
3252 annotation != null ? "ANR " + annotation : "ANR",
3253 info.toString());
3254
3255 // Bring up the infamous App Not Responding dialog
3256 Message msg = Message.obtain();
3257 HashMap map = new HashMap();
3258 msg.what = SHOW_NOT_RESPONDING_MSG;
3259 msg.obj = map;
3260 map.put("app", app);
3261 if (activity != null) {
3262 map.put("activity", activity);
3263 }
3264
3265 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 }
3268
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003269 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3270 if (!mLaunchWarningShown) {
3271 mLaunchWarningShown = true;
3272 mHandler.post(new Runnable() {
3273 @Override
3274 public void run() {
3275 synchronized (ActivityManagerService.this) {
3276 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3277 d.show();
3278 mHandler.postDelayed(new Runnable() {
3279 @Override
3280 public void run() {
3281 synchronized (ActivityManagerService.this) {
3282 d.dismiss();
3283 mLaunchWarningShown = false;
3284 }
3285 }
3286 }, 4000);
3287 }
3288 }
3289 });
3290 }
3291 }
3292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003294 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003295 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 int uid = Binder.getCallingUid();
3297 int pid = Binder.getCallingPid();
3298 long callingId = Binder.clearCallingIdentity();
3299 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003300 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 int pkgUid = -1;
3302 synchronized(this) {
3303 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003304 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 } catch (RemoteException e) {
3306 }
3307 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003308 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 return false;
3310 }
3311 if (uid == pkgUid || checkComponentPermission(
3312 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003313 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003315 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 } else {
3317 throw new SecurityException(pid+" does not have permission:"+
3318 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3319 "for process:"+packageName);
3320 }
3321 }
3322
3323 try {
3324 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003325 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3327 Uri.fromParts("package", packageName, null));
3328 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003329 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003330 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 } catch (RemoteException e) {
3332 }
3333 } finally {
3334 Binder.restoreCallingIdentity(callingId);
3335 }
3336 return true;
3337 }
3338
Dianne Hackborn03abb812010-01-04 18:43:19 -08003339 public void killBackgroundProcesses(final String packageName) {
3340 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3341 != PackageManager.PERMISSION_GRANTED &&
3342 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3343 != PackageManager.PERMISSION_GRANTED) {
3344 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 + Binder.getCallingPid()
3346 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003347 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003348 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 throw new SecurityException(msg);
3350 }
3351
Amith Yamasani483f3b02012-03-13 16:08:00 -07003352 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 long callingId = Binder.clearCallingIdentity();
3354 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003355 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 int pkgUid = -1;
3357 synchronized(this) {
3358 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003359 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 } catch (RemoteException e) {
3361 }
3362 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003363 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 return;
3365 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003366 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003367 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3368 }
3369 } finally {
3370 Binder.restoreCallingIdentity(callingId);
3371 }
3372 }
3373
3374 public void killAllBackgroundProcesses() {
3375 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3376 != PackageManager.PERMISSION_GRANTED) {
3377 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3378 + Binder.getCallingPid()
3379 + ", uid=" + Binder.getCallingUid()
3380 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3381 Slog.w(TAG, msg);
3382 throw new SecurityException(msg);
3383 }
3384
3385 long callingId = Binder.clearCallingIdentity();
3386 try {
3387 synchronized(this) {
3388 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3389 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3390 final int NA = apps.size();
3391 for (int ia=0; ia<NA; ia++) {
3392 ProcessRecord app = apps.valueAt(ia);
3393 if (app.persistent) {
3394 // we don't kill persistent processes
3395 continue;
3396 }
3397 if (app.removed) {
3398 procs.add(app);
3399 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3400 app.removed = true;
3401 procs.add(app);
3402 }
3403 }
3404 }
3405
3406 int N = procs.size();
3407 for (int i=0; i<N; i++) {
3408 removeProcessLocked(procs.get(i), false, true, "kill all background");
3409 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003410 }
3411 } finally {
3412 Binder.restoreCallingIdentity(callingId);
3413 }
3414 }
3415
3416 public void forceStopPackage(final String packageName) {
3417 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3418 != PackageManager.PERMISSION_GRANTED) {
3419 String msg = "Permission Denial: forceStopPackage() from pid="
3420 + Binder.getCallingPid()
3421 + ", uid=" + Binder.getCallingUid()
3422 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003423 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003424 throw new SecurityException(msg);
3425 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003426 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003427 long callingId = Binder.clearCallingIdentity();
3428 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003429 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003430 int pkgUid = -1;
3431 synchronized(this) {
3432 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003433 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003434 } catch (RemoteException e) {
3435 }
3436 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003437 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003438 return;
3439 }
3440 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003441 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003442 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003443 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003444 } catch (IllegalArgumentException e) {
3445 Slog.w(TAG, "Failed trying to unstop package "
3446 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 }
3449 } finally {
3450 Binder.restoreCallingIdentity(callingId);
3451 }
3452 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003453
3454 /*
3455 * The pkg name and uid have to be specified.
3456 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3457 */
3458 public void killApplicationWithUid(String pkg, int uid) {
3459 if (pkg == null) {
3460 return;
3461 }
3462 // Make sure the uid is valid.
3463 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003464 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003465 return;
3466 }
3467 int callerUid = Binder.getCallingUid();
3468 // Only the system server can kill an application
3469 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003470 // Post an aysnc message to kill the application
3471 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3472 msg.arg1 = uid;
3473 msg.arg2 = 0;
3474 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003475 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003476 } else {
3477 throw new SecurityException(callerUid + " cannot kill pkg: " +
3478 pkg);
3479 }
3480 }
3481
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003482 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003483 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003484 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003485 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003486 if (reason != null) {
3487 intent.putExtra("reason", reason);
3488 }
3489
3490 final int uid = Binder.getCallingUid();
3491 final long origId = Binder.clearCallingIdentity();
3492 synchronized (this) {
Dianne Hackbornffa42482009-09-23 22:20:11 -07003493 mWindowManager.closeSystemDialogs(reason);
3494
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08003495 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003496 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornffa42482009-09-23 22:20:11 -07003497 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498 r.stack.finishActivityLocked(r, i,
Dianne Hackbornffa42482009-09-23 22:20:11 -07003499 Activity.RESULT_CANCELED, null, "close-sys");
3500 }
3501 }
3502
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003503 broadcastIntentLocked(null, null, intent, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003504 null, 0, null, null, null, false, false, -1, uid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003505 }
3506 Binder.restoreCallingIdentity(origId);
3507 }
3508
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003509 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003510 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003511 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003512 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3513 for (int i=pids.length-1; i>=0; i--) {
3514 infos[i] = new Debug.MemoryInfo();
3515 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003516 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003517 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003518 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003519
Dianne Hackbornb437e092011-08-05 17:50:29 -07003520 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003521 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003522 long[] pss = new long[pids.length];
3523 for (int i=pids.length-1; i>=0; i--) {
3524 pss[i] = Debug.getPss(pids[i]);
3525 }
3526 return pss;
3527 }
3528
Christopher Tate5e1ab332009-09-01 20:32:49 -07003529 public void killApplicationProcess(String processName, int uid) {
3530 if (processName == null) {
3531 return;
3532 }
3533
3534 int callerUid = Binder.getCallingUid();
3535 // Only the system server can kill an application
3536 if (callerUid == Process.SYSTEM_UID) {
3537 synchronized (this) {
3538 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003539 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003540 try {
3541 app.thread.scheduleSuicide();
3542 } catch (RemoteException e) {
3543 // If the other end already died, then our work here is done.
3544 }
3545 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003547 + processName + " / " + uid);
3548 }
3549 }
3550 } else {
3551 throw new SecurityException(callerUid + " cannot kill app process: " +
3552 processName);
3553 }
3554 }
3555
Dianne Hackborn03abb812010-01-04 18:43:19 -08003556 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003557 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3559 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003560 if (!mProcessesReady) {
3561 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 intent.putExtra(Intent.EXTRA_UID, uid);
3564 broadcastIntentLocked(null, null, intent,
3565 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003566 false, false,
3567 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 }
3569
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003570 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003571 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003572 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003573 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574
Dianne Hackborn03abb812010-01-04 18:43:19 -08003575 // Remove all processes this package may have touched: all with the
3576 // same UID (except for the system or root user), and all whose name
3577 // matches the package name.
3578 final String procNamePrefix = packageName + ":";
3579 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3580 final int NA = apps.size();
3581 for (int ia=0; ia<NA; ia++) {
3582 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003583 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003584 // we don't kill persistent processes
3585 continue;
3586 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003587 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003588 if (doit) {
3589 procs.add(app);
3590 }
Amith Yamasani13593602012-03-22 16:16:17 -07003591 // If uid is specified and the uid and process name match
3592 // Or, the uid is not specified and the process name matches
3593 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003594 || ((app.processName.equals(packageName)
3595 || app.processName.startsWith(procNamePrefix))
3596 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003597 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003598 if (!doit) {
3599 return true;
3600 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003601 app.removed = true;
3602 procs.add(app);
3603 }
3604 }
3605 }
3606 }
3607
3608 int N = procs.size();
3609 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003610 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003611 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003612 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003613 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003614
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003615 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003616 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003617 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003618 int i;
3619 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003621 if (uid < 0) {
3622 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003623 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 } catch (RemoteException e) {
3625 }
3626 }
3627
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003628 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003629 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003630
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003631 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3632 while (badApps.hasNext()) {
3633 SparseArray<Long> ba = badApps.next();
3634 if (ba.get(uid) != null) {
3635 badApps.remove();
3636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
3638 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003639
3640 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003641 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003643 TaskRecord lastTask = null;
3644 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003645 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003646 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003647 if (r.userId == userId
3648 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003649 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003650 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003651 if (r.finishing) {
3652 // If this activity is just finishing, then it is not
3653 // interesting as far as something to stop.
3654 continue;
3655 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003656 return true;
3657 }
3658 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003659 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003660 if (samePackage) {
3661 if (r.app != null) {
3662 r.app.removed = true;
3663 }
3664 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003666 lastTask = r.task;
3667 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003668 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003669 i--;
3670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 }
3672 }
3673
3674 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003675 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003676 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003677 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003678 if (!doit) {
3679 return true;
3680 }
3681 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003682 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 if (service.app != null) {
3684 service.app.removed = true;
3685 }
3686 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003687 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 services.add(service);
3689 }
3690 }
3691
3692 N = services.size();
3693 for (i=0; i<N; i++) {
3694 bringDownServiceLocked(services.get(i), true);
3695 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003696
3697 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003698 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003699 if (provider.info.packageName.equals(name)
3700 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3701 if (!doit) {
3702 return true;
3703 }
3704 didSomething = true;
3705 providers.add(provider);
3706 }
3707 }
3708
3709 N = providers.size();
3710 for (i=0; i<N; i++) {
3711 removeDyingProviderLocked(null, providers.get(i));
3712 }
3713
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003714 if (doit) {
3715 if (purgeCache) {
3716 AttributeCache ac = AttributeCache.instance();
3717 if (ac != null) {
3718 ac.removePackage(name);
3719 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003720 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003721 if (mBooted) {
3722 mMainStack.resumeTopActivityLocked(null);
3723 mMainStack.scheduleIdleLocked();
3724 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003725 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726
3727 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 }
3729
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003730 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003731 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003733 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003734 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003735 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003736 + "/" + uid + ")");
3737
3738 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003739 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003740 if (mHeavyWeightProcess == app) {
3741 mHeavyWeightProcess = null;
3742 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 boolean needRestart = false;
3745 if (app.pid > 0 && app.pid != MY_PID) {
3746 int pid = app.pid;
3747 synchronized (mPidsSelfLocked) {
3748 mPidsSelfLocked.remove(pid);
3749 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3750 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003751 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003752 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003753 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003754 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003756 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003758 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 } else {
3760 needRestart = true;
3761 }
3762 }
3763 } else {
3764 mRemovedProcesses.add(app);
3765 }
3766
3767 return needRestart;
3768 }
3769
3770 private final void processStartTimedOutLocked(ProcessRecord app) {
3771 final int pid = app.pid;
3772 boolean gone = false;
3773 synchronized (mPidsSelfLocked) {
3774 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3775 if (knownApp != null && knownApp.thread == null) {
3776 mPidsSelfLocked.remove(pid);
3777 gone = true;
3778 }
3779 }
3780
3781 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003782 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003783 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003784 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003785 mProcessNames.remove(app.processName, app.uid);
3786 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003787 if (mHeavyWeightProcess == app) {
3788 mHeavyWeightProcess = null;
3789 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3790 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003791 // Take care of any launching providers waiting for this process.
3792 checkAppInLaunchingProvidersLocked(app, true);
3793 // Take care of any services that are waiting for the process.
3794 for (int i=0; i<mPendingServices.size(); i++) {
3795 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003796 if ((app.uid == sr.appInfo.uid
3797 && app.processName.equals(sr.processName))
3798 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003799 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003800 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003801 mPendingServices.remove(i);
3802 i--;
3803 bringDownServiceLocked(sr, true);
3804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003806 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3807 app.processName, app.setAdj, "start timeout");
3808 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003809 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003810 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003811 try {
3812 IBackupManager bm = IBackupManager.Stub.asInterface(
3813 ServiceManager.getService(Context.BACKUP_SERVICE));
3814 bm.agentDisconnected(app.info.packageName);
3815 } catch (RemoteException e) {
3816 // Can't happen; the backup manager is local
3817 }
3818 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003819 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003820 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003821 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003824 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 }
3826 }
3827
3828 private final boolean attachApplicationLocked(IApplicationThread thread,
3829 int pid) {
3830
3831 // Find the application record that is being attached... either via
3832 // the pid if we are running in multiple processes, or just pull the
3833 // next app record if we are emulating process with anonymous threads.
3834 ProcessRecord app;
3835 if (pid != MY_PID && pid >= 0) {
3836 synchronized (mPidsSelfLocked) {
3837 app = mPidsSelfLocked.get(pid);
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 } else {
3840 app = null;
3841 }
3842
3843 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003844 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003846 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003848 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 } else {
3850 try {
3851 thread.scheduleExit();
3852 } catch (Exception e) {
3853 // Ignore exceptions.
3854 }
3855 }
3856 return false;
3857 }
3858
3859 // If this application record is still attached to a previous
3860 // process, clean it up now.
3861 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003862 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864
3865 // Tell the process all about itself.
3866
Joe Onorato8a9b2202010-02-26 18:56:32 -08003867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 TAG, "Binding process pid " + pid + " to record " + app);
3869
3870 String processName = app.processName;
3871 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003872 AppDeathRecipient adr = new AppDeathRecipient(
3873 app, pid, thread);
3874 thread.asBinder().linkToDeath(adr, 0);
3875 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 } catch (RemoteException e) {
3877 app.resetPackageList();
3878 startProcessLocked(app, "link fail", processName);
3879 return false;
3880 }
3881
Doug Zongker2bec3d42009-12-04 12:52:44 -08003882 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883
3884 app.thread = thread;
3885 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003886 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3887 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 app.forcingToForeground = null;
3889 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003890 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 app.debugging = false;
3892
3893 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3894
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003895 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003896 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003898 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003899 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003900 }
3901
Joe Onorato8a9b2202010-02-26 18:56:32 -08003902 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 TAG, "New app record " + app
3904 + " thread=" + thread.asBinder() + " pid=" + pid);
3905 try {
3906 int testMode = IApplicationThread.DEBUG_OFF;
3907 if (mDebugApp != null && mDebugApp.equals(processName)) {
3908 testMode = mWaitForDebugger
3909 ? IApplicationThread.DEBUG_WAIT
3910 : IApplicationThread.DEBUG_ON;
3911 app.debugging = true;
3912 if (mDebugTransient) {
3913 mDebugApp = mOrigDebugApp;
3914 mWaitForDebugger = mOrigWaitForDebugger;
3915 }
3916 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003917 String profileFile = app.instrumentationProfileFile;
3918 ParcelFileDescriptor profileFd = null;
3919 boolean profileAutoStop = false;
3920 if (mProfileApp != null && mProfileApp.equals(processName)) {
3921 mProfileProc = app;
3922 profileFile = mProfileFile;
3923 profileFd = mProfileFd;
3924 profileAutoStop = mAutoStopProfiler;
3925 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003926 boolean enableOpenGlTrace = false;
3927 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
3928 enableOpenGlTrace = true;
3929 mOpenGlTraceApp = null;
3930 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003931
Christopher Tate181fafa2009-05-14 11:12:14 -07003932 // If the app is being launched for restore or full backup, set it up specially
3933 boolean isRestrictedBackupMode = false;
3934 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
3935 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07003936 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07003937 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
3938 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003939
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07003940 ensurePackageDexOpt(app.instrumentationInfo != null
3941 ? app.instrumentationInfo.packageName
3942 : app.info.packageName);
3943 if (app.instrumentationClass != null) {
3944 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003945 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08003946 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07003947 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003948 ApplicationInfo appInfo = app.instrumentationInfo != null
3949 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07003950 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003951 if (profileFd != null) {
3952 profileFd = profileFd.dup();
3953 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003954 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003955 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08003956 app.instrumentationArguments, app.instrumentationWatcher, testMode,
3957 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08003958 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08003959 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003960 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003961 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 } catch (Exception e) {
3963 // todo: Yikes! What should we do? For now we will try to
3964 // start another process, but that could easily get us in
3965 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08003966 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967
3968 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003969 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 startProcessLocked(app, "bind fail", processName);
3971 return false;
3972 }
3973
3974 // Remove this record from the list of starting applications.
3975 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003976 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
3977 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 mProcessesOnHold.remove(app);
3979
3980 boolean badApp = false;
3981 boolean didSomething = false;
3982
3983 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07003985 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003986 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 && processName.equals(hr.processName)) {
3988 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07003989 if (mHeadless) {
3990 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
3991 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 didSomething = true;
3993 }
3994 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003995 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 + hr.intent.getComponent().flattenToShortString(), e);
3997 badApp = true;
3998 }
3999 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 }
4003
4004 // Find any services that should be running in this process...
4005 if (!badApp && mPendingServices.size() > 0) {
4006 ServiceRecord sr = null;
4007 try {
4008 for (int i=0; i<mPendingServices.size(); i++) {
4009 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4011 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 continue;
4013 }
4014
4015 mPendingServices.remove(i);
4016 i--;
4017 realStartServiceLocked(sr, app);
4018 didSomething = true;
4019 }
4020 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004021 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 + sr.shortName, e);
4023 badApp = true;
4024 }
4025 }
4026
Christopher Tatef46723b2012-01-26 14:19:24 -08004027 // Check if a next-broadcast receiver is in this process...
4028 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004030 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004032 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 }
4035 }
4036
Christopher Tate181fafa2009-05-14 11:12:14 -07004037 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004038 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004040 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004041 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004042 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4043 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4044 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004045 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004046 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004047 e.printStackTrace();
4048 }
4049 }
4050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (badApp) {
4052 // todo: Also need to kill application to deal with all
4053 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004054 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 return false;
4056 }
4057
4058 if (!didSomething) {
4059 updateOomAdjLocked();
4060 }
4061
4062 return true;
4063 }
4064
4065 public final void attachApplication(IApplicationThread thread) {
4066 synchronized (this) {
4067 int callingPid = Binder.getCallingPid();
4068 final long origId = Binder.clearCallingIdentity();
4069 attachApplicationLocked(thread, callingPid);
4070 Binder.restoreCallingIdentity(origId);
4071 }
4072 }
4073
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004074 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004076 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4077 if (stopProfiling) {
4078 synchronized (this) {
4079 if (mProfileProc == r.app) {
4080 if (mProfileFd != null) {
4081 try {
4082 mProfileFd.close();
4083 } catch (IOException e) {
4084 }
4085 clearProfilerLocked();
4086 }
4087 }
4088 }
4089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 Binder.restoreCallingIdentity(origId);
4091 }
4092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004094 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004095 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004096 mWindowManager.enableScreenAfterBoot();
4097 }
4098
Dianne Hackborn661cd522011-08-22 00:26:20 -07004099 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004100 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004101 mWindowManager.showBootMessage(msg, always);
4102 }
4103
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004104 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004105 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004106 synchronized (this) {
4107 mMainStack.dismissKeyguardOnNextActivityLocked();
4108 }
4109 }
4110
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004111 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004112 IntentFilter pkgFilter = new IntentFilter();
4113 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4114 pkgFilter.addDataScheme("package");
4115 mContext.registerReceiver(new BroadcastReceiver() {
4116 @Override
4117 public void onReceive(Context context, Intent intent) {
4118 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4119 if (pkgs != null) {
4120 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004121 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004122 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4123 setResultCode(Activity.RESULT_OK);
4124 return;
4125 }
4126 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004127 }
4128 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004129 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004130 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004131
4132 IntentFilter userFilter = new IntentFilter();
4133 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4134 mContext.registerReceiver(new BroadcastReceiver() {
4135 @Override
4136 public void onReceive(Context context, Intent intent) {
4137 onUserRemoved(intent);
4138 }
4139 }, userFilter);
4140
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004141 synchronized (this) {
4142 // Ensure that any processes we had put on hold are now started
4143 // up.
4144 final int NP = mProcessesOnHold.size();
4145 if (NP > 0) {
4146 ArrayList<ProcessRecord> procs =
4147 new ArrayList<ProcessRecord>(mProcessesOnHold);
4148 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004149 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4150 + procs.get(ip));
4151 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004152 }
4153 }
4154
4155 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004156 // Start looking for apps that are abusing wake locks.
4157 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004158 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004159 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004160 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004161 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004162 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004163 broadcastIntentLocked(null, null,
4164 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4165 null, null, 0, null, null,
4166 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004167 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 }
4169 }
4170 }
4171
4172 final void ensureBootCompleted() {
4173 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004174 boolean enableScreen;
4175 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004176 booting = mBooting;
4177 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004178 enableScreen = !mBooted;
4179 mBooted = true;
4180 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004181
4182 if (booting) {
4183 finishBooting();
4184 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004185
4186 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004187 enableScreenAfterBoot();
4188 }
4189 }
4190
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004191 public final void activityPaused(IBinder token) {
4192 final long origId = Binder.clearCallingIdentity();
4193 mMainStack.activityPaused(token, false);
4194 Binder.restoreCallingIdentity(origId);
4195 }
4196
4197 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4198 CharSequence description) {
4199 if (localLOGV) Slog.v(
4200 TAG, "Activity stopped: token=" + token);
4201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 // Refuse possible leaked file descriptors
4203 if (icicle != null && icicle.hasFileDescriptors()) {
4204 throw new IllegalArgumentException("File descriptors passed in Bundle");
4205 }
4206
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004207 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208
4209 final long origId = Binder.clearCallingIdentity();
4210
4211 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004212 r = mMainStack.isInStackLocked(token);
4213 if (r != null) {
4214 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 }
4216 }
4217
4218 if (r != null) {
4219 sendPendingThumbnail(r, null, null, null, false);
4220 }
4221
4222 trimApplications();
4223
4224 Binder.restoreCallingIdentity(origId);
4225 }
4226
4227 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004228 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
4231
4232 public String getCallingPackage(IBinder token) {
4233 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004234 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004235 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 }
4237 }
4238
4239 public ComponentName getCallingActivity(IBinder token) {
4240 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004241 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 return r != null ? r.intent.getComponent() : null;
4243 }
4244 }
4245
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004246 private ActivityRecord getCallingRecordLocked(IBinder token) {
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.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 }
4253
4254 public ComponentName getActivityClassForToken(IBinder token) {
4255 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004256 ActivityRecord r = mMainStack.isInStackLocked(token);
4257 if (r == null) {
4258 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004260 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004261 }
4262 }
4263
4264 public String getPackageForToken(IBinder token) {
4265 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004266 ActivityRecord r = mMainStack.isInStackLocked(token);
4267 if (r == null) {
4268 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004269 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004270 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004271 }
4272 }
4273
4274 public IIntentSender getIntentSender(int type,
4275 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004276 int requestCode, Intent[] intents, String[] resolvedTypes,
4277 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004278 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004280 if (intents != null) {
4281 if (intents.length < 1) {
4282 throw new IllegalArgumentException("Intents array length must be >= 1");
4283 }
4284 for (int i=0; i<intents.length; i++) {
4285 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004286 if (intent != null) {
4287 if (intent.hasFileDescriptors()) {
4288 throw new IllegalArgumentException("File descriptors passed in Intent");
4289 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004290 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004291 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4292 throw new IllegalArgumentException(
4293 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4294 }
4295 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004296 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004297 }
4298 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004300 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004301 }
4302 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004303 if (options != null) {
4304 if (options.hasFileDescriptors()) {
4305 throw new IllegalArgumentException("File descriptors passed in options");
4306 }
4307 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 synchronized(this) {
4310 int callingUid = Binder.getCallingUid();
4311 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004312 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004313 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004314 .getPackageUid(packageName, UserId.getUserId(callingUid));
4315 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 String msg = "Permission Denial: getIntentSender() from pid="
4317 + Binder.getCallingPid()
4318 + ", uid=" + Binder.getCallingUid()
4319 + ", (need uid=" + uid + ")"
4320 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004321 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 throw new SecurityException(msg);
4323 }
4324 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004325
Amith Yamasani742a6712011-05-04 14:49:28 -07004326 if (DEBUG_MU)
4327 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4328 + Binder.getOrigCallingUid());
4329 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004330 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 } catch (RemoteException e) {
4333 throw new SecurityException(e);
4334 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004335 }
4336 }
4337
4338 IIntentSender getIntentSenderLocked(int type,
4339 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004340 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4341 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004342 if (DEBUG_MU)
4343 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004344 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004345 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004346 activity = mMainStack.isInStackLocked(token);
4347 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004348 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004350 if (activity.finishing) {
4351 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004353 }
4354
4355 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4356 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4357 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4358 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4359 |PendingIntent.FLAG_UPDATE_CURRENT);
4360
4361 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4362 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004363 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004364 WeakReference<PendingIntentRecord> ref;
4365 ref = mIntentSenderRecords.get(key);
4366 PendingIntentRecord rec = ref != null ? ref.get() : null;
4367 if (rec != null) {
4368 if (!cancelCurrent) {
4369 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004370 if (rec.key.requestIntent != null) {
4371 rec.key.requestIntent.replaceExtras(intents != null ? intents[0] : null);
4372 }
4373 if (intents != null) {
4374 intents[intents.length-1] = rec.key.requestIntent;
4375 rec.key.allIntents = intents;
4376 rec.key.allResolvedTypes = resolvedTypes;
4377 } else {
4378 rec.key.allIntents = null;
4379 rec.key.allResolvedTypes = null;
4380 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 return rec;
4383 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004384 rec.canceled = true;
4385 mIntentSenderRecords.remove(key);
4386 }
4387 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004388 return rec;
4389 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004390 rec = new PendingIntentRecord(this, key, callingUid);
4391 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004392 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004393 if (activity.pendingResults == null) {
4394 activity.pendingResults
4395 = new HashSet<WeakReference<PendingIntentRecord>>();
4396 }
4397 activity.pendingResults.add(rec.ref);
4398 }
4399 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
4401
4402 public void cancelIntentSender(IIntentSender sender) {
4403 if (!(sender instanceof PendingIntentRecord)) {
4404 return;
4405 }
4406 synchronized(this) {
4407 PendingIntentRecord rec = (PendingIntentRecord)sender;
4408 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004409 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004410 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004411 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004412 String msg = "Permission Denial: cancelIntentSender() from pid="
4413 + Binder.getCallingPid()
4414 + ", uid=" + Binder.getCallingUid()
4415 + " is not allowed to cancel packges "
4416 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004417 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 throw new SecurityException(msg);
4419 }
4420 } catch (RemoteException e) {
4421 throw new SecurityException(e);
4422 }
4423 cancelIntentSenderLocked(rec, true);
4424 }
4425 }
4426
4427 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4428 rec.canceled = true;
4429 mIntentSenderRecords.remove(rec.key);
4430 if (cleanActivity && rec.key.activity != null) {
4431 rec.key.activity.pendingResults.remove(rec.ref);
4432 }
4433 }
4434
4435 public String getPackageForIntentSender(IIntentSender pendingResult) {
4436 if (!(pendingResult instanceof PendingIntentRecord)) {
4437 return null;
4438 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004439 try {
4440 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4441 return res.key.packageName;
4442 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 }
4444 return null;
4445 }
4446
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004447 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4448 if (!(pendingResult instanceof PendingIntentRecord)) {
4449 return false;
4450 }
4451 try {
4452 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4453 if (res.key.allIntents == null) {
4454 return false;
4455 }
4456 for (int i=0; i<res.key.allIntents.length; i++) {
4457 Intent intent = res.key.allIntents[i];
4458 if (intent.getPackage() != null && intent.getComponent() != null) {
4459 return false;
4460 }
4461 }
4462 return true;
4463 } catch (ClassCastException e) {
4464 }
4465 return false;
4466 }
4467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 public void setProcessLimit(int max) {
4469 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4470 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004471 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004472 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004473 mProcessLimitOverride = max;
4474 }
4475 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477
4478 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004479 synchronized (this) {
4480 return mProcessLimitOverride;
4481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483
4484 void foregroundTokenDied(ForegroundToken token) {
4485 synchronized (ActivityManagerService.this) {
4486 synchronized (mPidsSelfLocked) {
4487 ForegroundToken cur
4488 = mForegroundProcesses.get(token.pid);
4489 if (cur != token) {
4490 return;
4491 }
4492 mForegroundProcesses.remove(token.pid);
4493 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4494 if (pr == null) {
4495 return;
4496 }
4497 pr.forcingToForeground = null;
4498 pr.foregroundServices = false;
4499 }
4500 updateOomAdjLocked();
4501 }
4502 }
4503
4504 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4505 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4506 "setProcessForeground()");
4507 synchronized(this) {
4508 boolean changed = false;
4509
4510 synchronized (mPidsSelfLocked) {
4511 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004512 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004513 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 return;
4515 }
4516 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4517 if (oldToken != null) {
4518 oldToken.token.unlinkToDeath(oldToken, 0);
4519 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004520 if (pr != null) {
4521 pr.forcingToForeground = null;
4522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 changed = true;
4524 }
4525 if (isForeground && token != null) {
4526 ForegroundToken newToken = new ForegroundToken() {
4527 public void binderDied() {
4528 foregroundTokenDied(this);
4529 }
4530 };
4531 newToken.pid = pid;
4532 newToken.token = token;
4533 try {
4534 token.linkToDeath(newToken, 0);
4535 mForegroundProcesses.put(pid, newToken);
4536 pr.forcingToForeground = token;
4537 changed = true;
4538 } catch (RemoteException e) {
4539 // If the process died while doing this, we will later
4540 // do the cleanup with the process death link.
4541 }
4542 }
4543 }
4544
4545 if (changed) {
4546 updateOomAdjLocked();
4547 }
4548 }
4549 }
4550
4551 // =========================================================
4552 // PERMISSIONS
4553 // =========================================================
4554
4555 static class PermissionController extends IPermissionController.Stub {
4556 ActivityManagerService mActivityManagerService;
4557 PermissionController(ActivityManagerService activityManagerService) {
4558 mActivityManagerService = activityManagerService;
4559 }
4560
4561 public boolean checkPermission(String permission, int pid, int uid) {
4562 return mActivityManagerService.checkPermission(permission, pid,
4563 uid) == PackageManager.PERMISSION_GRANTED;
4564 }
4565 }
4566
4567 /**
4568 * This can be called with or without the global lock held.
4569 */
4570 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004571 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 // We might be performing an operation on behalf of an indirect binder
4573 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4574 // client identity accordingly before proceeding.
4575 Identity tlsIdentity = sCallerIdentity.get();
4576 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004577 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4579 uid = tlsIdentity.uid;
4580 pid = tlsIdentity.pid;
4581 }
4582
4583 // Root, system server and our own process get to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004584 if (uid == 0 || uid == Process.SYSTEM_UID || pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004585 return PackageManager.PERMISSION_GRANTED;
4586 }
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004587 // Isolated processes don't get any permissions.
4588 if (UserId.isIsolated(uid)) {
4589 return PackageManager.PERMISSION_DENIED;
4590 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004591 // If there is a uid that owns whatever is being accessed, it has
4592 // blanket access to it regardless of the permissions it requires.
Amith Yamasani742a6712011-05-04 14:49:28 -07004593 if (owningUid >= 0 && UserId.isSameApp(uid, owningUid)) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004594 return PackageManager.PERMISSION_GRANTED;
4595 }
4596 // If the target is not exported, then nobody else can get to it.
4597 if (!exported) {
4598 Slog.w(TAG, "Permission denied: checkComponentPermission() owningUid=" + owningUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004599 return PackageManager.PERMISSION_DENIED;
4600 }
4601 if (permission == null) {
4602 return PackageManager.PERMISSION_GRANTED;
4603 }
4604 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004605 return AppGlobals.getPackageManager()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004606 .checkUidPermission(permission, uid);
4607 } catch (RemoteException e) {
4608 // Should never happen, but if it does... deny!
Joe Onorato8a9b2202010-02-26 18:56:32 -08004609 Slog.e(TAG, "PackageManager is dead?!?", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004610 }
4611 return PackageManager.PERMISSION_DENIED;
4612 }
4613
4614 /**
4615 * As the only public entry point for permissions checking, this method
4616 * can enforce the semantic that requesting a check on a null global
4617 * permission is automatically denied. (Internally a null permission
4618 * string is used when calling {@link #checkComponentPermission} in cases
4619 * when only uid-based security is needed.)
4620 *
4621 * This can be called with or without the global lock held.
4622 */
4623 public int checkPermission(String permission, int pid, int uid) {
4624 if (permission == null) {
4625 return PackageManager.PERMISSION_DENIED;
4626 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004627 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
4629
4630 /**
4631 * Binder IPC calls go through the public entry point.
4632 * This can be called with or without the global lock held.
4633 */
4634 int checkCallingPermission(String permission) {
4635 return checkPermission(permission,
4636 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004637 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004638 }
4639
4640 /**
4641 * This can be called with or without the global lock held.
4642 */
4643 void enforceCallingPermission(String permission, String func) {
4644 if (checkCallingPermission(permission)
4645 == PackageManager.PERMISSION_GRANTED) {
4646 return;
4647 }
4648
4649 String msg = "Permission Denial: " + func + " from pid="
4650 + Binder.getCallingPid()
4651 + ", uid=" + Binder.getCallingUid()
4652 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004653 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 throw new SecurityException(msg);
4655 }
4656
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004657 /**
4658 * Determine if UID is holding permissions required to access {@link Uri} in
4659 * the given {@link ProviderInfo}. Final permission checking is always done
4660 * in {@link ContentProvider}.
4661 */
4662 private final boolean checkHoldingPermissionsLocked(
4663 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004664 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4665 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004666
4667 if (pi.applicationInfo.uid == uid) {
4668 return true;
4669 } else if (!pi.exported) {
4670 return false;
4671 }
4672
4673 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4674 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004675 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004676 // check if target holds top-level <provider> permissions
4677 if (!readMet && pi.readPermission != null
4678 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4679 readMet = true;
4680 }
4681 if (!writeMet && pi.writePermission != null
4682 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4683 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004684 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004685
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004686 // track if unprotected read/write is allowed; any denied
4687 // <path-permission> below removes this ability
4688 boolean allowDefaultRead = pi.readPermission == null;
4689 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004690
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004691 // check if target holds any <path-permission> that match uri
4692 final PathPermission[] pps = pi.pathPermissions;
4693 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004694 final String path = uri.getPath();
4695 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004696 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004697 i--;
4698 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004699 if (pp.match(path)) {
4700 if (!readMet) {
4701 final String pprperm = pp.getReadPermission();
4702 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4703 + pprperm + " for " + pp.getPath()
4704 + ": match=" + pp.match(path)
4705 + " check=" + pm.checkUidPermission(pprperm, uid));
4706 if (pprperm != null) {
4707 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4708 readMet = true;
4709 } else {
4710 allowDefaultRead = false;
4711 }
4712 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004713 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004714 if (!writeMet) {
4715 final String ppwperm = pp.getWritePermission();
4716 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4717 + ppwperm + " for " + pp.getPath()
4718 + ": match=" + pp.match(path)
4719 + " check=" + pm.checkUidPermission(ppwperm, uid));
4720 if (ppwperm != null) {
4721 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4722 writeMet = true;
4723 } else {
4724 allowDefaultWrite = false;
4725 }
4726 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004727 }
4728 }
4729 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004730 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004731
4732 // grant unprotected <provider> read/write, if not blocked by
4733 // <path-permission> above
4734 if (allowDefaultRead) readMet = true;
4735 if (allowDefaultWrite) writeMet = true;
4736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 } catch (RemoteException e) {
4738 return false;
4739 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004740
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 }
4743
4744 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4745 int modeFlags) {
4746 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004747 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 return true;
4749 }
4750 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4751 if (perms == null) return false;
4752 UriPermission perm = perms.get(uri);
4753 if (perm == null) return false;
4754 return (modeFlags&perm.modeFlags) == modeFlags;
4755 }
4756
4757 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004758 enforceNotIsolatedCaller("checkUriPermission");
4759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004760 // Another redirected-binder-call permissions check as in
4761 // {@link checkComponentPermission}.
4762 Identity tlsIdentity = sCallerIdentity.get();
4763 if (tlsIdentity != null) {
4764 uid = tlsIdentity.uid;
4765 pid = tlsIdentity.pid;
4766 }
4767
Amith Yamasani742a6712011-05-04 14:49:28 -07004768 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004769 // Our own process gets to do everything.
4770 if (pid == MY_PID) {
4771 return PackageManager.PERMISSION_GRANTED;
4772 }
4773 synchronized(this) {
4774 return checkUriPermissionLocked(uri, uid, modeFlags)
4775 ? PackageManager.PERMISSION_GRANTED
4776 : PackageManager.PERMISSION_DENIED;
4777 }
4778 }
4779
Dianne Hackborn39792d22010-08-19 18:01:52 -07004780 /**
4781 * Check if the targetPkg can be granted permission to access uri by
4782 * the callingUid using the given modeFlags. Throws a security exception
4783 * if callingUid is not allowed to do this. Returns the uid of the target
4784 * if the URI permission grant should be performed; returns -1 if it is not
4785 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004786 * If you already know the uid of the target, you can supply it in
4787 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004788 */
4789 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004790 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004791 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4792 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4793 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004794 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004795 }
4796
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004797 if (targetPkg != null) {
4798 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4799 "Checking grant " + targetPkg + " permission to " + uri);
4800 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004801
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004802 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004803
4804 // If this is not a content: uri, we can't do anything with it.
4805 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004806 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004807 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004808 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004809 }
4810
4811 String name = uri.getAuthority();
4812 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004813 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4814 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004815 if (cpr != null) {
4816 pi = cpr.info;
4817 } else {
4818 try {
4819 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004820 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004821 } catch (RemoteException ex) {
4822 }
4823 }
4824 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004825 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004826 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004827 }
4828
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004829 int targetUid = lastTargetUid;
4830 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004831 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004832 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004833 if (targetUid < 0) {
4834 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4835 "Can't grant URI permission no uid for: " + targetPkg);
4836 return -1;
4837 }
4838 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004839 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 }
4842
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004843 if (targetUid >= 0) {
4844 // First... does the target actually need this permission?
4845 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4846 // No need to grant the target this permission.
4847 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4848 "Target " + targetPkg + " already has full permission to " + uri);
4849 return -1;
4850 }
4851 } else {
4852 // First... there is no target package, so can anyone access it?
4853 boolean allowed = pi.exported;
4854 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4855 if (pi.readPermission != null) {
4856 allowed = false;
4857 }
4858 }
4859 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4860 if (pi.writePermission != null) {
4861 allowed = false;
4862 }
4863 }
4864 if (allowed) {
4865 return -1;
4866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004867 }
4868
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004869 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 if (!pi.grantUriPermissions) {
4871 throw new SecurityException("Provider " + pi.packageName
4872 + "/" + pi.name
4873 + " does not allow granting of Uri permissions (uri "
4874 + uri + ")");
4875 }
4876 if (pi.uriPermissionPatterns != null) {
4877 final int N = pi.uriPermissionPatterns.length;
4878 boolean allowed = false;
4879 for (int i=0; i<N; i++) {
4880 if (pi.uriPermissionPatterns[i] != null
4881 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4882 allowed = true;
4883 break;
4884 }
4885 }
4886 if (!allowed) {
4887 throw new SecurityException("Provider " + pi.packageName
4888 + "/" + pi.name
4889 + " does not allow granting of permission to path of Uri "
4890 + uri);
4891 }
4892 }
4893
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004894 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004896 if (callingUid != Process.myUid()) {
4897 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4898 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4899 throw new SecurityException("Uid " + callingUid
4900 + " does not have permission to uri " + uri);
4901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903 }
4904
Dianne Hackborn39792d22010-08-19 18:01:52 -07004905 return targetUid;
4906 }
4907
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004908 public int checkGrantUriPermission(int callingUid, String targetPkg,
4909 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004910 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004911 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004912 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004913 }
4914 }
4915
Dianne Hackborn39792d22010-08-19 18:01:52 -07004916 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4917 Uri uri, int modeFlags, UriPermissionOwner owner) {
4918 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4919 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4920 if (modeFlags == 0) {
4921 return;
4922 }
4923
4924 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 // to the uri, and the target doesn't. Let's now give this to
4926 // the target.
4927
Joe Onorato8a9b2202010-02-26 18:56:32 -08004928 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07004929 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 HashMap<Uri, UriPermission> targetUris
4932 = mGrantedUriPermissions.get(targetUid);
4933 if (targetUris == null) {
4934 targetUris = new HashMap<Uri, UriPermission>();
4935 mGrantedUriPermissions.put(targetUid, targetUris);
4936 }
4937
4938 UriPermission perm = targetUris.get(uri);
4939 if (perm == null) {
4940 perm = new UriPermission(targetUid, uri);
4941 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07004945 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08004947 } else {
4948 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4949 perm.readOwners.add(owner);
4950 owner.addReadPermission(perm);
4951 }
4952 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4953 perm.writeOwners.add(owner);
4954 owner.addWritePermission(perm);
4955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 }
4957 }
4958
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004959 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
4960 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004961 if (targetPkg == null) {
4962 throw new NullPointerException("targetPkg");
4963 }
4964
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004965 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004966 if (targetUid < 0) {
4967 return;
4968 }
4969
4970 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
4971 }
4972
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004973 static class NeededUriGrants extends ArrayList<Uri> {
4974 final String targetPkg;
4975 final int targetUid;
4976 final int flags;
4977
4978 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
4979 targetPkg = _targetPkg;
4980 targetUid = _targetUid;
4981 flags = _flags;
4982 }
4983 }
4984
Dianne Hackborn39792d22010-08-19 18:01:52 -07004985 /**
4986 * Like checkGrantUriPermissionLocked, but takes an Intent.
4987 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004988 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
4989 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07004990 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004991 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
4992 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07004993 + " from " + intent + "; flags=0x"
4994 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
4995
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004996 if (targetPkg == null) {
4997 throw new NullPointerException("targetPkg");
4998 }
4999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005001 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 }
5003 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005004 ClipData clip = intent.getClipData();
5005 if (data == null && clip == null) {
5006 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005007 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005008 if (data != null) {
5009 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5010 mode, needed != null ? needed.targetUid : -1);
5011 if (target > 0) {
5012 if (needed == null) {
5013 needed = new NeededUriGrants(targetPkg, target, mode);
5014 }
5015 needed.add(data);
5016 }
5017 }
5018 if (clip != null) {
5019 for (int i=0; i<clip.getItemCount(); i++) {
5020 Uri uri = clip.getItemAt(i).getUri();
5021 if (uri != null) {
5022 int target = -1;
5023 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5024 mode, needed != null ? needed.targetUid : -1);
5025 if (target > 0) {
5026 if (needed == null) {
5027 needed = new NeededUriGrants(targetPkg, target, mode);
5028 }
5029 needed.add(uri);
5030 }
5031 } else {
5032 Intent clipIntent = clip.getItemAt(i).getIntent();
5033 if (clipIntent != null) {
5034 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5035 callingUid, targetPkg, clipIntent, mode, needed);
5036 if (newNeeded != null) {
5037 needed = newNeeded;
5038 }
5039 }
5040 }
5041 }
5042 }
5043
5044 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005045 }
5046
5047 /**
5048 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5049 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005050 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5051 UriPermissionOwner owner) {
5052 if (needed != null) {
5053 for (int i=0; i<needed.size(); i++) {
5054 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5055 needed.get(i), needed.flags, owner);
5056 }
5057 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005058 }
5059
5060 void grantUriPermissionFromIntentLocked(int callingUid,
5061 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005062 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005063 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005064 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 return;
5066 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005067
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005068 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 }
5070
5071 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5072 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005073 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 synchronized(this) {
5075 final ProcessRecord r = getRecordForAppLocked(caller);
5076 if (r == null) {
5077 throw new SecurityException("Unable to find app for caller "
5078 + caller
5079 + " when granting permission to uri " + uri);
5080 }
5081 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005082 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005083 }
5084 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005085 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005086 }
5087
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005088 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005089 null);
5090 }
5091 }
5092
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005093 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005094 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5095 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5096 HashMap<Uri, UriPermission> perms
5097 = mGrantedUriPermissions.get(perm.uid);
5098 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005099 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005100 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005101 perms.remove(perm.uri);
5102 if (perms.size() == 0) {
5103 mGrantedUriPermissions.remove(perm.uid);
5104 }
5105 }
5106 }
5107 }
5108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005109 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5110 int modeFlags) {
5111 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5112 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5113 if (modeFlags == 0) {
5114 return;
5115 }
5116
Joe Onorato8a9b2202010-02-26 18:56:32 -08005117 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005118 "Revoking all granted permissions to " + uri);
5119
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005120 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005121
5122 final String authority = uri.getAuthority();
5123 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005124 int userId = UserId.getUserId(callingUid);
5125 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126 if (cpr != null) {
5127 pi = cpr.info;
5128 } else {
5129 try {
5130 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005131 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005132 } catch (RemoteException ex) {
5133 }
5134 }
5135 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005136 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 return;
5138 }
5139
5140 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005141 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 // Right now, if you are not the original owner of the permission,
5143 // you are not allowed to revoke it.
5144 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5145 throw new SecurityException("Uid " + callingUid
5146 + " does not have permission to uri " + uri);
5147 //}
5148 }
5149
5150 // Go through all of the permissions and remove any that match.
5151 final List<String> SEGMENTS = uri.getPathSegments();
5152 if (SEGMENTS != null) {
5153 final int NS = SEGMENTS.size();
5154 int N = mGrantedUriPermissions.size();
5155 for (int i=0; i<N; i++) {
5156 HashMap<Uri, UriPermission> perms
5157 = mGrantedUriPermissions.valueAt(i);
5158 Iterator<UriPermission> it = perms.values().iterator();
5159 toploop:
5160 while (it.hasNext()) {
5161 UriPermission perm = it.next();
5162 Uri targetUri = perm.uri;
5163 if (!authority.equals(targetUri.getAuthority())) {
5164 continue;
5165 }
5166 List<String> targetSegments = targetUri.getPathSegments();
5167 if (targetSegments == null) {
5168 continue;
5169 }
5170 if (targetSegments.size() < NS) {
5171 continue;
5172 }
5173 for (int j=0; j<NS; j++) {
5174 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5175 continue toploop;
5176 }
5177 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005178 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005179 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005180 perm.clearModes(modeFlags);
5181 if (perm.modeFlags == 0) {
5182 it.remove();
5183 }
5184 }
5185 if (perms.size() == 0) {
5186 mGrantedUriPermissions.remove(
5187 mGrantedUriPermissions.keyAt(i));
5188 N--;
5189 i--;
5190 }
5191 }
5192 }
5193 }
5194
5195 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5196 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005197 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 synchronized(this) {
5199 final ProcessRecord r = getRecordForAppLocked(caller);
5200 if (r == null) {
5201 throw new SecurityException("Unable to find app for caller "
5202 + caller
5203 + " when revoking permission to uri " + uri);
5204 }
5205 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005206 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 return;
5208 }
5209
5210 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5211 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5212 if (modeFlags == 0) {
5213 return;
5214 }
5215
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005216 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217
5218 final String authority = uri.getAuthority();
5219 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005220 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 if (cpr != null) {
5222 pi = cpr.info;
5223 } else {
5224 try {
5225 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005226 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005227 } catch (RemoteException ex) {
5228 }
5229 }
5230 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005231 Slog.w(TAG, "No content provider found for permission revoke: "
5232 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005233 return;
5234 }
5235
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005236 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 }
5238 }
5239
Dianne Hackborn7e269642010-08-25 19:50:20 -07005240 @Override
5241 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005242 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005243 synchronized(this) {
5244 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5245 return owner.getExternalTokenLocked();
5246 }
5247 }
5248
5249 @Override
5250 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5251 Uri uri, int modeFlags) {
5252 synchronized(this) {
5253 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5254 if (owner == null) {
5255 throw new IllegalArgumentException("Unknown owner: " + token);
5256 }
5257 if (fromUid != Binder.getCallingUid()) {
5258 if (Binder.getCallingUid() != Process.myUid()) {
5259 // Only system code can grant URI permissions on behalf
5260 // of other users.
5261 throw new SecurityException("nice try");
5262 }
5263 }
5264 if (targetPkg == null) {
5265 throw new IllegalArgumentException("null target");
5266 }
5267 if (uri == null) {
5268 throw new IllegalArgumentException("null uri");
5269 }
5270
5271 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5272 }
5273 }
5274
5275 @Override
5276 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5277 synchronized(this) {
5278 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5279 if (owner == null) {
5280 throw new IllegalArgumentException("Unknown owner: " + token);
5281 }
5282
5283 if (uri == null) {
5284 owner.removeUriPermissionsLocked(mode);
5285 } else {
5286 owner.removeUriPermissionLocked(uri, mode);
5287 }
5288 }
5289 }
5290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5292 synchronized (this) {
5293 ProcessRecord app =
5294 who != null ? getRecordForAppLocked(who) : null;
5295 if (app == null) return;
5296
5297 Message msg = Message.obtain();
5298 msg.what = WAIT_FOR_DEBUGGER_MSG;
5299 msg.obj = app;
5300 msg.arg1 = waiting ? 1 : 0;
5301 mHandler.sendMessage(msg);
5302 }
5303 }
5304
5305 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005306 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5307 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005309 outInfo.threshold = homeAppMem;
5310 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5311 outInfo.hiddenAppThreshold = hiddenAppMem;
5312 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005313 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005314 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5315 ProcessList.VISIBLE_APP_ADJ);
5316 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5317 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 }
5319
5320 // =========================================================
5321 // TASK MANAGEMENT
5322 // =========================================================
5323
5324 public List getTasks(int maxNum, int flags,
5325 IThumbnailReceiver receiver) {
5326 ArrayList list = new ArrayList();
5327
5328 PendingThumbnailsRecord pending = null;
5329 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005330 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331
5332 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005333 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5335 + ", receiver=" + receiver);
5336
5337 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5338 != PackageManager.PERMISSION_GRANTED) {
5339 if (receiver != null) {
5340 // If the caller wants to wait for pending thumbnails,
5341 // it ain't gonna get them.
5342 try {
5343 receiver.finished();
5344 } catch (RemoteException ex) {
5345 }
5346 }
5347 String msg = "Permission Denial: getTasks() from pid="
5348 + Binder.getCallingPid()
5349 + ", uid=" + Binder.getCallingUid()
5350 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005351 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352 throw new SecurityException(msg);
5353 }
5354
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005355 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005356 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005357 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005358 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 TaskRecord curTask = null;
5360 int numActivities = 0;
5361 int numRunning = 0;
5362 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005363 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005364 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005365 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366
5367 // Initialize state for next task if needed.
5368 if (top == null ||
5369 (top.state == ActivityState.INITIALIZING
5370 && top.task == r.task)) {
5371 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 curTask = r.task;
5373 numActivities = numRunning = 0;
5374 }
5375
5376 // Add 'r' into the current task.
5377 numActivities++;
5378 if (r.app != null && r.app.thread != null) {
5379 numRunning++;
5380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005381
Joe Onorato8a9b2202010-02-26 18:56:32 -08005382 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 TAG, r.intent.getComponent().flattenToShortString()
5384 + ": task=" + r.task);
5385
5386 // If the next one is a different task, generate a new
5387 // TaskInfo entry for what we have.
5388 if (next == null || next.task != curTask) {
5389 ActivityManager.RunningTaskInfo ci
5390 = new ActivityManager.RunningTaskInfo();
5391 ci.id = curTask.taskId;
5392 ci.baseActivity = r.intent.getComponent();
5393 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005394 if (top.thumbHolder != null) {
5395 ci.description = top.thumbHolder.lastDescription;
5396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 ci.numActivities = numActivities;
5398 ci.numRunning = numRunning;
5399 //System.out.println(
5400 // "#" + maxNum + ": " + " descr=" + ci.description);
5401 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005402 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005403 TAG, "State=" + top.state + "Idle=" + top.idle
5404 + " app=" + top.app
5405 + " thr=" + (top.app != null ? top.app.thread : null));
5406 if (top.state == ActivityState.RESUMED
5407 || top.state == ActivityState.PAUSING) {
5408 if (top.idle && top.app != null
5409 && top.app.thread != null) {
5410 topRecord = top;
5411 topThumbnail = top.app.thread;
5412 } else {
5413 top.thumbnailNeeded = true;
5414 }
5415 }
5416 if (pending == null) {
5417 pending = new PendingThumbnailsRecord(receiver);
5418 }
5419 pending.pendingRecords.add(top);
5420 }
5421 list.add(ci);
5422 maxNum--;
5423 top = null;
5424 }
5425 }
5426
5427 if (pending != null) {
5428 mPendingThumbnails.add(pending);
5429 }
5430 }
5431
Joe Onorato8a9b2202010-02-26 18:56:32 -08005432 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005433
5434 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005435 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005437 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005439 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005440 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 }
5442 }
5443
5444 if (pending == null && receiver != null) {
5445 // In this case all thumbnails were available and the client
5446 // is being asked to be told when the remaining ones come in...
5447 // which is unusually, since the top-most currently running
5448 // activity should never have a canned thumbnail! Oh well.
5449 try {
5450 receiver.finished();
5451 } catch (RemoteException ex) {
5452 }
5453 }
5454
5455 return list;
5456 }
5457
5458 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5459 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005460 final int callingUid = Binder.getCallingUid();
5461 // If it's the system uid asking, then use the current user id.
5462 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5463 // require the entire list.
5464 final int callingUserId = callingUid == Process.SYSTEM_UID
5465 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005466 synchronized (this) {
5467 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5468 "getRecentTasks()");
5469
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005470 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 final int N = mRecentTasks.size();
5473 ArrayList<ActivityManager.RecentTaskInfo> res
5474 = new ArrayList<ActivityManager.RecentTaskInfo>(
5475 maxNum < N ? maxNum : N);
5476 for (int i=0; i<N && maxNum > 0; i++) {
5477 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005478 // Only add calling user's recent tasks
5479 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005480 // Return the entry if desired by the caller. We always return
5481 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005482 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005483 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5484 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005485
Dianne Hackborn905577f2011-09-07 18:31:28 -07005486 if (i == 0
5487 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 || (tr.intent == null)
5489 || ((tr.intent.getFlags()
5490 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5491 ActivityManager.RecentTaskInfo rti
5492 = new ActivityManager.RecentTaskInfo();
5493 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005494 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 rti.baseIntent = new Intent(
5496 tr.intent != null ? tr.intent : tr.affinityIntent);
5497 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005498 rti.description = tr.lastDescription;
5499
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005500 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5501 // Check whether this activity is currently available.
5502 try {
5503 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005504 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5505 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005506 continue;
5507 }
5508 } else if (rti.baseIntent != null) {
5509 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005510 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005511 continue;
5512 }
5513 }
5514 } catch (RemoteException e) {
5515 // Will never happen.
5516 }
5517 }
5518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 res.add(rti);
5520 maxNum--;
5521 }
5522 }
5523 return res;
5524 }
5525 }
5526
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005527 private TaskRecord taskForIdLocked(int id) {
5528 final int N = mRecentTasks.size();
5529 for (int i=0; i<N; i++) {
5530 TaskRecord tr = mRecentTasks.get(i);
5531 if (tr.taskId == id) {
5532 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005533 }
5534 }
5535 return null;
5536 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005537
5538 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5539 synchronized (this) {
5540 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5541 "getTaskThumbnails()");
5542 TaskRecord tr = taskForIdLocked(id);
5543 if (tr != null) {
5544 return mMainStack.getTaskThumbnailsLocked(tr);
5545 }
5546 }
5547 return null;
5548 }
5549
5550 public boolean removeSubTask(int taskId, int subTaskIndex) {
5551 synchronized (this) {
5552 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5553 "removeSubTask()");
5554 long ident = Binder.clearCallingIdentity();
5555 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005556 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5557 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005558 } finally {
5559 Binder.restoreCallingIdentity(ident);
5560 }
5561 }
5562 }
5563
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005564 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5565 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005566 Intent baseIntent = new Intent(
5567 tr.intent != null ? tr.intent : tr.affinityIntent);
5568 ComponentName component = baseIntent.getComponent();
5569 if (component == null) {
5570 Slog.w(TAG, "Now component for base intent of task: " + tr);
5571 return;
5572 }
5573
5574 // Find any running services associated with this app.
5575 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005576 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005577 if (sr.packageName.equals(component.getPackageName())) {
5578 services.add(sr);
5579 }
5580 }
5581
5582 // Take care of any running services associated with the app.
5583 for (int i=0; i<services.size(); i++) {
5584 ServiceRecord sr = services.get(i);
5585 if (sr.startRequested) {
5586 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005587 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005588 stopServiceLocked(sr);
5589 } else {
5590 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005591 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005592 if (sr.app != null && sr.app.thread != null) {
5593 sendServiceArgsLocked(sr, false);
5594 }
5595 }
5596 }
5597 }
5598
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005599 if (killProcesses) {
5600 // Find any running processes associated with this app.
5601 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5602 SparseArray<ProcessRecord> appProcs
5603 = mProcessNames.getMap().get(component.getPackageName());
5604 if (appProcs != null) {
5605 for (int i=0; i<appProcs.size(); i++) {
5606 procs.add(appProcs.valueAt(i));
5607 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005608 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005610 // Kill the running processes.
5611 for (int i=0; i<procs.size(); i++) {
5612 ProcessRecord pr = procs.get(i);
5613 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5614 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5615 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5616 pr.processName, pr.setAdj, "remove task");
5617 Process.killProcessQuiet(pr.pid);
5618 } else {
5619 pr.waitingToKill = "remove task";
5620 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005621 }
5622 }
5623 }
5624
5625 public boolean removeTask(int taskId, int flags) {
5626 synchronized (this) {
5627 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5628 "removeTask()");
5629 long ident = Binder.clearCallingIdentity();
5630 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005631 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5632 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005633 if (r != null) {
5634 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005635 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005636 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005637 } else {
5638 TaskRecord tr = null;
5639 int i=0;
5640 while (i < mRecentTasks.size()) {
5641 TaskRecord t = mRecentTasks.get(i);
5642 if (t.taskId == taskId) {
5643 tr = t;
5644 break;
5645 }
5646 i++;
5647 }
5648 if (tr != null) {
5649 if (tr.numActivities <= 0) {
5650 // Caller is just removing a recent task that is
5651 // not actively running. That is easy!
5652 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005653 cleanUpRemovedTaskLocked(tr, flags);
5654 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005655 } else {
5656 Slog.w(TAG, "removeTask: task " + taskId
5657 + " does not have activities to remove, "
5658 + " but numActivities=" + tr.numActivities
5659 + ": " + tr);
5660 }
5661 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005662 }
5663 } finally {
5664 Binder.restoreCallingIdentity(ident);
5665 }
5666 }
5667 return false;
5668 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5671 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005672 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 TaskRecord jt = startTask;
5674
5675 // First look backwards
5676 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005677 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005678 if (r.task != jt) {
5679 jt = r.task;
5680 if (affinity.equals(jt.affinity)) {
5681 return j;
5682 }
5683 }
5684 }
5685
5686 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005687 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 jt = startTask;
5689 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005690 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005691 if (r.task != jt) {
5692 if (affinity.equals(jt.affinity)) {
5693 return j;
5694 }
5695 jt = r.task;
5696 }
5697 }
5698
5699 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005700 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 return N-1;
5702 }
5703
5704 return -1;
5705 }
5706
5707 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005708 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005710 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5712 "moveTaskToFront()");
5713
5714 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005715 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5716 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005717 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005718 return;
5719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 final long origId = Binder.clearCallingIdentity();
5721 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005722 TaskRecord tr = taskForIdLocked(task);
5723 if (tr != null) {
5724 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5725 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005727 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5728 // Caller wants the home activity moved with it. To accomplish this,
5729 // we'll just move the home task to the top first.
5730 mMainStack.moveHomeToFrontLocked();
5731 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005732 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005733 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005735 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5736 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005738 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5739 mMainStack.mUserLeaving = true;
5740 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005741 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5742 // Caller wants the home activity moved with it. To accomplish this,
5743 // we'll just move the home task to the top first.
5744 mMainStack.moveHomeToFrontLocked();
5745 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005746 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 return;
5748 }
5749 }
5750 } finally {
5751 Binder.restoreCallingIdentity(origId);
5752 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005753 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 }
5755 }
5756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 public void moveTaskToBack(int task) {
5758 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5759 "moveTaskToBack()");
5760
5761 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005762 if (mMainStack.mResumedActivity != null
5763 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005764 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5765 Binder.getCallingUid(), "Task to back")) {
5766 return;
5767 }
5768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005770 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005771 Binder.restoreCallingIdentity(origId);
5772 }
5773 }
5774
5775 /**
5776 * Moves an activity, and all of the other activities within the same task, to the bottom
5777 * of the history stack. The activity's order within the task is unchanged.
5778 *
5779 * @param token A reference to the activity we wish to move
5780 * @param nonRoot If false then this only works if the activity is the root
5781 * of a task; if true it will work for any activity in a task.
5782 * @return Returns true if the move completed, false if not.
5783 */
5784 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005785 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 synchronized(this) {
5787 final long origId = Binder.clearCallingIdentity();
5788 int taskId = getTaskForActivityLocked(token, !nonRoot);
5789 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005790 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 }
5792 Binder.restoreCallingIdentity(origId);
5793 }
5794 return false;
5795 }
5796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 public void moveTaskBackwards(int task) {
5798 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5799 "moveTaskBackwards()");
5800
5801 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005802 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5803 Binder.getCallingUid(), "Task backwards")) {
5804 return;
5805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005806 final long origId = Binder.clearCallingIdentity();
5807 moveTaskBackwardsLocked(task);
5808 Binder.restoreCallingIdentity(origId);
5809 }
5810 }
5811
5812 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005813 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 }
5815
5816 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5817 synchronized(this) {
5818 return getTaskForActivityLocked(token, onlyRoot);
5819 }
5820 }
5821
5822 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005823 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005824 TaskRecord lastTask = null;
5825 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005826 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005827 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 if (!onlyRoot || lastTask != r.task) {
5829 return r.task.taskId;
5830 }
5831 return -1;
5832 }
5833 lastTask = r.task;
5834 }
5835
5836 return -1;
5837 }
5838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 // =========================================================
5840 // THUMBNAILS
5841 // =========================================================
5842
5843 public void reportThumbnail(IBinder token,
5844 Bitmap thumbnail, CharSequence description) {
5845 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5846 final long origId = Binder.clearCallingIdentity();
5847 sendPendingThumbnail(null, token, thumbnail, description, true);
5848 Binder.restoreCallingIdentity(origId);
5849 }
5850
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005851 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 Bitmap thumbnail, CharSequence description, boolean always) {
5853 TaskRecord task = null;
5854 ArrayList receivers = null;
5855
5856 //System.out.println("Send pending thumbnail: " + r);
5857
5858 synchronized(this) {
5859 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005860 r = mMainStack.isInStackLocked(token);
5861 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 return;
5863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005865 if (thumbnail == null && r.thumbHolder != null) {
5866 thumbnail = r.thumbHolder.lastThumbnail;
5867 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
5869 if (thumbnail == null && !always) {
5870 // If there is no thumbnail, and this entry is not actually
5871 // going away, then abort for now and pick up the next
5872 // thumbnail we get.
5873 return;
5874 }
5875 task = r.task;
5876
5877 int N = mPendingThumbnails.size();
5878 int i=0;
5879 while (i<N) {
5880 PendingThumbnailsRecord pr =
5881 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5882 //System.out.println("Looking in " + pr.pendingRecords);
5883 if (pr.pendingRecords.remove(r)) {
5884 if (receivers == null) {
5885 receivers = new ArrayList();
5886 }
5887 receivers.add(pr);
5888 if (pr.pendingRecords.size() == 0) {
5889 pr.finished = true;
5890 mPendingThumbnails.remove(i);
5891 N--;
5892 continue;
5893 }
5894 }
5895 i++;
5896 }
5897 }
5898
5899 if (receivers != null) {
5900 final int N = receivers.size();
5901 for (int i=0; i<N; i++) {
5902 try {
5903 PendingThumbnailsRecord pr =
5904 (PendingThumbnailsRecord)receivers.get(i);
5905 pr.receiver.newThumbnail(
5906 task != null ? task.taskId : -1, thumbnail, description);
5907 if (pr.finished) {
5908 pr.receiver.finished();
5909 }
5910 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005911 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 }
5913 }
5914 }
5915 }
5916
5917 // =========================================================
5918 // CONTENT PROVIDERS
5919 // =========================================================
5920
Jeff Brown10e89712011-07-08 18:52:57 -07005921 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
5922 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005924 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005925 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07005926 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 } catch (RemoteException ex) {
5928 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005929 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005930 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
5931 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 if (providers != null) {
5933 final int N = providers.size();
5934 for (int i=0; i<N; i++) {
5935 ProviderInfo cpi =
5936 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005937
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07005938 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07005939 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08005941 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07005942 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 }
Amith Yamasani742a6712011-05-04 14:49:28 -07005944 if (DEBUG_MU)
5945 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 app.pubProviders.put(cpi.name, cpr);
5947 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07005948 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 }
5950 }
5951 return providers;
5952 }
5953
Jeff Sharkey110a6b62012-03-12 11:12:41 -07005954 /**
5955 * Check if {@link ProcessRecord} has a possible chance at accessing the
5956 * given {@link ProviderInfo}. Final permission checking is always done
5957 * in {@link ContentProvider}.
5958 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07005960 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005961 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005962 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005964 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005965 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 return null;
5967 }
5968 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005969 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 == PackageManager.PERMISSION_GRANTED) {
5971 return null;
5972 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005973
5974 PathPermission[] pps = cpi.pathPermissions;
5975 if (pps != null) {
5976 int i = pps.length;
5977 while (i > 0) {
5978 i--;
5979 PathPermission pp = pps[i];
5980 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005981 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005982 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005983 return null;
5984 }
5985 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08005986 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07005987 == PackageManager.PERMISSION_GRANTED) {
5988 return null;
5989 }
5990 }
5991 }
5992
Dianne Hackbornb424b632010-08-18 15:59:05 -07005993 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
5994 if (perms != null) {
5995 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
5996 if (uri.getKey().getAuthority().equals(cpi.authority)) {
5997 return null;
5998 }
5999 }
6000 }
6001
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006002 String msg;
6003 if (!cpi.exported) {
6004 msg = "Permission Denial: opening provider " + cpi.name
6005 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6006 + ", uid=" + callingUid + ") that is not exported from uid "
6007 + cpi.applicationInfo.uid;
6008 } else {
6009 msg = "Permission Denial: opening provider " + cpi.name
6010 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6011 + ", uid=" + callingUid + ") requires "
6012 + cpi.readPermission + " or " + cpi.writePermission;
6013 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006014 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 return msg;
6016 }
6017
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006018 boolean incProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6019 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006020 if (r != null) {
6021 Integer cnt = r.conProviders.get(cpr);
6022 if (DEBUG_PROVIDER) Slog.v(TAG,
6023 "Adding provider requested by "
6024 + r.processName + " from process "
6025 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6026 + " cnt=" + (cnt == null ? 1 : cnt));
6027 if (cnt == null) {
6028 cpr.clients.add(r);
6029 r.conProviders.put(cpr, new Integer(1));
6030 return true;
6031 } else {
6032 r.conProviders.put(cpr, new Integer(cnt.intValue()+1));
6033 }
6034 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006035 cpr.addExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006036 }
6037 return false;
6038 }
6039
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006040 boolean decProviderCount(ProcessRecord r, final ContentProviderRecord cpr,
6041 IBinder externalProcessToken) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006042 if (r != null) {
6043 Integer cnt = r.conProviders.get(cpr);
6044 if (DEBUG_PROVIDER) Slog.v(TAG,
6045 "Removing provider requested by "
6046 + r.processName + " from process "
6047 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6048 + " cnt=" + cnt);
6049 if (cnt == null || cnt.intValue() <= 1) {
6050 cpr.clients.remove(r);
6051 r.conProviders.remove(cpr);
6052 return true;
6053 } else {
6054 r.conProviders.put(cpr, new Integer(cnt.intValue()-1));
6055 }
6056 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006057 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006058 }
6059 return false;
6060 }
6061
Amith Yamasani742a6712011-05-04 14:49:28 -07006062 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006063 String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 ContentProviderRecord cpr;
6065 ProviderInfo cpi = null;
6066
6067 synchronized(this) {
6068 ProcessRecord r = null;
6069 if (caller != null) {
6070 r = getRecordForAppLocked(caller);
6071 if (r == null) {
6072 throw new SecurityException(
6073 "Unable to find app for caller " + caller
6074 + " (pid=" + Binder.getCallingPid()
6075 + ") when getting content provider " + name);
6076 }
6077 }
6078
6079 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006080 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006081 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006082 boolean providerRunning = cpr != null;
6083 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006084 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006085 String msg;
6086 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6087 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 }
6089
6090 if (r != null && cpr.canRunHere(r)) {
6091 // This provider has been published or is in the process
6092 // of being published... but it is also allowed to run
6093 // in the caller's process, so don't make a connection
6094 // and just let the caller instantiate its own instance.
6095 if (cpr.provider != null) {
6096 // don't give caller the provider object, it needs
6097 // to make its own.
6098 cpr = new ContentProviderRecord(cpr);
6099 }
6100 return cpr;
6101 }
6102
6103 final long origId = Binder.clearCallingIdentity();
6104
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006105 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 // return it right away.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006107 final boolean countChanged = incProviderCount(r, cpr, token);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006108 if (countChanged) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006109 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006110 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006111 // make sure to count it as being accessed and thus
6112 // back up on the LRU list. This is good because
6113 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006114 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006115 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006116 }
6117
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006118 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006119 if (false) {
6120 if (cpr.name.flattenToShortString().equals(
6121 "com.android.providers.calendar/.CalendarProvider2")) {
6122 Slog.v(TAG, "****************** KILLING "
6123 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006124 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006125 }
6126 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006127 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006128 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6129 // NOTE: there is still a race here where a signal could be
6130 // pending on the process even though we managed to update its
6131 // adj level. Not sure what to do about this, but at least
6132 // the race is now smaller.
6133 if (!success) {
6134 // Uh oh... it looks like the provider's process
6135 // has been killed on us. We need to wait for a new
6136 // process to be started, and make sure its death
6137 // doesn't kill our process.
6138 Slog.i(TAG,
6139 "Existing provider " + cpr.name.flattenToShortString()
6140 + " is crashing; detaching " + r);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006141 boolean lastRef = decProviderCount(r, cpr, token);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006142 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006143 if (!lastRef) {
6144 // This wasn't the last ref our process had on
6145 // the provider... we have now been killed, bail.
6146 return null;
6147 }
6148 providerRunning = false;
6149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 }
6151
6152 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006155 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006157 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006158 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006159 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 } catch (RemoteException ex) {
6161 }
6162 if (cpi == null) {
6163 return null;
6164 }
6165
Amith Yamasani483f3b02012-03-13 16:08:00 -07006166 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006167
Dianne Hackbornb424b632010-08-18 15:59:05 -07006168 String msg;
6169 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6170 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 }
6172
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006173 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006174 && !cpi.processName.equals("system")) {
6175 // If this content provider does not run in the system
6176 // process, and the system is not yet ready to run other
6177 // processes, then fail fast instead of hanging.
6178 throw new IllegalArgumentException(
6179 "Attempt to launch content provider before system ready");
6180 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006181
6182 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006183 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 final boolean firstClass = cpr == null;
6185 if (firstClass) {
6186 try {
6187 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006188 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 getApplicationInfo(
6190 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006191 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006193 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 + cpi.name);
6195 return null;
6196 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006197 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006198 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 } catch (RemoteException ex) {
6200 // pm is in same process, this will never happen.
6201 }
6202 }
6203
6204 if (r != null && cpr.canRunHere(r)) {
6205 // If this is a multiprocess provider, then just return its
6206 // info and allow the caller to instantiate it. Only do
6207 // this if the provider is the same user as the caller's
6208 // process, or can run as root (so can be in any process).
6209 return cpr;
6210 }
6211
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006212 if (DEBUG_PROVIDER) {
6213 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006214 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006215 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 }
6217
6218 // This is single process, and our app is now connecting to it.
6219 // See if we are already in the process of launching this
6220 // provider.
6221 final int N = mLaunchingProviders.size();
6222 int i;
6223 for (i=0; i<N; i++) {
6224 if (mLaunchingProviders.get(i) == cpr) {
6225 break;
6226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006227 }
6228
6229 // If the provider is not already being launched, then get it
6230 // started.
6231 if (i >= N) {
6232 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006233
6234 try {
6235 // Content provider is now in use, its package can't be stopped.
6236 try {
6237 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006238 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006239 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006240 } catch (IllegalArgumentException e) {
6241 Slog.w(TAG, "Failed trying to unstop package "
6242 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006243 }
6244
6245 ProcessRecord proc = startProcessLocked(cpi.processName,
6246 cpr.appInfo, false, 0, "content provider",
6247 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006248 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006249 if (proc == null) {
6250 Slog.w(TAG, "Unable to launch app "
6251 + cpi.applicationInfo.packageName + "/"
6252 + cpi.applicationInfo.uid + " for provider "
6253 + name + ": process is bad");
6254 return null;
6255 }
6256 cpr.launchingApp = proc;
6257 mLaunchingProviders.add(cpr);
6258 } finally {
6259 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 }
6262
6263 // Make sure the provider is published (the same provider class
6264 // may be published under multiple names).
6265 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006266 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006268
Amith Yamasani742a6712011-05-04 14:49:28 -07006269 mProviderMap.putProviderByName(name, cpr);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006270 incProviderCount(r, cpr, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 }
6272 }
6273
6274 // Wait for the provider to be published...
6275 synchronized (cpr) {
6276 while (cpr.provider == null) {
6277 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006278 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 + cpi.applicationInfo.packageName + "/"
6280 + cpi.applicationInfo.uid + " for provider "
6281 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006282 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006283 cpi.applicationInfo.packageName,
6284 cpi.applicationInfo.uid, name);
6285 return null;
6286 }
6287 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006288 if (DEBUG_MU) {
6289 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6290 + cpr.launchingApp);
6291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 cpr.wait();
6293 } catch (InterruptedException ex) {
6294 }
6295 }
6296 }
6297 return cpr;
6298 }
6299
6300 public final ContentProviderHolder getContentProvider(
6301 IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006302 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 if (caller == null) {
6304 String msg = "null IApplicationThread when getting content provider "
6305 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006306 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 throw new SecurityException(msg);
6308 }
6309
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006310 return getContentProviderImpl(caller, name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 }
6312
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006313 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6314 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6315 "Do not have permission in call getContentProviderExternal()");
6316 return getContentProviderExternalUnchecked(name, token);
6317 }
6318
6319 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
6320 return getContentProviderImpl(null, name, token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 }
6322
6323 /**
6324 * Drop a content provider from a ProcessRecord's bookkeeping
6325 * @param cpr
6326 */
6327 public void removeContentProvider(IApplicationThread caller, String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006328 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006330 int userId = UserId.getUserId(Binder.getCallingUid());
6331 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if(cpr == null) {
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006333 // remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006334 if (DEBUG_PROVIDER) Slog.v(TAG, name +
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006335 " provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return;
6337 }
6338 final ProcessRecord r = getRecordForAppLocked(caller);
6339 if (r == null) {
6340 throw new SecurityException(
6341 "Unable to find app for caller " + caller +
6342 " when removing content provider " + name);
6343 }
6344 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006345 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006346 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
6347 if (DEBUG_PROVIDER) Slog.v(TAG, "Removing provider requested by "
6348 + r.info.processName + " from process "
6349 + localCpr.appInfo.processName);
6350 if (localCpr.launchingApp == r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 //should not happen. taken care of as a local provider
Joe Onorato8a9b2202010-02-26 18:56:32 -08006352 Slog.w(TAG, "removeContentProvider called on local provider: "
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006353 + cpr.info.name + " in process " + r.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 return;
6355 } else {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006356 if (decProviderCount(r, localCpr, null)) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006357 updateOomAdjLocked();
Dianne Hackborn0c3154d2009-10-06 17:18:05 -07006358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
6361 }
6362
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006363 public void removeContentProviderExternal(String name, IBinder token) {
6364 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6365 "Do not have permission in call removeContentProviderExternal()");
6366 removeContentProviderExternalUnchecked(name, token);
6367 }
6368
6369 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006371 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6372 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 if(cpr == null) {
6374 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006375 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006376 return;
6377 }
6378
6379 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006380 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006381 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6382 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006383 if (localCpr.hasExternalProcessHandles()) {
6384 if (localCpr.removeExternalProcessHandleLocked(token)) {
6385 updateOomAdjLocked();
6386 } else {
6387 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6388 + " with no external reference for token: "
6389 + token + ".");
6390 }
6391 } else {
6392 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6393 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396 }
6397
6398 public final void publishContentProviders(IApplicationThread caller,
6399 List<ContentProviderHolder> providers) {
6400 if (providers == null) {
6401 return;
6402 }
6403
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006404 enforceNotIsolatedCaller("publishContentProviders");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 synchronized(this) {
6406 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006407 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006408 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 if (r == null) {
6410 throw new SecurityException(
6411 "Unable to find app for caller " + caller
6412 + " (pid=" + Binder.getCallingPid()
6413 + ") when publishing content providers");
6414 }
6415
6416 final long origId = Binder.clearCallingIdentity();
6417
6418 final int N = providers.size();
6419 for (int i=0; i<N; i++) {
6420 ContentProviderHolder src = providers.get(i);
6421 if (src == null || src.info == null || src.provider == null) {
6422 continue;
6423 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006424 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006425 if (DEBUG_MU)
6426 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006427 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006428 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006429 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006430 String names[] = dst.info.authority.split(";");
6431 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006432 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 }
6434
6435 int NL = mLaunchingProviders.size();
6436 int j;
6437 for (j=0; j<NL; j++) {
6438 if (mLaunchingProviders.get(j) == dst) {
6439 mLaunchingProviders.remove(j);
6440 j--;
6441 NL--;
6442 }
6443 }
6444 synchronized (dst) {
6445 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006446 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 dst.notifyAll();
6448 }
6449 updateOomAdjLocked(r);
6450 }
6451 }
6452
6453 Binder.restoreCallingIdentity(origId);
6454 }
6455 }
6456
6457 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006458 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006459 synchronized (mSelf) {
6460 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6461 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006462 if (providers != null) {
6463 for (int i=providers.size()-1; i>=0; i--) {
6464 ProviderInfo pi = (ProviderInfo)providers.get(i);
6465 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6466 Slog.w(TAG, "Not installing system proc provider " + pi.name
6467 + ": not system .apk");
6468 providers.remove(i);
6469 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006470 }
6471 }
6472 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006473 if (providers != null) {
6474 mSystemThread.installSystemProviders(providers);
6475 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006476
6477 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006478
6479 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 }
6481
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006482 /**
6483 * Allows app to retrieve the MIME type of a URI without having permission
6484 * to access its content provider.
6485 *
6486 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6487 *
6488 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6489 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6490 */
6491 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006492 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006493 final String name = uri.getAuthority();
6494 final long ident = Binder.clearCallingIdentity();
6495 ContentProviderHolder holder = null;
6496
6497 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006498 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006499 if (holder != null) {
6500 return holder.provider.getType(uri);
6501 }
6502 } catch (RemoteException e) {
6503 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6504 return null;
6505 } finally {
6506 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006507 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006508 }
6509 Binder.restoreCallingIdentity(ident);
6510 }
6511
6512 return null;
6513 }
6514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 // =========================================================
6516 // GLOBAL MANAGEMENT
6517 // =========================================================
6518
6519 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006520 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 String proc = customProcess != null ? customProcess : info.processName;
6522 BatteryStatsImpl.Uid.Proc ps = null;
6523 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006524 int uid = info.uid;
6525 if (isolated) {
6526 int userId = UserId.getUserId(uid);
6527 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6528 uid = 0;
6529 while (true) {
6530 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6531 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6532 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6533 }
6534 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6535 mNextIsolatedProcessUid++;
6536 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6537 // No process for this uid, use it.
6538 break;
6539 }
6540 stepsLeft--;
6541 if (stepsLeft <= 0) {
6542 return null;
6543 }
6544 }
6545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 synchronized (stats) {
6547 ps = stats.getProcessStatsLocked(info.uid, proc);
6548 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006549 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006550 }
6551
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006552 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6553 ProcessRecord app;
6554 if (!isolated) {
6555 app = getProcessRecordLocked(info.processName, info.uid);
6556 } else {
6557 app = null;
6558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559
6560 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006561 app = newProcessRecordLocked(null, info, null, isolated);
6562 mProcessNames.put(info.processName, app.uid, app);
6563 if (isolated) {
6564 mIsolatedProcesses.put(app.uid, app);
6565 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006566 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006567 }
6568
Dianne Hackborne7f97212011-02-24 14:40:20 -08006569 // This package really, really can not be stopped.
6570 try {
6571 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006572 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006573 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006574 } catch (IllegalArgumentException e) {
6575 Slog.w(TAG, "Failed trying to unstop package "
6576 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006577 }
6578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6580 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6581 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006582 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 }
6584 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6585 mPersistentStartingProcesses.add(app);
6586 startProcessLocked(app, "added application", app.processName);
6587 }
6588
6589 return app;
6590 }
6591
6592 public void unhandledBack() {
6593 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6594 "unhandledBack()");
6595
6596 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006597 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006598 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 TAG, "Performing unhandledBack(): stack size = " + count);
6600 if (count > 1) {
6601 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006602 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6604 Binder.restoreCallingIdentity(origId);
6605 }
6606 }
6607 }
6608
6609 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006610 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006612 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 ParcelFileDescriptor pfd = null;
6614 if (cph != null) {
6615 // We record the binder invoker's uid in thread-local storage before
6616 // going to the content provider to open the file. Later, in the code
6617 // that handles all permissions checks, we look for this uid and use
6618 // that rather than the Activity Manager's own uid. The effect is that
6619 // we do the check against the caller's permissions even though it looks
6620 // to the content provider like the Activity Manager itself is making
6621 // the request.
6622 sCallerIdentity.set(new Identity(
6623 Binder.getCallingPid(), Binder.getCallingUid()));
6624 try {
6625 pfd = cph.provider.openFile(uri, "r");
6626 } catch (FileNotFoundException e) {
6627 // do nothing; pfd will be returned null
6628 } finally {
6629 // Ensure that whatever happens, we clean up the identity state
6630 sCallerIdentity.remove();
6631 }
6632
6633 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006634 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006635 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006636 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 }
6638 return pfd;
6639 }
6640
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006641 // Actually is sleeping or shutting down or whatever else in the future
6642 // is an inactive state.
6643 public boolean isSleeping() {
6644 return mSleeping || mShuttingDown;
6645 }
6646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 public void goingToSleep() {
6648 synchronized(this) {
6649 mSleeping = true;
6650 mWindowManager.setEventDispatching(false);
6651
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006652 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006653
6654 // Initialize the wake times of all processes.
Dianne Hackborn287952c2010-09-22 22:34:31 -07006655 checkExcessivePowerUsageLocked(false);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006656 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6657 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07006658 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 }
6660 }
6661
Dianne Hackborn55280a92009-05-07 15:53:46 -07006662 public boolean shutdown(int timeout) {
6663 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6664 != PackageManager.PERMISSION_GRANTED) {
6665 throw new SecurityException("Requires permission "
6666 + android.Manifest.permission.SHUTDOWN);
6667 }
6668
6669 boolean timedout = false;
6670
6671 synchronized(this) {
6672 mShuttingDown = true;
6673 mWindowManager.setEventDispatching(false);
6674
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006675 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006676 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006677 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006678 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006679 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006680 long delay = endTime - System.currentTimeMillis();
6681 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006682 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006683 timedout = true;
6684 break;
6685 }
6686 try {
6687 this.wait();
6688 } catch (InterruptedException e) {
6689 }
6690 }
6691 }
6692 }
6693
6694 mUsageStatsService.shutdown();
6695 mBatteryStatsService.shutdown();
6696
6697 return timedout;
6698 }
6699
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006700 public final void activitySlept(IBinder token) {
6701 if (localLOGV) Slog.v(
6702 TAG, "Activity slept: token=" + token);
6703
6704 ActivityRecord r = null;
6705
6706 final long origId = Binder.clearCallingIdentity();
6707
6708 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006709 r = mMainStack.isInStackLocked(token);
6710 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006711 mMainStack.activitySleptLocked(r);
6712 }
6713 }
6714
6715 Binder.restoreCallingIdentity(origId);
6716 }
6717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 public void wakingUp() {
6719 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 mWindowManager.setEventDispatching(true);
6721 mSleeping = false;
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006722 mMainStack.awakeFromSleepingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006723 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 }
6725 }
6726
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006727 public void stopAppSwitches() {
6728 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6729 != PackageManager.PERMISSION_GRANTED) {
6730 throw new SecurityException("Requires permission "
6731 + android.Manifest.permission.STOP_APP_SWITCHES);
6732 }
6733
6734 synchronized(this) {
6735 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6736 + APP_SWITCH_DELAY_TIME;
6737 mDidAppSwitch = false;
6738 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6739 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6740 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6741 }
6742 }
6743
6744 public void resumeAppSwitches() {
6745 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6746 != PackageManager.PERMISSION_GRANTED) {
6747 throw new SecurityException("Requires permission "
6748 + android.Manifest.permission.STOP_APP_SWITCHES);
6749 }
6750
6751 synchronized(this) {
6752 // Note that we don't execute any pending app switches... we will
6753 // let those wait until either the timeout, or the next start
6754 // activity request.
6755 mAppSwitchesAllowedTime = 0;
6756 }
6757 }
6758
6759 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6760 String name) {
6761 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6762 return true;
6763 }
6764
6765 final int perm = checkComponentPermission(
6766 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006767 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006768 if (perm == PackageManager.PERMISSION_GRANTED) {
6769 return true;
6770 }
6771
Joe Onorato8a9b2202010-02-26 18:56:32 -08006772 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006773 return false;
6774 }
6775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 public void setDebugApp(String packageName, boolean waitForDebugger,
6777 boolean persistent) {
6778 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
6779 "setDebugApp()");
6780
6781 // Note that this is not really thread safe if there are multiple
6782 // callers into it at the same time, but that's not a situation we
6783 // care about.
6784 if (persistent) {
6785 final ContentResolver resolver = mContext.getContentResolver();
6786 Settings.System.putString(
6787 resolver, Settings.System.DEBUG_APP,
6788 packageName);
6789 Settings.System.putInt(
6790 resolver, Settings.System.WAIT_FOR_DEBUGGER,
6791 waitForDebugger ? 1 : 0);
6792 }
6793
6794 synchronized (this) {
6795 if (!persistent) {
6796 mOrigDebugApp = mDebugApp;
6797 mOrigWaitForDebugger = mWaitForDebugger;
6798 }
6799 mDebugApp = packageName;
6800 mWaitForDebugger = waitForDebugger;
6801 mDebugTransient = !persistent;
6802 if (packageName != null) {
6803 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07006804 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 Binder.restoreCallingIdentity(origId);
6806 }
6807 }
6808 }
6809
Siva Velusamy92a8b222012-03-09 16:24:04 -08006810 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
6811 synchronized (this) {
6812 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6813 if (!isDebuggable) {
6814 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6815 throw new SecurityException("Process not debuggable: " + app.packageName);
6816 }
6817 }
6818
6819 mOpenGlTraceApp = processName;
6820 }
6821 }
6822
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07006823 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
6824 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
6825 synchronized (this) {
6826 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
6827 if (!isDebuggable) {
6828 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
6829 throw new SecurityException("Process not debuggable: " + app.packageName);
6830 }
6831 }
6832 mProfileApp = processName;
6833 mProfileFile = profileFile;
6834 if (mProfileFd != null) {
6835 try {
6836 mProfileFd.close();
6837 } catch (IOException e) {
6838 }
6839 mProfileFd = null;
6840 }
6841 mProfileFd = profileFd;
6842 mProfileType = 0;
6843 mAutoStopProfiler = autoStopProfiler;
6844 }
6845 }
6846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 public void setAlwaysFinish(boolean enabled) {
6848 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
6849 "setAlwaysFinish()");
6850
6851 Settings.System.putInt(
6852 mContext.getContentResolver(),
6853 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
6854
6855 synchronized (this) {
6856 mAlwaysFinishActivities = enabled;
6857 }
6858 }
6859
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006860 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006862 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07006864 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 }
6866 }
6867
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08006868 public boolean isUserAMonkey() {
6869 // For now the fact that there is a controller implies
6870 // we have a monkey.
6871 synchronized (this) {
6872 return mController != null;
6873 }
6874 }
6875
Jeff Sharkeya4620792011-05-20 15:29:23 -07006876 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006877 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
6878 "registerProcessObserver()");
6879 synchronized (this) {
6880 mProcessObservers.register(observer);
6881 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006882 }
6883
6884 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08006885 synchronized (this) {
6886 mProcessObservers.unregister(observer);
6887 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07006888 }
6889
Daniel Sandler69a48172010-06-23 16:29:36 -04006890 public void setImmersive(IBinder token, boolean immersive) {
6891 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006892 ActivityRecord r = mMainStack.isInStackLocked(token);
6893 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006894 throw new IllegalArgumentException();
6895 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006896 r.immersive = immersive;
6897 }
6898 }
6899
6900 public boolean isImmersive(IBinder token) {
6901 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006902 ActivityRecord r = mMainStack.isInStackLocked(token);
6903 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04006904 throw new IllegalArgumentException();
6905 }
Daniel Sandler69a48172010-06-23 16:29:36 -04006906 return r.immersive;
6907 }
6908 }
6909
6910 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006911 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04006912 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006913 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04006914 return (r != null) ? r.immersive : false;
6915 }
6916 }
6917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 public final void enterSafeMode() {
6919 synchronized(this) {
6920 // It only makes sense to do this before the system is ready
6921 // and started launching other packages.
6922 if (!mSystemReady) {
6923 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006924 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 } catch (RemoteException e) {
6926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
6928 }
6929 }
6930
Jeff Brownb09abc12011-01-13 21:08:27 -08006931 public final void showSafeModeOverlay() {
6932 View v = LayoutInflater.from(mContext).inflate(
6933 com.android.internal.R.layout.safe_mode, null);
6934 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
6935 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
6936 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
6937 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
6938 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
6939 lp.format = v.getBackground().getOpacity();
6940 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
6941 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
6942 ((WindowManager)mContext.getSystemService(
6943 Context.WINDOW_SERVICE)).addView(v, lp);
6944 }
6945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 public void noteWakeupAlarm(IIntentSender sender) {
6947 if (!(sender instanceof PendingIntentRecord)) {
6948 return;
6949 }
6950 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
6951 synchronized (stats) {
6952 if (mBatteryStatsService.isOnBattery()) {
6953 mBatteryStatsService.enforceCallingPermission();
6954 PendingIntentRecord rec = (PendingIntentRecord)sender;
6955 int MY_UID = Binder.getCallingUid();
6956 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
6957 BatteryStatsImpl.Uid.Pkg pkg =
6958 stats.getPackageStatsLocked(uid, rec.key.packageName);
6959 pkg.incWakeupsLocked();
6960 }
6961 }
6962 }
6963
Dianne Hackborn64825172011-03-02 21:32:58 -08006964 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006966 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006967 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07006968 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006969 // XXX Note: don't acquire main activity lock here, because the window
6970 // manager calls in with its locks held.
6971
6972 boolean killed = false;
6973 synchronized (mPidsSelfLocked) {
6974 int[] types = new int[pids.length];
6975 int worstType = 0;
6976 for (int i=0; i<pids.length; i++) {
6977 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
6978 if (proc != null) {
6979 int type = proc.setAdj;
6980 types[i] = type;
6981 if (type > worstType) {
6982 worstType = type;
6983 }
6984 }
6985 }
6986
Dianne Hackborn64825172011-03-02 21:32:58 -08006987 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006988 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006989 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
6990 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07006991 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006992 }
Dianne Hackborn64825172011-03-02 21:32:58 -08006993
6994 // If this is not a secure call, don't let it kill processes that
6995 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006996 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
6997 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08006998 }
6999
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007000 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007001 for (int i=0; i<pids.length; i++) {
7002 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7003 if (proc == null) {
7004 continue;
7005 }
7006 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007007 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007008 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007009 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7010 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007011 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007012 proc.killedBackground = true;
7013 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 }
7015 }
7016 }
7017 return killed;
7018 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007019
7020 @Override
7021 public boolean killProcessesBelowForeground(String reason) {
7022 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7023 throw new SecurityException("killProcessesBelowForeground() only available to system");
7024 }
7025
7026 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7027 }
7028
7029 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7030 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7031 throw new SecurityException("killProcessesBelowAdj() only available to system");
7032 }
7033
7034 boolean killed = false;
7035 synchronized (mPidsSelfLocked) {
7036 final int size = mPidsSelfLocked.size();
7037 for (int i = 0; i < size; i++) {
7038 final int pid = mPidsSelfLocked.keyAt(i);
7039 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7040 if (proc == null) continue;
7041
7042 final int adj = proc.setAdj;
7043 if (adj > belowAdj && !proc.killedBackground) {
7044 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7045 EventLog.writeEvent(
7046 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7047 killed = true;
7048 proc.killedBackground = true;
7049 Process.killProcessQuiet(pid);
7050 }
7051 }
7052 }
7053 return killed;
7054 }
7055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 public final void startRunning(String pkg, String cls, String action,
7057 String data) {
7058 synchronized(this) {
7059 if (mStartRunning) {
7060 return;
7061 }
7062 mStartRunning = true;
7063 mTopComponent = pkg != null && cls != null
7064 ? new ComponentName(pkg, cls) : null;
7065 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7066 mTopData = data;
7067 if (!mSystemReady) {
7068 return;
7069 }
7070 }
7071
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007072 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 }
7074
7075 private void retrieveSettings() {
7076 final ContentResolver resolver = mContext.getContentResolver();
7077 String debugApp = Settings.System.getString(
7078 resolver, Settings.System.DEBUG_APP);
7079 boolean waitForDebugger = Settings.System.getInt(
7080 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7081 boolean alwaysFinishActivities = Settings.System.getInt(
7082 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7083
7084 Configuration configuration = new Configuration();
7085 Settings.System.getConfiguration(resolver, configuration);
7086
7087 synchronized (this) {
7088 mDebugApp = mOrigDebugApp = debugApp;
7089 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7090 mAlwaysFinishActivities = alwaysFinishActivities;
7091 // This happens before any activities are started, so we can
7092 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007093 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007094 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 }
7096 }
7097
7098 public boolean testIsSystemReady() {
7099 // no need to synchronize(this) just to read & return the value
7100 return mSystemReady;
7101 }
7102
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007103 private static File getCalledPreBootReceiversFile() {
7104 File dataDir = Environment.getDataDirectory();
7105 File systemDir = new File(dataDir, "system");
7106 File fname = new File(systemDir, "called_pre_boots.dat");
7107 return fname;
7108 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007109
7110 static final int LAST_DONE_VERSION = 10000;
7111
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007112 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7113 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7114 File file = getCalledPreBootReceiversFile();
7115 FileInputStream fis = null;
7116 try {
7117 fis = new FileInputStream(file);
7118 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007119 int fvers = dis.readInt();
7120 if (fvers == LAST_DONE_VERSION) {
7121 String vers = dis.readUTF();
7122 String codename = dis.readUTF();
7123 String build = dis.readUTF();
7124 if (android.os.Build.VERSION.RELEASE.equals(vers)
7125 && android.os.Build.VERSION.CODENAME.equals(codename)
7126 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7127 int num = dis.readInt();
7128 while (num > 0) {
7129 num--;
7130 String pkg = dis.readUTF();
7131 String cls = dis.readUTF();
7132 lastDoneReceivers.add(new ComponentName(pkg, cls));
7133 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007134 }
7135 }
7136 } catch (FileNotFoundException e) {
7137 } catch (IOException e) {
7138 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7139 } finally {
7140 if (fis != null) {
7141 try {
7142 fis.close();
7143 } catch (IOException e) {
7144 }
7145 }
7146 }
7147 return lastDoneReceivers;
7148 }
7149
7150 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7151 File file = getCalledPreBootReceiversFile();
7152 FileOutputStream fos = null;
7153 DataOutputStream dos = null;
7154 try {
7155 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7156 fos = new FileOutputStream(file);
7157 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007158 dos.writeInt(LAST_DONE_VERSION);
7159 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007160 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007161 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007162 dos.writeInt(list.size());
7163 for (int i=0; i<list.size(); i++) {
7164 dos.writeUTF(list.get(i).getPackageName());
7165 dos.writeUTF(list.get(i).getClassName());
7166 }
7167 } catch (IOException e) {
7168 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7169 file.delete();
7170 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007171 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007172 if (dos != null) {
7173 try {
7174 dos.close();
7175 } catch (IOException e) {
7176 // TODO Auto-generated catch block
7177 e.printStackTrace();
7178 }
7179 }
7180 }
7181 }
7182
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007183 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 synchronized(this) {
7185 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007186 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 return;
7188 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007189
7190 // Check to see if there are any update receivers to run.
7191 if (!mDidUpdate) {
7192 if (mWaitingUpdate) {
7193 return;
7194 }
7195 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7196 List<ResolveInfo> ris = null;
7197 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007198 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007199 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007200 } catch (RemoteException e) {
7201 }
7202 if (ris != null) {
7203 for (int i=ris.size()-1; i>=0; i--) {
7204 if ((ris.get(i).activityInfo.applicationInfo.flags
7205 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7206 ris.remove(i);
7207 }
7208 }
7209 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007210
7211 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7212
7213 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007214 for (int i=0; i<ris.size(); i++) {
7215 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007216 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7217 if (lastDoneReceivers.contains(comp)) {
7218 ris.remove(i);
7219 i--;
7220 }
7221 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007222
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007223 for (int i=0; i<ris.size(); i++) {
7224 ActivityInfo ai = ris.get(i).activityInfo;
7225 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7226 doneReceivers.add(comp);
7227 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007228 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007229 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007230 finisher = new IIntentReceiver.Stub() {
7231 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007232 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007233 boolean sticky) {
7234 // The raw IIntentReceiver interface is called
7235 // with the AM lock held, so redispatch to
7236 // execute our code without the lock.
7237 mHandler.post(new Runnable() {
7238 public void run() {
7239 synchronized (ActivityManagerService.this) {
7240 mDidUpdate = true;
7241 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007242 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007243 showBootMessage(mContext.getText(
7244 R.string.android_upgrading_complete),
7245 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007246 systemReady(goingCallback);
7247 }
7248 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007249 }
7250 };
7251 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007252 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007253 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007254 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007255 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007256 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007257 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007258 mWaitingUpdate = true;
7259 }
7260 }
7261 }
7262 if (mWaitingUpdate) {
7263 return;
7264 }
7265 mDidUpdate = true;
7266 }
7267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007268 mSystemReady = true;
7269 if (!mStartRunning) {
7270 return;
7271 }
7272 }
7273
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007274 ArrayList<ProcessRecord> procsToKill = null;
7275 synchronized(mPidsSelfLocked) {
7276 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7277 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7278 if (!isAllowedWhileBooting(proc.info)){
7279 if (procsToKill == null) {
7280 procsToKill = new ArrayList<ProcessRecord>();
7281 }
7282 procsToKill.add(proc);
7283 }
7284 }
7285 }
7286
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007287 synchronized(this) {
7288 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007289 for (int i=procsToKill.size()-1; i>=0; i--) {
7290 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007291 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007292 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007293 }
7294 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007295
7296 // Now that we have cleaned up any update processes, we
7297 // are ready to start launching real processes and know that
7298 // we won't trample on them any more.
7299 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007300 }
7301
Joe Onorato8a9b2202010-02-26 18:56:32 -08007302 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007303 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007304 SystemClock.uptimeMillis());
7305
7306 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007307 // Make sure we have no pre-ready processes sitting around.
7308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7310 ResolveInfo ri = mContext.getPackageManager()
7311 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007312 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007313 CharSequence errorMsg = null;
7314 if (ri != null) {
7315 ActivityInfo ai = ri.activityInfo;
7316 ApplicationInfo app = ai.applicationInfo;
7317 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7318 mTopAction = Intent.ACTION_FACTORY_TEST;
7319 mTopData = null;
7320 mTopComponent = new ComponentName(app.packageName,
7321 ai.name);
7322 } else {
7323 errorMsg = mContext.getResources().getText(
7324 com.android.internal.R.string.factorytest_not_system);
7325 }
7326 } else {
7327 errorMsg = mContext.getResources().getText(
7328 com.android.internal.R.string.factorytest_no_action);
7329 }
7330 if (errorMsg != null) {
7331 mTopAction = null;
7332 mTopData = null;
7333 mTopComponent = null;
7334 Message msg = Message.obtain();
7335 msg.what = SHOW_FACTORY_ERROR_MSG;
7336 msg.getData().putCharSequence("msg", errorMsg);
7337 mHandler.sendMessage(msg);
7338 }
7339 }
7340 }
7341
7342 retrieveSettings();
7343
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007344 if (goingCallback != null) goingCallback.run();
7345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007346 synchronized (this) {
7347 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7348 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007349 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007350 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 if (apps != null) {
7352 int N = apps.size();
7353 int i;
7354 for (i=0; i<N; i++) {
7355 ApplicationInfo info
7356 = (ApplicationInfo)apps.get(i);
7357 if (info != null &&
7358 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007359 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007360 }
7361 }
7362 }
7363 } catch (RemoteException ex) {
7364 // pm is in same process, this will never happen.
7365 }
7366 }
7367
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007368 // Start up initial activity.
7369 mBooting = true;
7370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007372 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 Message msg = Message.obtain();
7374 msg.what = SHOW_UID_ERROR_MSG;
7375 mHandler.sendMessage(msg);
7376 }
7377 } catch (RemoteException e) {
7378 }
7379
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007380 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007381 }
7382 }
7383
Dan Egnorb7f03672009-12-09 16:22:32 -08007384 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007385 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007386 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007387 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007388 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007389 startAppProblemLocked(app);
7390 app.stopFreezingAllLocked();
7391 return handleAppCrashLocked(app);
7392 }
7393
Dan Egnorb7f03672009-12-09 16:22:32 -08007394 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007395 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007396 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007397 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007398 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7399 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 startAppProblemLocked(app);
7401 app.stopFreezingAllLocked();
7402 }
7403
7404 /**
7405 * Generate a process error record, suitable for attachment to a ProcessRecord.
7406 *
7407 * @param app The ProcessRecord in which the error occurred.
7408 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7409 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007410 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007411 * @param shortMsg Short message describing the crash.
7412 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007413 * @param stackTrace Full crash stack trace, may be null.
7414 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007415 * @return Returns a fully-formed AppErrorStateInfo record.
7416 */
7417 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007418 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007419 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 report.condition = condition;
7422 report.processName = app.processName;
7423 report.pid = app.pid;
7424 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007425 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 report.shortMsg = shortMsg;
7427 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007428 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429
7430 return report;
7431 }
7432
Dan Egnor42471dd2010-01-07 17:25:22 -08007433 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007434 synchronized (this) {
7435 app.crashing = false;
7436 app.crashingReport = null;
7437 app.notResponding = false;
7438 app.notRespondingReport = null;
7439 if (app.anrDialog == fromDialog) {
7440 app.anrDialog = null;
7441 }
7442 if (app.waitDialog == fromDialog) {
7443 app.waitDialog = null;
7444 }
7445 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007446 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007447 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007448 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7449 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007450 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007452 }
7453 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007454
Dan Egnorb7f03672009-12-09 16:22:32 -08007455 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007456 if (mHeadless) {
7457 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7458 return false;
7459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007460 long now = SystemClock.uptimeMillis();
7461
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007462 Long crashTime;
7463 if (!app.isolated) {
7464 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7465 } else {
7466 crashTime = null;
7467 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007468 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007469 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007470 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007472 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007473 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007474 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7475 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007476 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007477 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007478 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007479 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007480 }
7481 }
7482 if (!app.persistent) {
7483 // We don't want to start this process again until the user
7484 // explicitly does so... but for persistent process, we really
7485 // need to keep it running. If a persistent process is actually
7486 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007487 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007489 if (!app.isolated) {
7490 // XXX We don't have a way to mark isolated processes
7491 // as bad, since they don't have a peristent identity.
7492 mBadProcesses.put(app.info.processName, app.uid, now);
7493 mProcessCrashTimes.remove(app.info.processName, app.uid);
7494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007495 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007496 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007497 // Don't let services in this process be restarted and potentially
7498 // annoy the user repeatedly. Unless it is persistent, since those
7499 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007500 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007501 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007502 return false;
7503 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007504 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007505 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007506 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007507 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007508 // If the top running activity is from this crashing
7509 // process, then terminate it to avoid getting in a loop.
7510 Slog.w(TAG, " Force finishing activity "
7511 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007512 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007513 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007514 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007515 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007516 // stopped, to avoid a situation where one will get
7517 // re-start our crashing activity once it gets resumed again.
7518 index--;
7519 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007520 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007521 if (r.state == ActivityState.RESUMED
7522 || r.state == ActivityState.PAUSING
7523 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007524 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007525 Slog.w(TAG, " Force finishing activity "
7526 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007527 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007528 Activity.RESULT_CANCELED, null, "crashed");
7529 }
7530 }
7531 }
7532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 }
7534
7535 // Bump up the crash count of any services currently running in the proc.
7536 if (app.services.size() != 0) {
7537 // Any services running in the application need to be placed
7538 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007539 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007541 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007542 sr.crashCount++;
7543 }
7544 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007545
7546 // If the crashing process is what we consider to be the "home process" and it has been
7547 // replaced by a third-party app, clear the package preferred activities from packages
7548 // with a home activity running in the process to prevent a repeatedly crashing app
7549 // from blocking the user to manually clear the list.
7550 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7551 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7552 Iterator it = mHomeProcess.activities.iterator();
7553 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007554 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007555 if (r.isHomeActivity) {
7556 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7557 try {
7558 ActivityThread.getPackageManager()
7559 .clearPackagePreferredActivities(r.packageName);
7560 } catch (RemoteException c) {
7561 // pm is in same process, this will never happen.
7562 }
7563 }
7564 }
7565 }
7566
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007567 if (!app.isolated) {
7568 // XXX Can't keep track of crash times for isolated processes,
7569 // because they don't have a perisistent identity.
7570 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7571 }
7572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 return true;
7574 }
7575
7576 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007577 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7578 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007579 skipCurrentReceiverLocked(app);
7580 }
7581
7582 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007583 for (BroadcastQueue queue : mBroadcastQueues) {
7584 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007585 }
7586 }
7587
Dan Egnor60d87622009-12-16 16:32:58 -08007588 /**
7589 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7590 * The application process will exit immediately after this call returns.
7591 * @param app object of the crashing app, null for the system server
7592 * @param crashInfo describing the exception
7593 */
7594 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007595 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007596 final String processName = app == null ? "system_server"
7597 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007598
7599 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007600 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007601 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007602 crashInfo.exceptionClassName,
7603 crashInfo.exceptionMessage,
7604 crashInfo.throwFileName,
7605 crashInfo.throwLineNumber);
7606
Jeff Sharkeya353d262011-10-28 11:12:06 -07007607 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007608
7609 crashApplication(r, crashInfo);
7610 }
7611
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007612 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007613 IBinder app,
7614 int violationMask,
7615 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007616 ProcessRecord r = findAppProcess(app, "StrictMode");
7617 if (r == null) {
7618 return;
7619 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007620
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007621 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007622 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007623 boolean logIt = true;
7624 synchronized (mAlreadyLoggedViolatedStacks) {
7625 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7626 logIt = false;
7627 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007628 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007629 // the relative pain numbers, without logging all
7630 // the stack traces repeatedly. We'd want to do
7631 // likewise in the client code, which also does
7632 // dup suppression, before the Binder call.
7633 } else {
7634 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7635 mAlreadyLoggedViolatedStacks.clear();
7636 }
7637 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7638 }
7639 }
7640 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007641 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007642 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007643 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007644
7645 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7646 AppErrorResult result = new AppErrorResult();
7647 synchronized (this) {
7648 final long origId = Binder.clearCallingIdentity();
7649
7650 Message msg = Message.obtain();
7651 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7652 HashMap<String, Object> data = new HashMap<String, Object>();
7653 data.put("result", result);
7654 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007655 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007656 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007657 msg.obj = data;
7658 mHandler.sendMessage(msg);
7659
7660 Binder.restoreCallingIdentity(origId);
7661 }
7662 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007663 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007664 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007665 }
7666
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007667 // Depending on the policy in effect, there could be a bunch of
7668 // these in quick succession so we try to batch these together to
7669 // minimize disk writes, number of dropbox entries, and maximize
7670 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007671 private void logStrictModeViolationToDropBox(
7672 ProcessRecord process,
7673 StrictMode.ViolationInfo info) {
7674 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007675 return;
7676 }
7677 final boolean isSystemApp = process == null ||
7678 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7679 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007680 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007681 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7682 final DropBoxManager dbox = (DropBoxManager)
7683 mContext.getSystemService(Context.DROPBOX_SERVICE);
7684
7685 // Exit early if the dropbox isn't configured to accept this report type.
7686 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7687
7688 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007689 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007690 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7691 synchronized (sb) {
7692 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007693 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007694 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7695 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007696 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7697 if (info.violationNumThisLoop != 0) {
7698 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7699 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007700 if (info.numAnimationsRunning != 0) {
7701 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7702 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007703 if (info.broadcastIntentAction != null) {
7704 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7705 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007706 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007707 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007708 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007709 if (info.numInstances != -1) {
7710 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7711 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007712 if (info.tags != null) {
7713 for (String tag : info.tags) {
7714 sb.append("Span-Tag: ").append(tag).append("\n");
7715 }
7716 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007717 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007718 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7719 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007720 }
7721 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007722
7723 // Only buffer up to ~64k. Various logging bits truncate
7724 // things at 128k.
7725 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007726 }
7727
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007728 // Flush immediately if the buffer's grown too large, or this
7729 // is a non-system app. Non-system apps are isolated with a
7730 // different tag & policy and not batched.
7731 //
7732 // Batching is useful during internal testing with
7733 // StrictMode settings turned up high. Without batching,
7734 // thousands of separate files could be created on boot.
7735 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007736 new Thread("Error dump: " + dropboxTag) {
7737 @Override
7738 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007739 String report;
7740 synchronized (sb) {
7741 report = sb.toString();
7742 sb.delete(0, sb.length());
7743 sb.trimToSize();
7744 }
7745 if (report.length() != 0) {
7746 dbox.addText(dropboxTag, report);
7747 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007748 }
7749 }.start();
7750 return;
7751 }
7752
7753 // System app batching:
7754 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007755 // An existing dropbox-writing thread is outstanding, so
7756 // we don't need to start it up. The existing thread will
7757 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007758 return;
7759 }
7760
7761 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7762 // (After this point, we shouldn't access AMS internal data structures.)
7763 new Thread("Error dump: " + dropboxTag) {
7764 @Override
7765 public void run() {
7766 // 5 second sleep to let stacks arrive and be batched together
7767 try {
7768 Thread.sleep(5000); // 5 seconds
7769 } catch (InterruptedException e) {}
7770
7771 String errorReport;
7772 synchronized (mStrictModeBuffer) {
7773 errorReport = mStrictModeBuffer.toString();
7774 if (errorReport.length() == 0) {
7775 return;
7776 }
7777 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
7778 mStrictModeBuffer.trimToSize();
7779 }
7780 dbox.addText(dropboxTag, errorReport);
7781 }
7782 }.start();
7783 }
7784
Dan Egnor60d87622009-12-16 16:32:58 -08007785 /**
7786 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
7787 * @param app object of the crashing app, null for the system server
7788 * @param tag reported by the caller
7789 * @param crashInfo describing the context of the error
7790 * @return true if the process should exit immediately (WTF is fatal)
7791 */
7792 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08007793 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007794 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007795 final String processName = app == null ? "system_server"
7796 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007797
7798 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007799 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007800 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007801 tag, crashInfo.exceptionMessage);
7802
Jeff Sharkeya353d262011-10-28 11:12:06 -07007803 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007804
Dianne Hackborn1ab43772011-03-15 14:38:02 -07007805 if (r != null && r.pid != Process.myPid() &&
7806 Settings.Secure.getInt(mContext.getContentResolver(),
7807 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08007808 crashApplication(r, crashInfo);
7809 return true;
7810 } else {
7811 return false;
7812 }
7813 }
7814
7815 /**
7816 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
7817 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
7818 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08007819 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08007820 if (app == null) {
7821 return null;
7822 }
7823
7824 synchronized (this) {
7825 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
7826 final int NA = apps.size();
7827 for (int ia=0; ia<NA; ia++) {
7828 ProcessRecord p = apps.valueAt(ia);
7829 if (p.thread != null && p.thread.asBinder() == app) {
7830 return p;
7831 }
7832 }
7833 }
7834
Dianne Hackborncb44d962011-03-10 17:02:27 -08007835 Slog.w(TAG, "Can't find mystery application for " + reason
7836 + " from pid=" + Binder.getCallingPid()
7837 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08007838 return null;
7839 }
7840 }
7841
7842 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007843 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
7844 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08007845 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07007846 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
7847 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007848 // Watchdog thread ends up invoking this function (with
7849 // a null ProcessRecord) to add the stack file to dropbox.
7850 // Do not acquire a lock on this (am) in such cases, as it
7851 // could cause a potential deadlock, if and when watchdog
7852 // is invoked due to unavailability of lock on am and it
7853 // would prevent watchdog from killing system_server.
7854 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007855 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08007856 return;
7857 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07007858 // Note: ProcessRecord 'process' is guarded by the service
7859 // instance. (notably process.pkgList, which could otherwise change
7860 // concurrently during execution of this method)
7861 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07007862 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08007863 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007864 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08007865 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
7866 for (String pkg : process.pkgList) {
7867 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08007868 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07007869 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08007870 if (pi != null) {
7871 sb.append(" v").append(pi.versionCode);
7872 if (pi.versionName != null) {
7873 sb.append(" (").append(pi.versionName).append(")");
7874 }
7875 }
7876 } catch (RemoteException e) {
7877 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08007878 }
Dan Egnora455d192010-03-12 08:52:28 -08007879 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08007880 }
Dan Egnora455d192010-03-12 08:52:28 -08007881 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007882 }
7883
7884 private static String processClass(ProcessRecord process) {
7885 if (process == null || process.pid == MY_PID) {
7886 return "system_server";
7887 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7888 return "system_app";
7889 } else {
7890 return "data_app";
7891 }
7892 }
7893
7894 /**
7895 * Write a description of an error (crash, WTF, ANR) to the drop box.
7896 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
7897 * @param process which caused the error, null means the system server
7898 * @param activity which triggered the error, null if unknown
7899 * @param parent activity related to the error, null if unknown
7900 * @param subject line related to the error, null if absent
7901 * @param report in long form describing the error, null if absent
7902 * @param logFile to include in the report, null if none
7903 * @param crashInfo giving an application stack trace, null if absent
7904 */
7905 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07007906 ProcessRecord process, String processName, ActivityRecord activity,
7907 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007908 final String report, final File logFile,
7909 final ApplicationErrorReport.CrashInfo crashInfo) {
7910 // NOTE -- this must never acquire the ActivityManagerService lock,
7911 // otherwise the watchdog may be prevented from resetting the system.
7912
7913 final String dropboxTag = processClass(process) + "_" + eventType;
7914 final DropBoxManager dbox = (DropBoxManager)
7915 mContext.getSystemService(Context.DROPBOX_SERVICE);
7916
7917 // Exit early if the dropbox isn't configured to accept this report type.
7918 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7919
7920 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07007921 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08007922 if (activity != null) {
7923 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
7924 }
7925 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
7926 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
7927 }
7928 if (parent != null && parent != activity) {
7929 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
7930 }
7931 if (subject != null) {
7932 sb.append("Subject: ").append(subject).append("\n");
7933 }
7934 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02007935 if (Debug.isDebuggerConnected()) {
7936 sb.append("Debugger: Connected\n");
7937 }
Dan Egnora455d192010-03-12 08:52:28 -08007938 sb.append("\n");
7939
7940 // Do the rest in a worker thread to avoid blocking the caller on I/O
7941 // (After this point, we shouldn't access AMS internal data structures.)
7942 Thread worker = new Thread("Error dump: " + dropboxTag) {
7943 @Override
7944 public void run() {
7945 if (report != null) {
7946 sb.append(report);
7947 }
7948 if (logFile != null) {
7949 try {
7950 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
7951 } catch (IOException e) {
7952 Slog.e(TAG, "Error reading " + logFile, e);
7953 }
7954 }
7955 if (crashInfo != null && crashInfo.stackTrace != null) {
7956 sb.append(crashInfo.stackTrace);
7957 }
7958
7959 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
7960 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
7961 if (lines > 0) {
7962 sb.append("\n");
7963
7964 // Merge several logcat streams, and take the last N lines
7965 InputStreamReader input = null;
7966 try {
7967 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
7968 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
7969 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
7970
7971 try { logcat.getOutputStream().close(); } catch (IOException e) {}
7972 try { logcat.getErrorStream().close(); } catch (IOException e) {}
7973 input = new InputStreamReader(logcat.getInputStream());
7974
7975 int num;
7976 char[] buf = new char[8192];
7977 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
7978 } catch (IOException e) {
7979 Slog.e(TAG, "Error running logcat", e);
7980 } finally {
7981 if (input != null) try { input.close(); } catch (IOException e) {}
7982 }
7983 }
7984
7985 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08007986 }
Dan Egnora455d192010-03-12 08:52:28 -08007987 };
7988
7989 if (process == null || process.pid == MY_PID) {
7990 worker.run(); // We may be about to die -- need to run this synchronously
7991 } else {
7992 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08007993 }
7994 }
7995
7996 /**
7997 * Bring up the "unexpected error" dialog box for a crashing app.
7998 * Deal with edge cases (intercepts from instrumented applications,
7999 * ActivityController, error intent receivers, that sort of thing).
8000 * @param r the application crashing
8001 * @param crashInfo describing the failure
8002 */
8003 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008004 long timeMillis = System.currentTimeMillis();
8005 String shortMsg = crashInfo.exceptionClassName;
8006 String longMsg = crashInfo.exceptionMessage;
8007 String stackTrace = crashInfo.stackTrace;
8008 if (shortMsg != null && longMsg != null) {
8009 longMsg = shortMsg + ": " + longMsg;
8010 } else if (shortMsg != null) {
8011 longMsg = shortMsg;
8012 }
8013
Dan Egnor60d87622009-12-16 16:32:58 -08008014 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008016 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008017 try {
8018 String name = r != null ? r.processName : null;
8019 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008020 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008021 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008022 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 + " at watcher's request");
8024 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008025 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 }
8027 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008028 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 }
8030 }
8031
8032 final long origId = Binder.clearCallingIdentity();
8033
8034 // If this process is running instrumentation, finish it.
8035 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008036 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008038 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8039 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 Bundle info = new Bundle();
8041 info.putString("shortMsg", shortMsg);
8042 info.putString("longMsg", longMsg);
8043 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8044 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008045 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008046 }
8047
Dan Egnor60d87622009-12-16 16:32:58 -08008048 // If we can't identify the process or it's already exceeded its crash quota,
8049 // quit right away without showing a crash dialog.
8050 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008051 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008052 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008053 }
8054
8055 Message msg = Message.obtain();
8056 msg.what = SHOW_ERROR_MSG;
8057 HashMap data = new HashMap();
8058 data.put("result", result);
8059 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 msg.obj = data;
8061 mHandler.sendMessage(msg);
8062
8063 Binder.restoreCallingIdentity(origId);
8064 }
8065
8066 int res = result.get();
8067
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008068 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008069 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008070 if (r != null && !r.isolated) {
8071 // XXX Can't keep track of crash time for isolated processes,
8072 // since they don't have a persistent identity.
8073 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 SystemClock.uptimeMillis());
8075 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008076 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008077 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008078 }
8079 }
8080
8081 if (appErrorIntent != null) {
8082 try {
8083 mContext.startActivity(appErrorIntent);
8084 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008085 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008088 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008089
8090 Intent createAppErrorIntentLocked(ProcessRecord r,
8091 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8092 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008093 if (report == null) {
8094 return null;
8095 }
8096 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8097 result.setComponent(r.errorReportReceiver);
8098 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8099 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8100 return result;
8101 }
8102
Dan Egnorb7f03672009-12-09 16:22:32 -08008103 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8104 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008105 if (r.errorReportReceiver == null) {
8106 return null;
8107 }
8108
8109 if (!r.crashing && !r.notResponding) {
8110 return null;
8111 }
8112
Dan Egnorb7f03672009-12-09 16:22:32 -08008113 ApplicationErrorReport report = new ApplicationErrorReport();
8114 report.packageName = r.info.packageName;
8115 report.installerPackageName = r.errorReportReceiver.getPackageName();
8116 report.processName = r.processName;
8117 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008118 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008119
Dan Egnorb7f03672009-12-09 16:22:32 -08008120 if (r.crashing) {
8121 report.type = ApplicationErrorReport.TYPE_CRASH;
8122 report.crashInfo = crashInfo;
8123 } else if (r.notResponding) {
8124 report.type = ApplicationErrorReport.TYPE_ANR;
8125 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008126
Dan Egnorb7f03672009-12-09 16:22:32 -08008127 report.anrInfo.activity = r.notRespondingReport.tag;
8128 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8129 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008130 }
8131
Dan Egnorb7f03672009-12-09 16:22:32 -08008132 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008133 }
8134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008136 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 // assume our apps are happy - lazy create the list
8138 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8139
8140 synchronized (this) {
8141
8142 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008143 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8144 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008145 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8146 // This one's in trouble, so we'll generate a report for it
8147 // crashes are higher priority (in case there's a crash *and* an anr)
8148 ActivityManager.ProcessErrorStateInfo report = null;
8149 if (app.crashing) {
8150 report = app.crashingReport;
8151 } else if (app.notResponding) {
8152 report = app.notRespondingReport;
8153 }
8154
8155 if (report != null) {
8156 if (errList == null) {
8157 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8158 }
8159 errList.add(report);
8160 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008161 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008162 " crashing = " + app.crashing +
8163 " notResponding = " + app.notResponding);
8164 }
8165 }
8166 }
8167 }
8168
8169 return errList;
8170 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008171
8172 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008173 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008174 if (currApp != null) {
8175 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8176 }
8177 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008178 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8179 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008180 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8181 if (currApp != null) {
8182 currApp.lru = 0;
8183 }
8184 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008185 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008186 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8187 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8188 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8189 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8190 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8191 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8192 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8193 } else {
8194 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8195 }
8196 }
8197
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008198 private void fillInProcMemInfo(ProcessRecord app,
8199 ActivityManager.RunningAppProcessInfo outInfo) {
8200 outInfo.pid = app.pid;
8201 outInfo.uid = app.info.uid;
8202 if (mHeavyWeightProcess == app) {
8203 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8204 }
8205 if (app.persistent) {
8206 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8207 }
8208 outInfo.lastTrimLevel = app.trimMemoryLevel;
8209 int adj = app.curAdj;
8210 outInfo.importance = oomAdjToImportance(adj, outInfo);
8211 outInfo.importanceReasonCode = app.adjTypeCode;
8212 }
8213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008214 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008215 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008216 // Lazy instantiation of list
8217 List<ActivityManager.RunningAppProcessInfo> runList = null;
8218 synchronized (this) {
8219 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008220 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8221 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008222 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8223 // Generate process state info for running application
8224 ActivityManager.RunningAppProcessInfo currApp =
8225 new ActivityManager.RunningAppProcessInfo(app.processName,
8226 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008227 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008228 if (app.adjSource instanceof ProcessRecord) {
8229 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008230 currApp.importanceReasonImportance = oomAdjToImportance(
8231 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008232 } else if (app.adjSource instanceof ActivityRecord) {
8233 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008234 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8235 }
8236 if (app.adjTarget instanceof ComponentName) {
8237 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8238 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008239 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008240 // + " lru=" + currApp.lru);
8241 if (runList == null) {
8242 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8243 }
8244 runList.add(currApp);
8245 }
8246 }
8247 }
8248 return runList;
8249 }
8250
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008251 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008252 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008253 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8254 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8255 if (runningApps != null && runningApps.size() > 0) {
8256 Set<String> extList = new HashSet<String>();
8257 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8258 if (app.pkgList != null) {
8259 for (String pkg : app.pkgList) {
8260 extList.add(pkg);
8261 }
8262 }
8263 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008264 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008265 for (String pkg : extList) {
8266 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008267 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008268 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8269 retList.add(info);
8270 }
8271 } catch (RemoteException e) {
8272 }
8273 }
8274 }
8275 return retList;
8276 }
8277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008279 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8280 enforceNotIsolatedCaller("getMyMemoryState");
8281 synchronized (this) {
8282 ProcessRecord proc;
8283 synchronized (mPidsSelfLocked) {
8284 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8285 }
8286 fillInProcMemInfo(proc, outInfo);
8287 }
8288 }
8289
8290 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008292 if (checkCallingPermission(android.Manifest.permission.DUMP)
8293 != PackageManager.PERMISSION_GRANTED) {
8294 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8295 + Binder.getCallingPid()
8296 + ", uid=" + Binder.getCallingUid()
8297 + " without permission "
8298 + android.Manifest.permission.DUMP);
8299 return;
8300 }
8301
8302 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008303 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008304 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008305
8306 int opti = 0;
8307 while (opti < args.length) {
8308 String opt = args[opti];
8309 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8310 break;
8311 }
8312 opti++;
8313 if ("-a".equals(opt)) {
8314 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008315 } else if ("-c".equals(opt)) {
8316 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008317 } else if ("-h".equals(opt)) {
8318 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008319 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008320 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008321 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008322 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8323 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8324 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008325 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008326 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008327 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008328 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008329 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008330 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008331 pw.println(" all: dump all activities");
8332 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008333 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008334 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8335 pw.println(" a partial substring in a component name, a");
8336 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008337 pw.println(" -a: include all available server state.");
8338 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008340 } else {
8341 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008343 }
8344
8345 // Is the caller requesting to dump a particular piece of data?
8346 if (opti < args.length) {
8347 String cmd = args[opti];
8348 opti++;
8349 if ("activities".equals(cmd) || "a".equals(cmd)) {
8350 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008351 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008353 return;
8354 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008355 String[] newArgs;
8356 String name;
8357 if (opti >= args.length) {
8358 name = null;
8359 newArgs = EMPTY_STRING_ARRAY;
8360 } else {
8361 name = args[opti];
8362 opti++;
8363 newArgs = new String[args.length - opti];
8364 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8365 args.length - opti);
8366 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008367 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008368 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008369 }
8370 return;
8371 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008372 String[] newArgs;
8373 String name;
8374 if (opti >= args.length) {
8375 name = null;
8376 newArgs = EMPTY_STRING_ARRAY;
8377 } else {
8378 name = args[opti];
8379 opti++;
8380 newArgs = new String[args.length - opti];
8381 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8382 args.length - opti);
8383 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008384 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008385 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008386 }
8387 return;
8388 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008389 String[] newArgs;
8390 String name;
8391 if (opti >= args.length) {
8392 name = null;
8393 newArgs = EMPTY_STRING_ARRAY;
8394 } else {
8395 name = args[opti];
8396 opti++;
8397 newArgs = new String[args.length - opti];
8398 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8399 args.length - opti);
8400 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008401 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008402 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008403 }
8404 return;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008405 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8406 synchronized (this) {
8407 dumpOomLocked(fd, pw, args, opti, true);
8408 }
8409 return;
Marco Nelissen18cb2872011-11-15 11:19:53 -08008410 } else if ("provider".equals(cmd)) {
8411 String[] newArgs;
8412 String name;
8413 if (opti >= args.length) {
8414 name = null;
8415 newArgs = EMPTY_STRING_ARRAY;
8416 } else {
8417 name = args[opti];
8418 opti++;
8419 newArgs = new String[args.length - opti];
8420 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8421 }
8422 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8423 pw.println("No providers match: " + name);
8424 pw.println("Use -h for help.");
8425 }
8426 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008427 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8428 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008429 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008430 }
8431 return;
8432 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008433 String[] newArgs;
8434 String name;
8435 if (opti >= args.length) {
8436 name = null;
8437 newArgs = EMPTY_STRING_ARRAY;
8438 } else {
8439 name = args[opti];
8440 opti++;
8441 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008442 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8443 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008444 }
8445 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8446 pw.println("No services match: " + name);
8447 pw.println("Use -h for help.");
8448 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008449 return;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008450 } else if ("package".equals(cmd)) {
8451 String[] newArgs;
8452 if (opti >= args.length) {
8453 pw.println("package: no package name specified");
8454 pw.println("Use -h for help.");
8455 return;
8456 } else {
8457 dumpPackage = args[opti];
8458 opti++;
8459 newArgs = new String[args.length - opti];
8460 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8461 args.length - opti);
8462 args = newArgs;
8463 opti = 0;
8464 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008465 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8466 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008467 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008468 }
8469 return;
Dianne Hackborn625ac272010-09-17 18:29:22 -07008470 } else {
8471 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008472 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8473 pw.println("Bad activity command, or no activities match: " + cmd);
8474 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008475 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08008476 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008478 }
8479
8480 // No piece of data specified, dump everything.
8481 synchronized (this) {
8482 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008483 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008484 if (needSep) {
8485 pw.println(" ");
8486 }
8487 if (dumpAll) {
8488 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008489 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008490 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008491 if (needSep) {
8492 pw.println(" ");
8493 }
8494 if (dumpAll) {
8495 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008496 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008497 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008498 if (needSep) {
8499 pw.println(" ");
8500 }
8501 if (dumpAll) {
8502 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008503 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008504 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008505 if (needSep) {
8506 pw.println(" ");
8507 }
8508 if (dumpAll) {
8509 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008510 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008511 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008512 if (needSep) {
8513 pw.println(" ");
8514 }
8515 if (dumpAll) {
8516 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008517 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008518 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008519 }
8520 }
8521
8522 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008523 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008524 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8525 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008526 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8527 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008528 pw.println(" ");
8529 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008530 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8531 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008532 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008534 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008535 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008536 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008537 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008538 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008542 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008544 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8545 pw.println(" ");
8546 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008547 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008548 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008549 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008550 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008551 pw.println(" ");
8552 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008553 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008554 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008557 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008558 if (mMainStack.mPausingActivity != null) {
8559 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008561 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008562 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008563 if (dumpAll) {
8564 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8565 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008566 pw.println(" mDismissKeyguardOnNextActivity: "
8567 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008570 if (mRecentTasks.size() > 0) {
8571 pw.println();
8572 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008573
8574 final int N = mRecentTasks.size();
8575 for (int i=0; i<N; i++) {
8576 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008577 if (dumpPackage != null) {
8578 if (tr.realActivity == null ||
8579 !dumpPackage.equals(tr.realActivity)) {
8580 continue;
8581 }
8582 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008583 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8584 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008585 if (dumpAll) {
8586 mRecentTasks.get(i).dump(pw, " ");
8587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008588 }
8589 }
8590
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008591 if (dumpAll) {
8592 pw.println(" ");
8593 pw.println(" mCurTask: " + mCurTask);
8594 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008595
8596 return true;
8597 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008598
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008599 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008600 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008601 boolean needSep = false;
8602 int numPers = 0;
8603
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008604 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8605
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8608 final int NA = procs.size();
8609 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 ProcessRecord r = procs.valueAt(ia);
8611 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8612 continue;
8613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008614 if (!needSep) {
8615 pw.println(" All known processes:");
8616 needSep = true;
8617 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008618 pw.print(r.persistent ? " *PERS*" : " *APP*");
8619 pw.print(" UID "); pw.print(procs.keyAt(ia));
8620 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008621 r.dump(pw, " ");
8622 if (r.persistent) {
8623 numPers++;
8624 }
8625 }
8626 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008628
8629 if (mIsolatedProcesses.size() > 0) {
8630 if (needSep) pw.println(" ");
8631 needSep = true;
8632 pw.println(" Isolated process list (sorted by uid):");
8633 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8634 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8635 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8636 continue;
8637 }
8638 pw.println(String.format("%sIsolated #%2d: %s",
8639 " ", i, r.toString()));
8640 }
8641 }
8642
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 if (mLruProcesses.size() > 0) {
8644 if (needSep) pw.println(" ");
8645 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008646 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008647 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008648 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008649 needSep = true;
8650 }
8651
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008652 if (dumpAll) {
8653 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008654 boolean printed = false;
8655 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8656 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8657 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8658 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008659 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008660 if (!printed) {
8661 if (needSep) pw.println(" ");
8662 needSep = true;
8663 pw.println(" PID mappings:");
8664 printed = true;
8665 }
8666 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8667 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 }
8669 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008670 }
8671
8672 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008673 synchronized (mPidsSelfLocked) {
8674 boolean printed = false;
8675 for (int i=0; i<mForegroundProcesses.size(); i++) {
8676 ProcessRecord r = mPidsSelfLocked.get(
8677 mForegroundProcesses.valueAt(i).pid);
8678 if (dumpPackage != null && (r == null
8679 || !dumpPackage.equals(r.info.packageName))) {
8680 continue;
8681 }
8682 if (!printed) {
8683 if (needSep) pw.println(" ");
8684 needSep = true;
8685 pw.println(" Foreground Processes:");
8686 printed = true;
8687 }
8688 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8689 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008692 }
8693
8694 if (mPersistentStartingProcesses.size() > 0) {
8695 if (needSep) pw.println(" ");
8696 needSep = true;
8697 pw.println(" Persisent processes that are starting:");
8698 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008699 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 if (mRemovedProcesses.size() > 0) {
8703 if (needSep) pw.println(" ");
8704 needSep = true;
8705 pw.println(" Processes that are being removed:");
8706 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008708 }
8709
8710 if (mProcessesOnHold.size() > 0) {
8711 if (needSep) pw.println(" ");
8712 needSep = true;
8713 pw.println(" Processes that are on old until the system is ready:");
8714 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008715 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008717
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008718 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719
8720 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008721 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008722 long now = SystemClock.uptimeMillis();
8723 for (Map.Entry<String, SparseArray<Long>> procs
8724 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008725 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 SparseArray<Long> uids = procs.getValue();
8727 final int N = uids.size();
8728 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 int puid = uids.keyAt(i);
8730 ProcessRecord r = mProcessNames.get(pname, puid);
8731 if (dumpPackage != null && (r == null
8732 || !dumpPackage.equals(r.info.packageName))) {
8733 continue;
8734 }
8735 if (!printed) {
8736 if (needSep) pw.println(" ");
8737 needSep = true;
8738 pw.println(" Time since processes crashed:");
8739 printed = true;
8740 }
8741 pw.print(" Process "); pw.print(pname);
8742 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008743 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008744 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8745 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008746 }
8747 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008750 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008751 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 for (Map.Entry<String, SparseArray<Long>> procs
8753 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008754 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 SparseArray<Long> uids = procs.getValue();
8756 final int N = uids.size();
8757 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 int puid = uids.keyAt(i);
8759 ProcessRecord r = mProcessNames.get(pname, puid);
8760 if (dumpPackage != null && (r == null
8761 || !dumpPackage.equals(r.info.packageName))) {
8762 continue;
8763 }
8764 if (!printed) {
8765 if (needSep) pw.println(" ");
8766 needSep = true;
8767 pw.println(" Bad processes:");
8768 }
8769 pw.print(" Bad process "); pw.print(pname);
8770 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008771 pw.print(": crashed at time ");
8772 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 }
8774 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008777 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008779 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08008780 if (dumpAll) {
8781 StringBuilder sb = new StringBuilder(128);
8782 sb.append(" mPreviousProcessVisibleTime: ");
8783 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
8784 pw.println(sb);
8785 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07008786 if (mHeavyWeightProcess != null) {
8787 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8788 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008789 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008790 if (dumpAll) {
8791 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07008792 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008793 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008794 for (Map.Entry<String, Integer> entry
8795 : mCompatModePackages.getPackages().entrySet()) {
8796 String pkg = entry.getKey();
8797 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008798 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
8799 continue;
8800 }
8801 if (!printed) {
8802 pw.println(" mScreenCompatPackages:");
8803 printed = true;
8804 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07008805 pw.print(" "); pw.print(pkg); pw.print(": ");
8806 pw.print(mode); pw.println();
8807 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07008808 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008809 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 pw.println(" mSleeping=" + mSleeping + " mShuttingDown=" + mShuttingDown);
8811 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
8812 || mOrigWaitForDebugger) {
8813 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
8814 + " mDebugTransient=" + mDebugTransient
8815 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
8816 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08008817 if (mOpenGlTraceApp != null) {
8818 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
8819 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07008820 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
8821 || mProfileFd != null) {
8822 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
8823 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
8824 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
8825 + mAutoStopProfiler);
8826 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827 if (mAlwaysFinishActivities || mController != null) {
8828 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
8829 + " mController=" + mController);
8830 }
8831 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07008834 + " mProcessesReady=" + mProcessesReady
8835 + " mSystemReady=" + mSystemReady);
8836 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 + " mBooted=" + mBooted
8838 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008839 pw.print(" mLastPowerCheckRealtime=");
8840 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
8841 pw.println("");
8842 pw.print(" mLastPowerCheckUptime=");
8843 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
8844 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008845 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
8846 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07008847 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008848 pw.println(" mNumServiceProcs=" + mNumServiceProcs
8849 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008851
8852 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 }
8854
Dianne Hackborn287952c2010-09-22 22:34:31 -07008855 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008856 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008857 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008859 long now = SystemClock.uptimeMillis();
8860 for (int i=0; i<mProcessesToGc.size(); i++) {
8861 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
8863 continue;
8864 }
8865 if (!printed) {
8866 if (needSep) pw.println(" ");
8867 needSep = true;
8868 pw.println(" Processes that are waiting to GC:");
8869 printed = true;
8870 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008871 pw.print(" Process "); pw.println(proc);
8872 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
8873 pw.print(", last gced=");
8874 pw.print(now-proc.lastRequestedGc);
8875 pw.print(" ms ago, last lowMem=");
8876 pw.print(now-proc.lastLowMemory);
8877 pw.println(" ms ago");
8878
8879 }
8880 }
8881 return needSep;
8882 }
8883
8884 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
8885 int opti, boolean dumpAll) {
8886 boolean needSep = false;
8887
8888 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07008889 if (needSep) pw.println(" ");
8890 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008891 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07008892 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008893 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008894 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
8895 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
8896 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
8897 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
8898 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008899 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008900 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008901 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008902 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07008903 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008904 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07008905
8906 if (needSep) pw.println(" ");
8907 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07008908 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07008909 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008910 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008911 needSep = true;
8912 }
8913
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008914 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008915
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07008917 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07008918 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07008919 if (mHeavyWeightProcess != null) {
8920 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
8921 }
8922
8923 return true;
8924 }
8925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 /**
8927 * There are three ways to call this:
8928 * - no service specified: dump all the services
8929 * - a flattened component name that matched an existing service was specified as the
8930 * first arg: dump that one service
8931 * - the first arg isn't the flattened component name of an existing service:
8932 * dump all services whose component contains the first arg as a substring
8933 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008934 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
8935 int opti, boolean dumpAll) {
8936 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008938 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008939 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008940 try {
8941 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8942 for (UserInfo user : users) {
8943 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8944 services.add(r1);
8945 }
8946 }
8947 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008948 }
8949 }
8950 } else {
8951 ComponentName componentName = name != null
8952 ? ComponentName.unflattenFromString(name) : null;
8953 int objectId = 0;
8954 if (componentName == null) {
8955 // Not a '/' separated full component name; maybe an object ID?
8956 try {
8957 objectId = Integer.parseInt(name, 16);
8958 name = null;
8959 componentName = null;
8960 } catch (RuntimeException e) {
8961 }
8962 }
8963
8964 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07008965 try {
8966 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
8967 for (UserInfo user : users) {
8968 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
8969 if (componentName != null) {
8970 if (r1.name.equals(componentName)) {
8971 services.add(r1);
8972 }
8973 } else if (name != null) {
8974 if (r1.name.flattenToString().contains(name)) {
8975 services.add(r1);
8976 }
8977 } else if (System.identityHashCode(r1) == objectId) {
8978 services.add(r1);
8979 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008980 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07008981 }
Amith Yamasani742a6712011-05-04 14:49:28 -07008982 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008983 }
8984 }
8985 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008986
8987 if (services.size() <= 0) {
8988 return false;
8989 }
8990
8991 boolean needSep = false;
8992 for (int i=0; i<services.size(); i++) {
8993 if (needSep) {
8994 pw.println();
8995 }
8996 needSep = true;
8997 dumpService("", fd, pw, services.get(i), args, dumpAll);
8998 }
8999 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 }
9001
9002 /**
9003 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9004 * there is a thread associated with the service.
9005 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009006 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9007 final ServiceRecord r, String[] args, boolean dumpAll) {
9008 String innerPrefix = prefix + " ";
9009 synchronized (this) {
9010 pw.print(prefix); pw.print("SERVICE ");
9011 pw.print(r.shortName); pw.print(" ");
9012 pw.print(Integer.toHexString(System.identityHashCode(r)));
9013 pw.print(" pid=");
9014 if (r.app != null) pw.println(r.app.pid);
9015 else pw.println("(not running)");
9016 if (dumpAll) {
9017 r.dump(pw, innerPrefix);
9018 }
9019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009021 pw.print(prefix); pw.println(" Client:");
9022 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009024 TransferPipe tp = new TransferPipe();
9025 try {
9026 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9027 tp.setBufferPrefix(prefix + " ");
9028 tp.go(fd);
9029 } finally {
9030 tp.kill();
9031 }
9032 } catch (IOException e) {
9033 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009034 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009035 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 }
9037 }
9038 }
9039
Marco Nelissen18cb2872011-11-15 11:19:53 -08009040 /**
9041 * There are three ways to call this:
9042 * - no provider specified: dump all the providers
9043 * - a flattened component name that matched an existing provider was specified as the
9044 * first arg: dump that one provider
9045 * - the first arg isn't the flattened component name of an existing provider:
9046 * dump all providers whose component contains the first arg as a substring
9047 */
9048 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9049 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009050 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009051 }
9052
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009053 static class ItemMatcher {
9054 ArrayList<ComponentName> components;
9055 ArrayList<String> strings;
9056 ArrayList<Integer> objects;
9057 boolean all;
9058
9059 ItemMatcher() {
9060 all = true;
9061 }
9062
9063 void build(String name) {
9064 ComponentName componentName = ComponentName.unflattenFromString(name);
9065 if (componentName != null) {
9066 if (components == null) {
9067 components = new ArrayList<ComponentName>();
9068 }
9069 components.add(componentName);
9070 all = false;
9071 } else {
9072 int objectId = 0;
9073 // Not a '/' separated full component name; maybe an object ID?
9074 try {
9075 objectId = Integer.parseInt(name, 16);
9076 if (objects == null) {
9077 objects = new ArrayList<Integer>();
9078 }
9079 objects.add(objectId);
9080 all = false;
9081 } catch (RuntimeException e) {
9082 // Not an integer; just do string match.
9083 if (strings == null) {
9084 strings = new ArrayList<String>();
9085 }
9086 strings.add(name);
9087 all = false;
9088 }
9089 }
9090 }
9091
9092 int build(String[] args, int opti) {
9093 for (; opti<args.length; opti++) {
9094 String name = args[opti];
9095 if ("--".equals(name)) {
9096 return opti+1;
9097 }
9098 build(name);
9099 }
9100 return opti;
9101 }
9102
9103 boolean match(Object object, ComponentName comp) {
9104 if (all) {
9105 return true;
9106 }
9107 if (components != null) {
9108 for (int i=0; i<components.size(); i++) {
9109 if (components.get(i).equals(comp)) {
9110 return true;
9111 }
9112 }
9113 }
9114 if (objects != null) {
9115 for (int i=0; i<objects.size(); i++) {
9116 if (System.identityHashCode(object) == objects.get(i)) {
9117 return true;
9118 }
9119 }
9120 }
9121 if (strings != null) {
9122 String flat = comp.flattenToString();
9123 for (int i=0; i<strings.size(); i++) {
9124 if (flat.contains(strings.get(i))) {
9125 return true;
9126 }
9127 }
9128 }
9129 return false;
9130 }
9131 }
9132
Dianne Hackborn625ac272010-09-17 18:29:22 -07009133 /**
9134 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009135 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009136 * - the cmd arg isn't the flattened component name of an existing activity:
9137 * dump all activity whose component contains the cmd as a substring
9138 * - A hex number of the ActivityRecord object instance.
9139 */
9140 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9141 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009142 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009143
9144 if ("all".equals(name)) {
9145 synchronized (this) {
9146 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009147 activities.add(r1);
9148 }
9149 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009150 } else if ("top".equals(name)) {
9151 synchronized (this) {
9152 final int N = mMainStack.mHistory.size();
9153 if (N > 0) {
9154 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9155 }
9156 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009158 ItemMatcher matcher = new ItemMatcher();
9159 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009160
9161 synchronized (this) {
9162 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009163 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009164 activities.add(r1);
9165 }
9166 }
9167 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009168 }
9169
9170 if (activities.size() <= 0) {
9171 return false;
9172 }
9173
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009174 String[] newArgs = new String[args.length - opti];
9175 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9176
Dianne Hackborn30d71892010-12-11 10:37:55 -08009177 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009178 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009179 for (int i=activities.size()-1; i>=0; i--) {
9180 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009181 if (needSep) {
9182 pw.println();
9183 }
9184 needSep = true;
9185 synchronized (this) {
9186 if (lastTask != r.task) {
9187 lastTask = r.task;
9188 pw.print("TASK "); pw.print(lastTask.affinity);
9189 pw.print(" id="); pw.println(lastTask.taskId);
9190 if (dumpAll) {
9191 lastTask.dump(pw, " ");
9192 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009193 }
9194 }
9195 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009196 }
9197 return true;
9198 }
9199
9200 /**
9201 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9202 * there is a thread associated with the activity.
9203 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009204 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009205 final ActivityRecord r, String[] args, boolean dumpAll) {
9206 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009207 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009208 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9209 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9210 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009211 if (r.app != null) pw.println(r.app.pid);
9212 else pw.println("(not running)");
9213 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009214 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009215 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009216 }
9217 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009218 // flush anything that is already in the PrintWriter since the thread is going
9219 // to write to the file descriptor directly
9220 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009221 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009222 TransferPipe tp = new TransferPipe();
9223 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009224 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9225 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009226 tp.go(fd);
9227 } finally {
9228 tp.kill();
9229 }
9230 } catch (IOException e) {
9231 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009232 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009233 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009234 }
9235 }
9236 }
9237
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009238 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009239 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009240 boolean needSep = false;
9241
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009242 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009243 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009244 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009245 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 Iterator it = mRegisteredReceivers.values().iterator();
9247 while (it.hasNext()) {
9248 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009249 if (dumpPackage != null && (r.app == null ||
9250 !dumpPackage.equals(r.app.info.packageName))) {
9251 continue;
9252 }
9253 if (!printed) {
9254 pw.println(" Registered Receivers:");
9255 needSep = true;
9256 printed = true;
9257 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009258 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009259 r.dump(pw, " ");
9260 }
9261 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009262
9263 if (mReceiverResolver.dump(pw, needSep ?
9264 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9265 " ", dumpPackage, false)) {
9266 needSep = true;
9267 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009268 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009269
9270 for (BroadcastQueue q : mBroadcastQueues) {
9271 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009274 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009275
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009276 if (mStickyBroadcasts != null && dumpPackage == null) {
9277 if (needSep) {
9278 pw.println();
9279 }
9280 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009281 pw.println(" Sticky broadcasts:");
9282 StringBuilder sb = new StringBuilder(128);
9283 for (Map.Entry<String, ArrayList<Intent>> ent
9284 : mStickyBroadcasts.entrySet()) {
9285 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009286 if (dumpAll) {
9287 pw.println(":");
9288 ArrayList<Intent> intents = ent.getValue();
9289 final int N = intents.size();
9290 for (int i=0; i<N; i++) {
9291 sb.setLength(0);
9292 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009293 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009294 pw.println(sb.toString());
9295 Bundle bundle = intents.get(i).getExtras();
9296 if (bundle != null) {
9297 pw.print(" ");
9298 pw.println(bundle.toString());
9299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009300 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009301 } else {
9302 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 }
9304 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009305 needSep = true;
9306 }
9307
9308 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009309 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009310 for (BroadcastQueue queue : mBroadcastQueues) {
9311 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9312 + queue.mBroadcastsScheduled);
9313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009314 pw.println(" mHandler:");
9315 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009316 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009318
9319 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 }
9321
Marco Nelissen18cb2872011-11-15 11:19:53 -08009322 /**
9323 * Prints a list of ServiceRecords (dumpsys activity services)
9324 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009325 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009326 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009327 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009328
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009329 ItemMatcher matcher = new ItemMatcher();
9330 matcher.build(args, opti);
9331
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009332 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009333 try {
9334 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9335 for (UserInfo user : users) {
9336 if (mServiceMap.getAllServices(user.id).size() > 0) {
9337 boolean printed = false;
9338 long nowReal = SystemClock.elapsedRealtime();
9339 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9340 user.id).iterator();
9341 needSep = false;
9342 while (it.hasNext()) {
9343 ServiceRecord r = it.next();
9344 if (!matcher.match(r, r.name)) {
9345 continue;
9346 }
9347 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9348 continue;
9349 }
9350 if (!printed) {
9351 pw.println(" Active services:");
9352 printed = true;
9353 }
9354 if (needSep) {
9355 pw.println();
9356 }
9357 pw.print(" * ");
9358 pw.println(r);
9359 if (dumpAll) {
9360 r.dump(pw, " ");
9361 needSep = true;
9362 } else {
9363 pw.print(" app=");
9364 pw.println(r.app);
9365 pw.print(" created=");
9366 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9367 pw.print(" started=");
9368 pw.print(r.startRequested);
9369 pw.print(" connections=");
9370 pw.println(r.connections.size());
9371 if (r.connections.size() > 0) {
9372 pw.println(" Connections:");
9373 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9374 for (int i = 0; i < clist.size(); i++) {
9375 ConnectionRecord conn = clist.get(i);
9376 pw.print(" ");
9377 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009378 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009379 pw.print(" -> ");
9380 ProcessRecord proc = conn.binding.client;
9381 pw.println(proc != null ? proc.toShortString() : "null");
9382 }
9383 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009384 }
9385 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009386 if (dumpClient && r.app != null && r.app.thread != null) {
9387 pw.println(" Client:");
9388 pw.flush();
9389 try {
9390 TransferPipe tp = new TransferPipe();
9391 try {
9392 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9393 r, args);
9394 tp.setBufferPrefix(" ");
9395 // Short timeout, since blocking here can
9396 // deadlock with the application.
9397 tp.go(fd, 2000);
9398 } finally {
9399 tp.kill();
9400 }
9401 } catch (IOException e) {
9402 pw.println(" Failure while dumping the service: " + e);
9403 } catch (RemoteException e) {
9404 pw.println(" Got a RemoteException while dumping the service");
9405 }
9406 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009407 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009408 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009409 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009412 } catch (RemoteException re) {
9413
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009415
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009416 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009417 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009418 for (int i=0; i<mPendingServices.size(); i++) {
9419 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009420 if (!matcher.match(r, r.name)) {
9421 continue;
9422 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009423 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9424 continue;
9425 }
9426 if (!printed) {
9427 if (needSep) pw.println(" ");
9428 needSep = true;
9429 pw.println(" Pending services:");
9430 printed = true;
9431 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009432 pw.print(" * Pending "); pw.println(r);
9433 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009435 needSep = true;
9436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009437
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009438 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009439 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009440 for (int i=0; i<mRestartingServices.size(); i++) {
9441 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009442 if (!matcher.match(r, r.name)) {
9443 continue;
9444 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009445 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9446 continue;
9447 }
9448 if (!printed) {
9449 if (needSep) pw.println(" ");
9450 needSep = true;
9451 pw.println(" Restarting services:");
9452 printed = true;
9453 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009454 pw.print(" * Restarting "); pw.println(r);
9455 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009457 needSep = true;
9458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009459
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009460 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009461 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009462 for (int i=0; i<mStoppingServices.size(); i++) {
9463 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009464 if (!matcher.match(r, r.name)) {
9465 continue;
9466 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009467 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9468 continue;
9469 }
9470 if (!printed) {
9471 if (needSep) pw.println(" ");
9472 needSep = true;
9473 pw.println(" Stopping services:");
9474 printed = true;
9475 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009476 pw.print(" * Stopping "); pw.println(r);
9477 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009478 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 needSep = true;
9480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009481
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009482 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009483 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009484 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009485 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 = mServiceConnections.values().iterator();
9487 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009488 ArrayList<ConnectionRecord> r = it.next();
9489 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009490 ConnectionRecord cr = r.get(i);
9491 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9492 continue;
9493 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009494 if (dumpPackage != null && (cr.binding.client == null
9495 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9496 continue;
9497 }
9498 if (!printed) {
9499 if (needSep) pw.println(" ");
9500 needSep = true;
9501 pw.println(" Connection bindings to services:");
9502 printed = true;
9503 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009504 pw.print(" * "); pw.println(cr);
9505 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009507 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009508 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009509 }
9510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511
9512 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 }
9514
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009516 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009517 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009519 ItemMatcher matcher = new ItemMatcher();
9520 matcher.build(args, opti);
9521
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009522 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009523
9524 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009525
9526 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009527 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009528 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009529 ContentProviderRecord r = mLaunchingProviders.get(i);
9530 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9531 continue;
9532 }
9533 if (!printed) {
9534 if (needSep) pw.println(" ");
9535 needSep = true;
9536 pw.println(" Launching content providers:");
9537 printed = true;
9538 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009539 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009540 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009541 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009542 }
9543
9544 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545 if (needSep) pw.println();
9546 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009547 pw.println("Granted Uri Permissions:");
9548 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9549 int uid = mGrantedUriPermissions.keyAt(i);
9550 HashMap<Uri, UriPermission> perms
9551 = mGrantedUriPermissions.valueAt(i);
9552 pw.print(" * UID "); pw.print(uid);
9553 pw.println(" holds:");
9554 for (UriPermission perm : perms.values()) {
9555 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009556 if (dumpAll) {
9557 perm.dump(pw, " ");
9558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559 }
9560 }
9561 needSep = true;
9562 }
9563
9564 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 }
9566
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009568 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 boolean needSep = false;
9570
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009571 if (mIntentSenderRecords.size() > 0) {
9572 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 Iterator<WeakReference<PendingIntentRecord>> it
9574 = mIntentSenderRecords.values().iterator();
9575 while (it.hasNext()) {
9576 WeakReference<PendingIntentRecord> ref = it.next();
9577 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009578 if (dumpPackage != null && (rec == null
9579 || !dumpPackage.equals(rec.key.packageName))) {
9580 continue;
9581 }
9582 if (!printed) {
9583 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9584 printed = true;
9585 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 needSep = true;
9587 if (rec != null) {
9588 pw.print(" * "); pw.println(rec);
9589 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 } else {
9593 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009594 }
9595 }
9596 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009597
9598 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009599 }
9600
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009601 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009602 String prefix, String label, boolean complete, boolean brief, boolean client,
9603 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 boolean needNL = false;
9606 final String innerPrefix = prefix + " ";
9607 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009608 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009609 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009610 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9611 continue;
9612 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009613 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009614 if (needNL) {
9615 pw.println(" ");
9616 needNL = false;
9617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009618 if (lastTask != r.task) {
9619 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009620 pw.print(prefix);
9621 pw.print(full ? "* " : " ");
9622 pw.println(lastTask);
9623 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009624 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009625 } else if (complete) {
9626 // Complete + brief == give a summary. Isn't that obvious?!?
9627 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009628 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009629 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009630 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009632 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009633 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9634 pw.print(" #"); pw.print(i); pw.print(": ");
9635 pw.println(r);
9636 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009637 r.dump(pw, innerPrefix);
9638 } else if (complete) {
9639 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009640 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009641 if (r.app != null) {
9642 pw.print(innerPrefix); pw.println(r.app);
9643 }
9644 }
9645 if (client && r.app != null && r.app.thread != null) {
9646 // flush anything that is already in the PrintWriter since the thread is going
9647 // to write to the file descriptor directly
9648 pw.flush();
9649 try {
9650 TransferPipe tp = new TransferPipe();
9651 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009652 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9653 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009654 // Short timeout, since blocking here can
9655 // deadlock with the application.
9656 tp.go(fd, 2000);
9657 } finally {
9658 tp.kill();
9659 }
9660 } catch (IOException e) {
9661 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9662 } catch (RemoteException e) {
9663 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9664 }
9665 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009667 }
9668 }
9669
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009670 private static String buildOomTag(String prefix, String space, int val, int base) {
9671 if (val == base) {
9672 if (space == null) return prefix;
9673 return prefix + " ";
9674 }
9675 return prefix + "+" + Integer.toString(val-base);
9676 }
9677
9678 private static final int dumpProcessList(PrintWriter pw,
9679 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 String prefix, String normalLabel, String persistentLabel,
9681 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009683 final int N = list.size()-1;
9684 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009685 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9687 continue;
9688 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009689 pw.println(String.format("%s%s #%2d: %s",
9690 prefix, (r.persistent ? persistentLabel : normalLabel),
9691 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 if (r.persistent) {
9693 numPers++;
9694 }
9695 }
9696 return numPers;
9697 }
9698
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009699 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009700 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009701 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009702 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009703
Dianne Hackborn905577f2011-09-07 18:31:28 -07009704 ArrayList<Pair<ProcessRecord, Integer>> list
9705 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9706 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009707 ProcessRecord r = origList.get(i);
9708 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9709 continue;
9710 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009711 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9712 }
9713
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009714 if (list.size() <= 0) {
9715 return false;
9716 }
9717
Dianne Hackborn905577f2011-09-07 18:31:28 -07009718 Comparator<Pair<ProcessRecord, Integer>> comparator
9719 = new Comparator<Pair<ProcessRecord, Integer>>() {
9720 @Override
9721 public int compare(Pair<ProcessRecord, Integer> object1,
9722 Pair<ProcessRecord, Integer> object2) {
9723 if (object1.first.setAdj != object2.first.setAdj) {
9724 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9725 }
9726 if (object1.second.intValue() != object2.second.intValue()) {
9727 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9728 }
9729 return 0;
9730 }
9731 };
9732
9733 Collections.sort(list, comparator);
9734
Dianne Hackborn287952c2010-09-22 22:34:31 -07009735 final long curRealtime = SystemClock.elapsedRealtime();
9736 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9737 final long curUptime = SystemClock.uptimeMillis();
9738 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9739
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009740 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009741 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009742 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009743 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009744 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009745 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9746 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009747 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9748 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009749 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9750 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009751 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9752 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009753 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009754 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009755 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9756 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9757 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9758 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9759 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9760 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9761 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9762 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009763 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9764 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009765 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9766 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009767 } else {
9768 oomAdj = Integer.toString(r.setAdj);
9769 }
9770 String schedGroup;
9771 switch (r.setSchedGroup) {
9772 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9773 schedGroup = "B";
9774 break;
9775 case Process.THREAD_GROUP_DEFAULT:
9776 schedGroup = "F";
9777 break;
9778 default:
9779 schedGroup = Integer.toString(r.setSchedGroup);
9780 break;
9781 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009782 String foreground;
9783 if (r.foregroundActivities) {
9784 foreground = "A";
9785 } else if (r.foregroundServices) {
9786 foreground = "S";
9787 } else {
9788 foreground = " ";
9789 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009790 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009791 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009792 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9793 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009794 if (r.adjSource != null || r.adjTarget != null) {
9795 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009796 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009797 if (r.adjTarget instanceof ComponentName) {
9798 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9799 } else if (r.adjTarget != null) {
9800 pw.print(r.adjTarget.toString());
9801 } else {
9802 pw.print("{null}");
9803 }
9804 pw.print("<=");
9805 if (r.adjSource instanceof ProcessRecord) {
9806 pw.print("Proc{");
9807 pw.print(((ProcessRecord)r.adjSource).toShortString());
9808 pw.println("}");
9809 } else if (r.adjSource != null) {
9810 pw.println(r.adjSource.toString());
9811 } else {
9812 pw.println("{null}");
9813 }
9814 }
9815 if (inclDetails) {
9816 pw.print(prefix);
9817 pw.print(" ");
9818 pw.print("oom: max="); pw.print(r.maxAdj);
9819 pw.print(" hidden="); pw.print(r.hiddenAdj);
9820 pw.print(" curRaw="); pw.print(r.curRawAdj);
9821 pw.print(" setRaw="); pw.print(r.setRawAdj);
9822 pw.print(" cur="); pw.print(r.curAdj);
9823 pw.print(" set="); pw.println(r.setAdj);
9824 pw.print(prefix);
9825 pw.print(" ");
9826 pw.print("keeping="); pw.print(r.keeping);
9827 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009828 pw.print(" empty="); pw.print(r.empty);
9829 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009830
9831 if (!r.keeping) {
9832 if (r.lastWakeTime != 0) {
9833 long wtime;
9834 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9835 synchronized (stats) {
9836 wtime = stats.getProcessWakeTime(r.info.uid,
9837 r.pid, curRealtime);
9838 }
9839 long timeUsed = wtime - r.lastWakeTime;
9840 pw.print(prefix);
9841 pw.print(" ");
9842 pw.print("keep awake over ");
9843 TimeUtils.formatDuration(realtimeSince, pw);
9844 pw.print(" used ");
9845 TimeUtils.formatDuration(timeUsed, pw);
9846 pw.print(" (");
9847 pw.print((timeUsed*100)/realtimeSince);
9848 pw.println("%)");
9849 }
9850 if (r.lastCpuTime != 0) {
9851 long timeUsed = r.curCpuTime - r.lastCpuTime;
9852 pw.print(prefix);
9853 pw.print(" ");
9854 pw.print("run cpu over ");
9855 TimeUtils.formatDuration(uptimeSince, pw);
9856 pw.print(" used ");
9857 TimeUtils.formatDuration(timeUsed, pw);
9858 pw.print(" (");
9859 pw.print((timeUsed*100)/uptimeSince);
9860 pw.println("%)");
9861 }
9862 }
9863 }
9864 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009865 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009866 }
9867
Dianne Hackbornb437e092011-08-05 17:50:29 -07009868 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009869 ArrayList<ProcessRecord> procs;
9870 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009871 if (args != null && args.length > start
9872 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009873 procs = new ArrayList<ProcessRecord>();
9874 int pid = -1;
9875 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009876 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009877 } catch (NumberFormatException e) {
9878
9879 }
9880 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9881 ProcessRecord proc = mLruProcesses.get(i);
9882 if (proc.pid == pid) {
9883 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009884 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009885 procs.add(proc);
9886 }
9887 }
9888 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009889 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009890 return null;
9891 }
9892 } else {
9893 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9894 }
9895 }
9896 return procs;
9897 }
9898
9899 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9900 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009901 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009902 if (procs == null) {
9903 return;
9904 }
9905
9906 long uptime = SystemClock.uptimeMillis();
9907 long realtime = SystemClock.elapsedRealtime();
9908 pw.println("Applications Graphics Acceleration Info:");
9909 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9910
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009911 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9912 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009913 if (r.thread != null) {
9914 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9915 pw.flush();
9916 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009917 TransferPipe tp = new TransferPipe();
9918 try {
9919 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9920 tp.go(fd);
9921 } finally {
9922 tp.kill();
9923 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009925 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009926 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009927 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009928 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009929 pw.flush();
9930 }
9931 }
9932 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009933 }
9934
Jeff Brown6754ba22011-12-14 20:20:01 -08009935 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9936 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9937 if (procs == null) {
9938 return;
9939 }
9940
9941 pw.println("Applications Database Info:");
9942
9943 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9944 ProcessRecord r = procs.get(i);
9945 if (r.thread != null) {
9946 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
9947 pw.flush();
9948 try {
9949 TransferPipe tp = new TransferPipe();
9950 try {
9951 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
9952 tp.go(fd);
9953 } finally {
9954 tp.kill();
9955 }
9956 } catch (IOException e) {
9957 pw.println("Failure while dumping the app: " + r);
9958 pw.flush();
9959 } catch (RemoteException e) {
9960 pw.println("Got a RemoteException while dumping the app " + r);
9961 pw.flush();
9962 }
9963 }
9964 }
9965 }
9966
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009967 final static class MemItem {
9968 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009969 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009970 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009971 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -07009972 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009973
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009974 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009975 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009976 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009977 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009978 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009979 }
9980 }
9981
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08009982 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -07009983 boolean sort) {
9984 if (sort) {
9985 Collections.sort(items, new Comparator<MemItem>() {
9986 @Override
9987 public int compare(MemItem lhs, MemItem rhs) {
9988 if (lhs.pss < rhs.pss) {
9989 return 1;
9990 } else if (lhs.pss > rhs.pss) {
9991 return -1;
9992 }
9993 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009994 }
Dianne Hackbornb437e092011-08-05 17:50:29 -07009995 });
9996 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009997
9998 for (int i=0; i<items.size(); i++) {
9999 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010000 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010001 if (mi.subitems != null) {
10002 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10003 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010004 }
10005 }
10006
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010007 // These are in KB.
10008 static final long[] DUMP_MEM_BUCKETS = new long[] {
10009 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10010 120*1024, 160*1024, 200*1024,
10011 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10012 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10013 };
10014
Dianne Hackborn672342c2011-11-29 11:29:02 -080010015 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10016 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010017 int start = label.lastIndexOf('.');
10018 if (start >= 0) start++;
10019 else start = 0;
10020 int end = label.length();
10021 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10022 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10023 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10024 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010025 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010026 out.append(label, start, end);
10027 return;
10028 }
10029 }
10030 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010031 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010032 out.append(label, start, end);
10033 }
10034
10035 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10036 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10037 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10038 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10039 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10040 };
10041 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10042 "System", "Persistent", "Foreground",
10043 "Visible", "Perceptible", "Heavy Weight",
10044 "Backup", "A Services", "Home", "Previous",
10045 "B Services", "Background"
10046 };
10047
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010048 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010049 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010050 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010051 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010052 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010053
10054 int opti = 0;
10055 while (opti < args.length) {
10056 String opt = args[opti];
10057 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10058 break;
10059 }
10060 opti++;
10061 if ("-a".equals(opt)) {
10062 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010063 } else if ("--oom".equals(opt)) {
10064 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010065 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010066 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010067 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010068 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010069 pw.println("If [process] is specified it can be the name or ");
10070 pw.println("pid of a specific process to dump.");
10071 return;
10072 } else {
10073 pw.println("Unknown argument: " + opt + "; use -h for help");
10074 }
10075 }
10076
10077 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 if (procs == null) {
10079 return;
10080 }
10081
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010082 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010083 long uptime = SystemClock.uptimeMillis();
10084 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010085
10086 if (procs.size() == 1 || isCheckinRequest) {
10087 dumpAll = true;
10088 }
10089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010090 if (isCheckinRequest) {
10091 // short checkin version
10092 pw.println(uptime + "," + realtime);
10093 pw.flush();
10094 } else {
10095 pw.println("Applications Memory Usage (kB):");
10096 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10097 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010098
Dianne Hackbornb437e092011-08-05 17:50:29 -070010099 String[] innerArgs = new String[args.length-opti];
10100 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10101
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010102 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10103 long nativePss=0, dalvikPss=0, otherPss=0;
10104 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10105
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010106 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10107 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10108 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010109
10110 long totalPss = 0;
10111
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010112 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10113 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010114 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010115 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010116 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10117 pw.flush();
10118 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010119 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120 if (dumpAll) {
10121 try {
10122 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10123 } catch (RemoteException e) {
10124 if (!isCheckinRequest) {
10125 pw.println("Got RemoteException!");
10126 pw.flush();
10127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010128 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010129 } else {
10130 mi = new Debug.MemoryInfo();
10131 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010132 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010133
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010134 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010135 long myTotalPss = mi.getTotalPss();
10136 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010137 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010138 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010139 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010140
10141 nativePss += mi.nativePss;
10142 dalvikPss += mi.dalvikPss;
10143 otherPss += mi.otherPss;
10144 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10145 long mem = mi.getOtherPss(j);
10146 miscPss[j] += mem;
10147 otherPss -= mem;
10148 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010149
10150 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010151 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10152 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010153 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010154 if (oomProcs[oomIndex] == null) {
10155 oomProcs[oomIndex] = new ArrayList<MemItem>();
10156 }
10157 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010158 break;
10159 }
10160 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010162 }
10163 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010164
10165 if (!isCheckinRequest && procs.size() > 1) {
10166 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10167
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010168 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10169 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10170 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010172 String label = Debug.MemoryInfo.getOtherLabel(j);
10173 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010174 }
10175
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10177 for (int j=0; j<oomPss.length; j++) {
10178 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010179 String label = DUMP_MEM_OOM_LABEL[j];
10180 MemItem item = new MemItem(label, label, oomPss[j],
10181 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010182 item.subitems = oomProcs[j];
10183 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184 }
10185 }
10186
Dianne Hackborn672342c2011-11-29 11:29:02 -080010187 if (outTag != null || outStack != null) {
10188 if (outTag != null) {
10189 appendMemBucket(outTag, totalPss, "total", false);
10190 }
10191 if (outStack != null) {
10192 appendMemBucket(outStack, totalPss, "total", true);
10193 }
10194 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010195 for (int i=0; i<oomMems.size(); i++) {
10196 MemItem miCat = oomMems.get(i);
10197 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10198 continue;
10199 }
10200 if (miCat.id < ProcessList.SERVICE_ADJ
10201 || miCat.id == ProcessList.HOME_APP_ADJ
10202 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010203 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10204 outTag.append(" / ");
10205 }
10206 if (outStack != null) {
10207 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10208 if (firstLine) {
10209 outStack.append(":");
10210 firstLine = false;
10211 }
10212 outStack.append("\n\t at ");
10213 } else {
10214 outStack.append("$");
10215 }
10216 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 for (int j=0; j<miCat.subitems.size(); j++) {
10218 MemItem mi = miCat.subitems.get(j);
10219 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010220 if (outTag != null) {
10221 outTag.append(" ");
10222 }
10223 if (outStack != null) {
10224 outStack.append("$");
10225 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010226 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010227 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10228 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10229 }
10230 if (outStack != null) {
10231 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10232 }
10233 }
10234 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10235 outStack.append("(");
10236 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10237 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10238 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10239 outStack.append(":");
10240 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10241 }
10242 }
10243 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010244 }
10245 }
10246 }
10247 }
10248
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010249 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010250 pw.println();
10251 pw.println("Total PSS by process:");
10252 dumpMemItems(pw, " ", procMems, true);
10253 pw.println();
10254 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010255 pw.println("Total PSS by OOM adjustment:");
10256 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010257 if (!oomOnly) {
10258 PrintWriter out = categoryPw != null ? categoryPw : pw;
10259 out.println();
10260 out.println("Total PSS by category:");
10261 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010262 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010263 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010264 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010266 }
10267
10268 /**
10269 * Searches array of arguments for the specified string
10270 * @param args array of argument strings
10271 * @param value value to search for
10272 * @return true if the value is contained in the array
10273 */
10274 private static boolean scanArgs(String[] args, String value) {
10275 if (args != null) {
10276 for (String arg : args) {
10277 if (value.equals(arg)) {
10278 return true;
10279 }
10280 }
10281 }
10282 return false;
10283 }
10284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010285 private final void killServicesLocked(ProcessRecord app,
10286 boolean allowRestart) {
10287 // Report disconnected services.
10288 if (false) {
10289 // XXX we are letting the client link to the service for
10290 // death notifications.
10291 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010292 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010293 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010294 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010295 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010296 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010297 = r.connections.values().iterator();
10298 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010299 ArrayList<ConnectionRecord> cl = jt.next();
10300 for (int i=0; i<cl.size(); i++) {
10301 ConnectionRecord c = cl.get(i);
10302 if (c.binding.client != app) {
10303 try {
10304 //c.conn.connected(r.className, null);
10305 } catch (Exception e) {
10306 // todo: this should be asynchronous!
10307 Slog.w(TAG, "Exception thrown disconnected servce "
10308 + r.shortName
10309 + " from app " + app.processName, e);
10310 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010311 }
10312 }
10313 }
10314 }
10315 }
10316 }
10317 }
10318
10319 // Clean up any connections this application has to other services.
10320 if (app.connections.size() > 0) {
10321 Iterator<ConnectionRecord> it = app.connections.iterator();
10322 while (it.hasNext()) {
10323 ConnectionRecord r = it.next();
10324 removeConnectionLocked(r, app, null);
10325 }
10326 }
10327 app.connections.clear();
10328
10329 if (app.services.size() != 0) {
10330 // Any services running in the application need to be placed
10331 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010332 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010333 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010334 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010335 synchronized (sr.stats.getBatteryStats()) {
10336 sr.stats.stopLaunchedLocked();
10337 }
10338 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010339 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010340 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010341 if (mStoppingServices.remove(sr)) {
10342 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10343 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010344
10345 boolean hasClients = sr.bindings.size() > 0;
10346 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010347 Iterator<IntentBindRecord> bindings
10348 = sr.bindings.values().iterator();
10349 while (bindings.hasNext()) {
10350 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010351 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010352 + ": shouldUnbind=" + b.hasBound);
10353 b.binder = null;
10354 b.requested = b.received = b.hasBound = false;
10355 }
10356 }
10357
Dianne Hackborn070783f2010-12-29 16:46:28 -080010358 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10359 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010360 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010361 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010362 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 sr.crashCount, sr.shortName, app.pid);
10364 bringDownServiceLocked(sr, true);
10365 } else if (!allowRestart) {
10366 bringDownServiceLocked(sr, true);
10367 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010368 boolean canceled = scheduleServiceRestartLocked(sr, true);
10369
10370 // Should the service remain running? Note that in the
10371 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010372 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010373 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10374 if (sr.pendingStarts.size() == 0) {
10375 sr.startRequested = false;
10376 if (!hasClients) {
10377 // Whoops, no reason to restart!
10378 bringDownServiceLocked(sr, true);
10379 }
10380 }
10381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383 }
10384
10385 if (!allowRestart) {
10386 app.services.clear();
10387 }
10388 }
10389
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010390 // Make sure we have no more records on the stopping list.
10391 int i = mStoppingServices.size();
10392 while (i > 0) {
10393 i--;
10394 ServiceRecord sr = mStoppingServices.get(i);
10395 if (sr.app == app) {
10396 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010397 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010398 }
10399 }
10400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010401 app.executingServices.clear();
10402 }
10403
10404 private final void removeDyingProviderLocked(ProcessRecord proc,
10405 ContentProviderRecord cpr) {
10406 synchronized (cpr) {
10407 cpr.launchingApp = null;
10408 cpr.notifyAll();
10409 }
10410
Amith Yamasani742a6712011-05-04 14:49:28 -070010411 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010412 String names[] = cpr.info.authority.split(";");
10413 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010414 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 }
10416
10417 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10418 while (cit.hasNext()) {
10419 ProcessRecord capp = cit.next();
10420 if (!capp.persistent && capp.thread != null
10421 && capp.pid != 0
10422 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010423 Slog.i(TAG, "Kill " + capp.processName
10424 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010425 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010426 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010427 capp.processName, capp.setAdj, "dying provider "
10428 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010429 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 }
10431 }
10432
10433 mLaunchingProviders.remove(cpr);
10434 }
10435
10436 /**
10437 * Main code for cleaning up a process when it has gone away. This is
10438 * called both as a result of the process dying, or directly when stopping
10439 * a process when running in single process mode.
10440 */
10441 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010442 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010444 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 }
10446
Dianne Hackborn36124872009-10-08 16:22:03 -070010447 mProcessesToGc.remove(app);
10448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010449 // Dismiss any open dialogs.
10450 if (app.crashDialog != null) {
10451 app.crashDialog.dismiss();
10452 app.crashDialog = null;
10453 }
10454 if (app.anrDialog != null) {
10455 app.anrDialog.dismiss();
10456 app.anrDialog = null;
10457 }
10458 if (app.waitDialog != null) {
10459 app.waitDialog.dismiss();
10460 app.waitDialog = null;
10461 }
10462
10463 app.crashing = false;
10464 app.notResponding = false;
10465
10466 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010467 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010468 app.thread = null;
10469 app.forcingToForeground = null;
10470 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010471 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010472 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010473 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010474
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010475 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010476
10477 boolean restart = false;
10478
10479 int NL = mLaunchingProviders.size();
10480
10481 // Remove published content providers.
10482 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010483 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010485 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010487 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010488
10489 // See if someone is waiting for this provider... in which
10490 // case we don't remove it, but just let it restart.
10491 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010492 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010493 for (; i<NL; i++) {
10494 if (mLaunchingProviders.get(i) == cpr) {
10495 restart = true;
10496 break;
10497 }
10498 }
10499 } else {
10500 i = NL;
10501 }
10502
10503 if (i >= NL) {
10504 removeDyingProviderLocked(app, cpr);
10505 NL = mLaunchingProviders.size();
10506 }
10507 }
10508 app.pubProviders.clear();
10509 }
10510
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010511 // Take care of any launching providers waiting for this process.
10512 if (checkAppInLaunchingProvidersLocked(app, false)) {
10513 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 // Unregister from connected content providers.
10517 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010518 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010519 while (it.hasNext()) {
10520 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10521 cpr.clients.remove(app);
10522 }
10523 app.conProviders.clear();
10524 }
10525
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010526 // At this point there may be remaining entries in mLaunchingProviders
10527 // where we were the only one waiting, so they are no longer of use.
10528 // Look for these and clean up if found.
10529 // XXX Commented out for now. Trying to figure out a way to reproduce
10530 // the actual situation to identify what is actually going on.
10531 if (false) {
10532 for (int i=0; i<NL; i++) {
10533 ContentProviderRecord cpr = (ContentProviderRecord)
10534 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010535 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010536 synchronized (cpr) {
10537 cpr.launchingApp = null;
10538 cpr.notifyAll();
10539 }
10540 }
10541 }
10542 }
10543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010544 skipCurrentReceiverLocked(app);
10545
10546 // Unregister any receivers.
10547 if (app.receivers.size() > 0) {
10548 Iterator<ReceiverList> it = app.receivers.iterator();
10549 while (it.hasNext()) {
10550 removeReceiverLocked(it.next());
10551 }
10552 app.receivers.clear();
10553 }
10554
Christopher Tate181fafa2009-05-14 11:12:14 -070010555 // If the app is undergoing backup, tell the backup manager about it
10556 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010557 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010558 try {
10559 IBackupManager bm = IBackupManager.Stub.asInterface(
10560 ServiceManager.getService(Context.BACKUP_SERVICE));
10561 bm.agentDisconnected(app.info.packageName);
10562 } catch (RemoteException e) {
10563 // can't happen; backup manager is local
10564 }
10565 }
10566
Jeff Sharkey287bd832011-05-28 19:36:26 -070010567 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010569 // If the caller is restarting this app, then leave it in its
10570 // current lists and let the caller take care of it.
10571 if (restarting) {
10572 return;
10573 }
10574
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010575 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010576 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010578 mProcessNames.remove(app.processName, app.uid);
10579 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010580 if (mHeavyWeightProcess == app) {
10581 mHeavyWeightProcess = null;
10582 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 } else if (!app.removed) {
10585 // This app is persistent, so we need to keep its record around.
10586 // If it is not already on the pending app list, add it there
10587 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010588 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10589 mPersistentStartingProcesses.add(app);
10590 restart = true;
10591 }
10592 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010593 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10594 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010595 mProcessesOnHold.remove(app);
10596
The Android Open Source Project4df24232009-03-05 14:34:35 -080010597 if (app == mHomeProcess) {
10598 mHomeProcess = null;
10599 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010600 if (app == mPreviousProcess) {
10601 mPreviousProcess = null;
10602 }
10603
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010604 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 // We have components that still need to be running in the
10606 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010607 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010608 startProcessLocked(app, "restart", app.processName);
10609 } else if (app.pid > 0 && app.pid != MY_PID) {
10610 // Goodbye!
10611 synchronized (mPidsSelfLocked) {
10612 mPidsSelfLocked.remove(app.pid);
10613 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10614 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010615 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 }
10617 }
10618
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010619 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10620 // Look through the content providers we are waiting to have launched,
10621 // and if any run in this process then either schedule a restart of
10622 // the process or kill the client waiting for it if this process has
10623 // gone bad.
10624 int NL = mLaunchingProviders.size();
10625 boolean restart = false;
10626 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010627 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010628 if (cpr.launchingApp == app) {
10629 if (!alwaysBad && !app.bad) {
10630 restart = true;
10631 } else {
10632 removeDyingProviderLocked(app, cpr);
10633 NL = mLaunchingProviders.size();
10634 }
10635 }
10636 }
10637 return restart;
10638 }
10639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010640 // =========================================================
10641 // SERVICES
10642 // =========================================================
10643
10644 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10645 ActivityManager.RunningServiceInfo info =
10646 new ActivityManager.RunningServiceInfo();
10647 info.service = r.name;
10648 if (r.app != null) {
10649 info.pid = r.app.pid;
10650 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010651 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010652 info.process = r.processName;
10653 info.foreground = r.isForeground;
10654 info.activeSince = r.createTime;
10655 info.started = r.startRequested;
10656 info.clientCount = r.connections.size();
10657 info.crashCount = r.crashCount;
10658 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010659 if (r.isForeground) {
10660 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10661 }
10662 if (r.startRequested) {
10663 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10664 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010665 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010666 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10667 }
10668 if (r.app != null && r.app.persistent) {
10669 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10670 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010671
10672 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10673 for (int i=0; i<connl.size(); i++) {
10674 ConnectionRecord conn = connl.get(i);
10675 if (conn.clientLabel != 0) {
10676 info.clientPackage = conn.binding.client.info.packageName;
10677 info.clientLabel = conn.clientLabel;
10678 return info;
10679 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010680 }
10681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010682 return info;
10683 }
10684
10685 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10686 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010687 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 synchronized (this) {
10689 ArrayList<ActivityManager.RunningServiceInfo> res
10690 = new ArrayList<ActivityManager.RunningServiceInfo>();
10691
Amith Yamasani742a6712011-05-04 14:49:28 -070010692 int userId = UserId.getUserId(Binder.getCallingUid());
10693 if (mServiceMap.getAllServices(userId).size() > 0) {
10694 Iterator<ServiceRecord> it
10695 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 while (it.hasNext() && res.size() < maxNum) {
10697 res.add(makeRunningServiceInfoLocked(it.next()));
10698 }
10699 }
10700
10701 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10702 ServiceRecord r = mRestartingServices.get(i);
10703 ActivityManager.RunningServiceInfo info =
10704 makeRunningServiceInfoLocked(r);
10705 info.restarting = r.nextRestartTime;
10706 res.add(info);
10707 }
10708
10709 return res;
10710 }
10711 }
10712
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010713 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010714 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010715 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010716 int userId = UserId.getUserId(Binder.getCallingUid());
10717 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010718 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010719 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10720 for (int i=0; i<conn.size(); i++) {
10721 if (conn.get(i).clientIntent != null) {
10722 return conn.get(i).clientIntent;
10723 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010724 }
10725 }
10726 }
10727 }
10728 return null;
10729 }
10730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010731 private final ServiceRecord findServiceLocked(ComponentName name,
10732 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010733 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010734 return r == token ? r : null;
10735 }
10736
10737 private final class ServiceLookupResult {
10738 final ServiceRecord record;
10739 final String permission;
10740
10741 ServiceLookupResult(ServiceRecord _record, String _permission) {
10742 record = _record;
10743 permission = _permission;
10744 }
10745 };
10746
10747 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010748 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 ServiceRecord r = null;
10750 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010751 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010752 }
10753 if (r == null) {
10754 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010755 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 }
10757
10758 if (r == null) {
10759 try {
10760 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010761 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010762 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 ServiceInfo sInfo =
10764 rInfo != null ? rInfo.serviceInfo : null;
10765 if (sInfo == null) {
10766 return null;
10767 }
10768
10769 ComponentName name = new ComponentName(
10770 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010771 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 } catch (RemoteException ex) {
10773 // pm is in same process, this will never happen.
10774 }
10775 }
10776 if (r != null) {
10777 int callingPid = Binder.getCallingPid();
10778 int callingUid = Binder.getCallingUid();
10779 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010780 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010782 if (!r.exported) {
10783 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10784 + " from pid=" + callingPid
10785 + ", uid=" + callingUid
10786 + " that is not exported from uid " + r.appInfo.uid);
10787 return new ServiceLookupResult(null, "not exported from uid "
10788 + r.appInfo.uid);
10789 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010790 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 + " from pid=" + callingPid
10792 + ", uid=" + callingUid
10793 + " requires " + r.permission);
10794 return new ServiceLookupResult(null, r.permission);
10795 }
10796 return new ServiceLookupResult(r, null);
10797 }
10798 return null;
10799 }
10800
10801 private class ServiceRestarter implements Runnable {
10802 private ServiceRecord mService;
10803
10804 void setService(ServiceRecord service) {
10805 mService = service;
10806 }
10807
10808 public void run() {
10809 synchronized(ActivityManagerService.this) {
10810 performServiceRestartLocked(mService);
10811 }
10812 }
10813 }
10814
10815 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010816 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010818 if (DEBUG_SERVICE)
10819 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010820 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010822 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010823 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010825 if (r == null) {
10826 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010827 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010829 if (r == null) {
10830 try {
10831 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010832 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010833 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010834 ServiceInfo sInfo =
10835 rInfo != null ? rInfo.serviceInfo : null;
10836 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010837 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010838 ": not found");
10839 return null;
10840 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010841 if (userId > 0) {
10842 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 ComponentName name = new ComponentName(
10845 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010846 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010848 Intent.FilterComparison filter = new Intent.FilterComparison(
10849 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010850 ServiceRestarter res = new ServiceRestarter();
10851 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10852 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10853 synchronized (stats) {
10854 ss = stats.getServiceStatsLocked(
10855 sInfo.applicationInfo.uid, sInfo.packageName,
10856 sInfo.name);
10857 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010858 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010859 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010860 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10861 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862
10863 // Make sure this component isn't in the pending list.
10864 int N = mPendingServices.size();
10865 for (int i=0; i<N; i++) {
10866 ServiceRecord pr = mPendingServices.get(i);
10867 if (pr.name.equals(name)) {
10868 mPendingServices.remove(i);
10869 i--;
10870 N--;
10871 }
10872 }
10873 }
10874 } catch (RemoteException ex) {
10875 // pm is in same process, this will never happen.
10876 }
10877 }
10878 if (r != null) {
10879 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010880 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010881 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010882 if (!r.exported) {
10883 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10884 + " from pid=" + callingPid
10885 + ", uid=" + callingUid
10886 + " that is not exported from uid " + r.appInfo.uid);
10887 return new ServiceLookupResult(null, "not exported from uid "
10888 + r.appInfo.uid);
10889 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010890 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010891 + " from pid=" + callingPid
10892 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 + " requires " + r.permission);
10894 return new ServiceLookupResult(null, r.permission);
10895 }
10896 return new ServiceLookupResult(r, null);
10897 }
10898 return null;
10899 }
10900
Dianne Hackborn287952c2010-09-22 22:34:31 -070010901 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10902 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10903 + why + " of " + r + " in app " + r.app);
10904 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10905 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010906 long now = SystemClock.uptimeMillis();
10907 if (r.executeNesting == 0 && r.app != null) {
10908 if (r.app.executingServices.size() == 0) {
10909 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10910 msg.obj = r.app;
10911 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10912 }
10913 r.app.executingServices.add(r);
10914 }
10915 r.executeNesting++;
10916 r.executingStart = now;
10917 }
10918
10919 private final void sendServiceArgsLocked(ServiceRecord r,
10920 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010921 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 if (N == 0) {
10923 return;
10924 }
10925
Dianne Hackborn39792d22010-08-19 18:01:52 -070010926 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010927 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010928 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010929 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10930 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010931 if (si.intent == null && N > 1) {
10932 // If somehow we got a dummy null intent in the middle,
10933 // then skip it. DO NOT skip a null intent when it is
10934 // the only one in the list -- this is to support the
10935 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010936 continue;
10937 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010938 si.deliveredTime = SystemClock.uptimeMillis();
10939 r.deliveredStarts.add(si);
10940 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010941 if (si.neededGrants != null) {
10942 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10943 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010944 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010945 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010946 if (!oomAdjusted) {
10947 oomAdjusted = true;
10948 updateOomAdjLocked(r.app);
10949 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010950 int flags = 0;
10951 if (si.deliveryCount > 0) {
10952 flags |= Service.START_FLAG_RETRY;
10953 }
10954 if (si.doneExecutingCount > 0) {
10955 flags |= Service.START_FLAG_REDELIVERY;
10956 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010957 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010958 } catch (RemoteException e) {
10959 // Remote process gone... we'll let the normal cleanup take
10960 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010961 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010962 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010963 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010964 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 break;
10966 }
10967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010968 }
10969
10970 private final boolean requestServiceBindingLocked(ServiceRecord r,
10971 IntentBindRecord i, boolean rebind) {
10972 if (r.app == null || r.app.thread == null) {
10973 // If service is not currently running, can't yet bind.
10974 return false;
10975 }
10976 if ((!i.requested || rebind) && i.apps.size() > 0) {
10977 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070010978 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
10980 if (!rebind) {
10981 i.requested = true;
10982 }
10983 i.hasBound = true;
10984 i.doRebind = false;
10985 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010986 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010987 return false;
10988 }
10989 }
10990 return true;
10991 }
10992
10993 private final void requestServiceBindingsLocked(ServiceRecord r) {
10994 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
10995 while (bindings.hasNext()) {
10996 IntentBindRecord i = bindings.next();
10997 if (!requestServiceBindingLocked(r, i, false)) {
10998 break;
10999 }
11000 }
11001 }
11002
11003 private final void realStartServiceLocked(ServiceRecord r,
11004 ProcessRecord app) throws RemoteException {
11005 if (app.thread == null) {
11006 throw new RemoteException();
11007 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011008 if (DEBUG_MU)
11009 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011010 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011012 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013
11014 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011015 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011016 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017
11018 boolean created = false;
11019 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011020 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011021 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011022 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011024 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011025 synchronized (r.stats.getBatteryStats()) {
11026 r.stats.startLaunchedLocked();
11027 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011028 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011029 app.thread.scheduleCreateService(r, r.serviceInfo,
11030 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011031 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 created = true;
11033 } finally {
11034 if (!created) {
11035 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011036 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 }
11038 }
11039
11040 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011041
11042 // If the service is in the started state, and there are no
11043 // pending arguments, then fake up one so its onStartCommand() will
11044 // be called.
11045 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011046 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011047 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011048 }
11049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 sendServiceArgsLocked(r, true);
11051 }
11052
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011053 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11054 boolean allowCancel) {
11055 boolean canceled = false;
11056
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011057 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011058 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011059 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011060
Dianne Hackborn070783f2010-12-29 16:46:28 -080011061 if ((r.serviceInfo.applicationInfo.flags
11062 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11063 minDuration /= 4;
11064 }
11065
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011066 // Any delivered but not yet finished starts should be put back
11067 // on the pending list.
11068 final int N = r.deliveredStarts.size();
11069 if (N > 0) {
11070 for (int i=N-1; i>=0; i--) {
11071 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011072 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011073 if (si.intent == null) {
11074 // We'll generate this again if needed.
11075 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11076 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11077 r.pendingStarts.add(0, si);
11078 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11079 dur *= 2;
11080 if (minDuration < dur) minDuration = dur;
11081 if (resetTime < dur) resetTime = dur;
11082 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011083 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011084 + r.name);
11085 canceled = true;
11086 }
11087 }
11088 r.deliveredStarts.clear();
11089 }
11090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011091 r.totalRestartCount++;
11092 if (r.restartDelay == 0) {
11093 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011094 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 } else {
11096 // If it has been a "reasonably long time" since the service
11097 // was started, then reset our restart duration back to
11098 // the beginning, so we don't infinitely increase the duration
11099 // on a service that just occasionally gets killed (which is
11100 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011101 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011102 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011103 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011104 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011105 if ((r.serviceInfo.applicationInfo.flags
11106 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11107 // Services in peristent processes will restart much more
11108 // quickly, since they are pretty important. (Think SystemUI).
11109 r.restartDelay += minDuration/2;
11110 } else {
11111 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11112 if (r.restartDelay < minDuration) {
11113 r.restartDelay = minDuration;
11114 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 }
11117 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011118
11119 r.nextRestartTime = now + r.restartDelay;
11120
11121 // Make sure that we don't end up restarting a bunch of services
11122 // all at the same time.
11123 boolean repeat;
11124 do {
11125 repeat = false;
11126 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11127 ServiceRecord r2 = mRestartingServices.get(i);
11128 if (r2 != r && r.nextRestartTime
11129 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11130 && r.nextRestartTime
11131 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11132 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11133 r.restartDelay = r.nextRestartTime - now;
11134 repeat = true;
11135 break;
11136 }
11137 }
11138 } while (repeat);
11139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 if (!mRestartingServices.contains(r)) {
11141 mRestartingServices.add(r);
11142 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011143
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011144 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011147 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011149 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011151 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152 r.shortName, r.restartDelay);
11153
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011154 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011155 }
11156
11157 final void performServiceRestartLocked(ServiceRecord r) {
11158 if (!mRestartingServices.contains(r)) {
11159 return;
11160 }
11161 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11162 }
11163
11164 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11165 if (r.restartDelay == 0) {
11166 return false;
11167 }
11168 r.resetRestartCounter();
11169 mRestartingServices.remove(r);
11170 mHandler.removeCallbacks(r.restarter);
11171 return true;
11172 }
11173
11174 private final boolean bringUpServiceLocked(ServiceRecord r,
11175 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011176 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011177 //r.dump(" ");
11178
Dianne Hackborn36124872009-10-08 16:22:03 -070011179 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011180 sendServiceArgsLocked(r, false);
11181 return true;
11182 }
11183
11184 if (!whileRestarting && r.restartDelay > 0) {
11185 // If waiting for a restart, then do nothing.
11186 return true;
11187 }
11188
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011189 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011190
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011191 // We are now bringing the service up, so no longer in the
11192 // restarting state.
11193 mRestartingServices.remove(r);
11194
Dianne Hackborne7f97212011-02-24 14:40:20 -080011195 // Service is now being launched, its package can't be stopped.
11196 try {
11197 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011198 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011199 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011200 } catch (IllegalArgumentException e) {
11201 Slog.w(TAG, "Failed trying to unstop package "
11202 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011203 }
11204
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011205 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011206 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011207 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011209 if (!isolated) {
11210 app = getProcessRecordLocked(appName, r.appInfo.uid);
11211 if (DEBUG_MU)
11212 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11213 if (app != null && app.thread != null) {
11214 try {
11215 app.addPackage(r.appInfo.packageName);
11216 realStartServiceLocked(r, app);
11217 return true;
11218 } catch (RemoteException e) {
11219 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11220 }
11221
11222 // If a dead object exception was thrown -- fall through to
11223 // restart the application.
11224 }
11225 } else {
11226 // If this service runs in an isolated process, then each time
11227 // we call startProcessLocked() we will get a new isolated
11228 // process, starting another process if we are currently waiting
11229 // for a previous process to come up. To deal with this, we store
11230 // in the service any current isolated process it is running in or
11231 // waiting to have come up.
11232 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011233 }
11234
Dianne Hackborn36124872009-10-08 16:22:03 -070011235 // Not running -- get it started, and enqueue this service record
11236 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011237 if (app == null) {
11238 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11239 "service", r.name, false, isolated)) == null) {
11240 Slog.w(TAG, "Unable to launch app "
11241 + r.appInfo.packageName + "/"
11242 + r.appInfo.uid + " for service "
11243 + r.intent.getIntent() + ": process is bad");
11244 bringDownServiceLocked(r, true);
11245 return false;
11246 }
11247 if (isolated) {
11248 r.isolatedProc = app;
11249 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011250 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011253 mPendingServices.add(r);
11254 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 return true;
11257 }
11258
11259 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011260 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011261 //r.dump(" ");
11262
11263 // Does it still need to run?
11264 if (!force && r.startRequested) {
11265 return;
11266 }
11267 if (r.connections.size() > 0) {
11268 if (!force) {
11269 // XXX should probably keep a count of the number of auto-create
11270 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011273 ArrayList<ConnectionRecord> cr = it.next();
11274 for (int i=0; i<cr.size(); i++) {
11275 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11276 return;
11277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 }
11279 }
11280 }
11281
11282 // Report to all of the connections that the service is no longer
11283 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011284 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011285 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011286 ArrayList<ConnectionRecord> c = it.next();
11287 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011288 ConnectionRecord cr = c.get(i);
11289 // There is still a connection to the service that is
11290 // being brought down. Mark it as dead.
11291 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011292 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011293 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011294 } catch (Exception e) {
11295 Slog.w(TAG, "Failure disconnecting service " + r.name +
11296 " to connection " + c.get(i).conn.asBinder() +
11297 " (in " + c.get(i).binding.client.processName + ")", e);
11298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299 }
11300 }
11301 }
11302
11303 // Tell the service that it has been unbound.
11304 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11305 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11306 while (it.hasNext()) {
11307 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011308 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 + ": hasBound=" + ibr.hasBound);
11310 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11311 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011312 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 updateOomAdjLocked(r.app);
11314 ibr.hasBound = false;
11315 r.app.thread.scheduleUnbindService(r,
11316 ibr.intent.getIntent());
11317 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011318 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011319 + r.shortName, e);
11320 serviceDoneExecutingLocked(r, true);
11321 }
11322 }
11323 }
11324 }
11325
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011326 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011327 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 System.identityHashCode(r), r.shortName,
11329 (r.app != null) ? r.app.pid : -1);
11330
Amith Yamasani742a6712011-05-04 14:49:28 -070011331 mServiceMap.removeServiceByName(r.name, r.userId);
11332 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 r.totalRestartCount = 0;
11334 unscheduleServiceRestartLocked(r);
11335
11336 // Also make sure it is not on the pending list.
11337 int N = mPendingServices.size();
11338 for (int i=0; i<N; i++) {
11339 if (mPendingServices.get(i) == r) {
11340 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011341 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 i--;
11343 N--;
11344 }
11345 }
11346
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011347 r.cancelNotification();
11348 r.isForeground = false;
11349 r.foregroundId = 0;
11350 r.foregroundNoti = null;
11351
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011352 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011353 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011354 r.pendingStarts.clear();
11355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 if (r.app != null) {
11357 synchronized (r.stats.getBatteryStats()) {
11358 r.stats.stopLaunchedLocked();
11359 }
11360 r.app.services.remove(r);
11361 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011363 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011364 mStoppingServices.add(r);
11365 updateOomAdjLocked(r.app);
11366 r.app.thread.scheduleStopService(r);
11367 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011368 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 + r.shortName, e);
11370 serviceDoneExecutingLocked(r, true);
11371 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011372 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011373 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011374 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011375 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011376 }
11377 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011378 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011379 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011380 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011381
11382 if (r.bindings.size() > 0) {
11383 r.bindings.clear();
11384 }
11385
11386 if (r.restarter instanceof ServiceRestarter) {
11387 ((ServiceRestarter)r.restarter).setService(null);
11388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 }
11390
11391 ComponentName startServiceLocked(IApplicationThread caller,
11392 Intent service, String resolvedType,
11393 int callingPid, int callingUid) {
11394 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011395 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 + " type=" + resolvedType + " args=" + service.getExtras());
11397
11398 if (caller != null) {
11399 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11400 if (callerApp == null) {
11401 throw new SecurityException(
11402 "Unable to find app for caller " + caller
11403 + " (pid=" + Binder.getCallingPid()
11404 + ") when starting service " + service);
11405 }
11406 }
11407
11408 ServiceLookupResult res =
11409 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011410 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 if (res == null) {
11412 return null;
11413 }
11414 if (res.record == null) {
11415 return new ComponentName("!", res.permission != null
11416 ? res.permission : "private to package");
11417 }
11418 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011419 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11420 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011421 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011422 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011423 }
11424 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011425 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011426 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011427 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 r.lastActivity = SystemClock.uptimeMillis();
11429 synchronized (r.stats.getBatteryStats()) {
11430 r.stats.startRunningLocked();
11431 }
11432 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11433 return new ComponentName("!", "Service process is bad");
11434 }
11435 return r.name;
11436 }
11437 }
11438
11439 public ComponentName startService(IApplicationThread caller, Intent service,
11440 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011441 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011442 // Refuse possible leaked file descriptors
11443 if (service != null && service.hasFileDescriptors() == true) {
11444 throw new IllegalArgumentException("File descriptors passed in Intent");
11445 }
11446
Amith Yamasani742a6712011-05-04 14:49:28 -070011447 if (DEBUG_SERVICE)
11448 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 synchronized(this) {
11450 final int callingPid = Binder.getCallingPid();
11451 final int callingUid = Binder.getCallingUid();
11452 final long origId = Binder.clearCallingIdentity();
11453 ComponentName res = startServiceLocked(caller, service,
11454 resolvedType, callingPid, callingUid);
11455 Binder.restoreCallingIdentity(origId);
11456 return res;
11457 }
11458 }
11459
11460 ComponentName startServiceInPackage(int uid,
11461 Intent service, String resolvedType) {
11462 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011463 if (DEBUG_SERVICE)
11464 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 final long origId = Binder.clearCallingIdentity();
11466 ComponentName res = startServiceLocked(null, service,
11467 resolvedType, -1, uid);
11468 Binder.restoreCallingIdentity(origId);
11469 return res;
11470 }
11471 }
11472
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011473 private void stopServiceLocked(ServiceRecord service) {
11474 synchronized (service.stats.getBatteryStats()) {
11475 service.stats.stopRunningLocked();
11476 }
11477 service.startRequested = false;
11478 service.callStart = false;
11479 bringDownServiceLocked(service, false);
11480 }
11481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 public int stopService(IApplicationThread caller, Intent service,
11483 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011484 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011485 // Refuse possible leaked file descriptors
11486 if (service != null && service.hasFileDescriptors() == true) {
11487 throw new IllegalArgumentException("File descriptors passed in Intent");
11488 }
11489
11490 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011491 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 + " type=" + resolvedType);
11493
11494 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11495 if (caller != null && callerApp == null) {
11496 throw new SecurityException(
11497 "Unable to find app for caller " + caller
11498 + " (pid=" + Binder.getCallingPid()
11499 + ") when stopping service " + service);
11500 }
11501
11502 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011503 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11504 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 if (r != null) {
11506 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011507 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011508 try {
11509 stopServiceLocked(r.record);
11510 } finally {
11511 Binder.restoreCallingIdentity(origId);
11512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011513 return 1;
11514 }
11515 return -1;
11516 }
11517 }
11518
11519 return 0;
11520 }
11521
11522 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011523 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 // Refuse possible leaked file descriptors
11525 if (service != null && service.hasFileDescriptors() == true) {
11526 throw new IllegalArgumentException("File descriptors passed in Intent");
11527 }
11528
11529 IBinder ret = null;
11530
11531 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011532 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11533 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011534
11535 if (r != null) {
11536 // r.record is null if findServiceLocked() failed the caller permission check
11537 if (r.record == null) {
11538 throw new SecurityException(
11539 "Permission Denial: Accessing service " + r.record.name
11540 + " from pid=" + Binder.getCallingPid()
11541 + ", uid=" + Binder.getCallingUid()
11542 + " requires " + r.permission);
11543 }
11544 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11545 if (ib != null) {
11546 ret = ib.binder;
11547 }
11548 }
11549 }
11550
11551 return ret;
11552 }
11553
11554 public boolean stopServiceToken(ComponentName className, IBinder token,
11555 int startId) {
11556 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011557 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 + " " + token + " startId=" + startId);
11559 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011560 if (r != null) {
11561 if (startId >= 0) {
11562 // Asked to only stop if done with all work. Note that
11563 // to avoid leaks, we will take this as dropping all
11564 // start items up to and including this one.
11565 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11566 if (si != null) {
11567 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011568 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11569 cur.removeUriPermissionsLocked();
11570 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011571 break;
11572 }
11573 }
11574 }
11575
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011576 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011577 return false;
11578 }
11579
11580 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011581 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011582 + " is last, but have " + r.deliveredStarts.size()
11583 + " remaining args");
11584 }
11585 }
11586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011587 synchronized (r.stats.getBatteryStats()) {
11588 r.stats.stopRunningLocked();
11589 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011590 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011591 }
11592 final long origId = Binder.clearCallingIdentity();
11593 bringDownServiceLocked(r, false);
11594 Binder.restoreCallingIdentity(origId);
11595 return true;
11596 }
11597 }
11598 return false;
11599 }
11600
11601 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011602 int id, Notification notification, boolean removeNotification) {
11603 final long origId = Binder.clearCallingIdentity();
11604 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 synchronized(this) {
11606 ServiceRecord r = findServiceLocked(className, token);
11607 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011608 if (id != 0) {
11609 if (notification == null) {
11610 throw new IllegalArgumentException("null notification");
11611 }
11612 if (r.foregroundId != id) {
11613 r.cancelNotification();
11614 r.foregroundId = id;
11615 }
11616 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11617 r.foregroundNoti = notification;
11618 r.isForeground = true;
11619 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 if (r.app != null) {
11621 updateServiceForegroundLocked(r.app, true);
11622 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011623 } else {
11624 if (r.isForeground) {
11625 r.isForeground = false;
11626 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011627 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011628 updateServiceForegroundLocked(r.app, true);
11629 }
11630 }
11631 if (removeNotification) {
11632 r.cancelNotification();
11633 r.foregroundId = 0;
11634 r.foregroundNoti = null;
11635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 }
11637 }
11638 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011639 } finally {
11640 Binder.restoreCallingIdentity(origId);
11641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 }
11643
11644 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11645 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011646 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 if (sr.isForeground) {
11648 anyForeground = true;
11649 break;
11650 }
11651 }
11652 if (anyForeground != proc.foregroundServices) {
11653 proc.foregroundServices = anyForeground;
11654 if (oomAdj) {
11655 updateOomAdjLocked();
11656 }
11657 }
11658 }
11659
11660 public int bindService(IApplicationThread caller, IBinder token,
11661 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011662 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011663 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 // Refuse possible leaked file descriptors
11665 if (service != null && service.hasFileDescriptors() == true) {
11666 throw new IllegalArgumentException("File descriptors passed in Intent");
11667 }
11668
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011669 checkValidCaller(Binder.getCallingUid(), userId);
11670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011672 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011673 + " type=" + resolvedType + " conn=" + connection.asBinder()
11674 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011675 if (DEBUG_MU)
11676 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11677 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011678 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11679 if (callerApp == null) {
11680 throw new SecurityException(
11681 "Unable to find app for caller " + caller
11682 + " (pid=" + Binder.getCallingPid()
11683 + ") when binding service " + service);
11684 }
11685
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011686 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011688 activity = mMainStack.isInStackLocked(token);
11689 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011690 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011691 return 0;
11692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011693 }
11694
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011695 int clientLabel = 0;
11696 PendingIntent clientIntent = null;
11697
11698 if (callerApp.info.uid == Process.SYSTEM_UID) {
11699 // Hacky kind of thing -- allow system stuff to tell us
11700 // what they are, so we can report this elsewhere for
11701 // others to know why certain services are running.
11702 try {
11703 clientIntent = (PendingIntent)service.getParcelableExtra(
11704 Intent.EXTRA_CLIENT_INTENT);
11705 } catch (RuntimeException e) {
11706 }
11707 if (clientIntent != null) {
11708 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11709 if (clientLabel != 0) {
11710 // There are no useful extras in the intent, trash them.
11711 // System code calling with this stuff just needs to know
11712 // this will happen.
11713 service = service.cloneFilter();
11714 }
11715 }
11716 }
11717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 ServiceLookupResult res =
11719 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011720 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011721 if (res == null) {
11722 return 0;
11723 }
11724 if (res.record == null) {
11725 return -1;
11726 }
11727 ServiceRecord s = res.record;
11728
11729 final long origId = Binder.clearCallingIdentity();
11730
11731 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011732 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011733 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 }
11735
11736 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11737 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011738 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739
11740 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011741 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11742 if (clist == null) {
11743 clist = new ArrayList<ConnectionRecord>();
11744 s.connections.put(binder, clist);
11745 }
11746 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011747 b.connections.add(c);
11748 if (activity != null) {
11749 if (activity.connections == null) {
11750 activity.connections = new HashSet<ConnectionRecord>();
11751 }
11752 activity.connections.add(c);
11753 }
11754 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011755 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11756 b.client.hasAboveClient = true;
11757 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011758 clist = mServiceConnections.get(binder);
11759 if (clist == null) {
11760 clist = new ArrayList<ConnectionRecord>();
11761 mServiceConnections.put(binder, clist);
11762 }
11763 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011764
11765 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11766 s.lastActivity = SystemClock.uptimeMillis();
11767 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11768 return 0;
11769 }
11770 }
11771
11772 if (s.app != null) {
11773 // This could have made the service more important.
11774 updateOomAdjLocked(s.app);
11775 }
11776
Joe Onorato8a9b2202010-02-26 18:56:32 -080011777 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 + ": received=" + b.intent.received
11779 + " apps=" + b.intent.apps.size()
11780 + " doRebind=" + b.intent.doRebind);
11781
11782 if (s.app != null && b.intent.received) {
11783 // Service is already running, so we can immediately
11784 // publish the connection.
11785 try {
11786 c.conn.connected(s.name, b.intent.binder);
11787 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011788 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011789 + " to connection " + c.conn.asBinder()
11790 + " (in " + c.binding.client.processName + ")", e);
11791 }
11792
11793 // If this is the first app connected back to this binding,
11794 // and the service had previously asked to be told when
11795 // rebound, then do so.
11796 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11797 requestServiceBindingLocked(s, b.intent, true);
11798 }
11799 } else if (!b.intent.requested) {
11800 requestServiceBindingLocked(s, b.intent, false);
11801 }
11802
11803 Binder.restoreCallingIdentity(origId);
11804 }
11805
11806 return 1;
11807 }
11808
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011809 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011810 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011811 IBinder binder = c.conn.asBinder();
11812 AppBindRecord b = c.binding;
11813 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011814 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11815 if (clist != null) {
11816 clist.remove(c);
11817 if (clist.size() == 0) {
11818 s.connections.remove(binder);
11819 }
11820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011821 b.connections.remove(c);
11822 if (c.activity != null && c.activity != skipAct) {
11823 if (c.activity.connections != null) {
11824 c.activity.connections.remove(c);
11825 }
11826 }
11827 if (b.client != skipApp) {
11828 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011829 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11830 b.client.updateHasAboveClientLocked();
11831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011833 clist = mServiceConnections.get(binder);
11834 if (clist != null) {
11835 clist.remove(c);
11836 if (clist.size() == 0) {
11837 mServiceConnections.remove(binder);
11838 }
11839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011840
11841 if (b.connections.size() == 0) {
11842 b.intent.apps.remove(b.client);
11843 }
11844
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011845 if (!c.serviceDead) {
11846 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11847 + ": shouldUnbind=" + b.intent.hasBound);
11848 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11849 && b.intent.hasBound) {
11850 try {
11851 bumpServiceExecutingLocked(s, "unbind");
11852 updateOomAdjLocked(s.app);
11853 b.intent.hasBound = false;
11854 // Assume the client doesn't want to know about a rebind;
11855 // we will deal with that later if it asks for one.
11856 b.intent.doRebind = false;
11857 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11858 } catch (Exception e) {
11859 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11860 serviceDoneExecutingLocked(s, true);
11861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011862 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011863
11864 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11865 bringDownServiceLocked(s, false);
11866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011867 }
11868 }
11869
11870 public boolean unbindService(IServiceConnection connection) {
11871 synchronized (this) {
11872 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011873 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011874 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11875 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011876 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 + connection.asBinder());
11878 return false;
11879 }
11880
11881 final long origId = Binder.clearCallingIdentity();
11882
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011883 while (clist.size() > 0) {
11884 ConnectionRecord r = clist.get(0);
11885 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011887 if (r.binding.service.app != null) {
11888 // This could have made the service less important.
11889 updateOomAdjLocked(r.binding.service.app);
11890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 }
11892
11893 Binder.restoreCallingIdentity(origId);
11894 }
11895
11896 return true;
11897 }
11898
11899 public void publishService(IBinder token, Intent intent, IBinder service) {
11900 // Refuse possible leaked file descriptors
11901 if (intent != null && intent.hasFileDescriptors() == true) {
11902 throw new IllegalArgumentException("File descriptors passed in Intent");
11903 }
11904
11905 synchronized(this) {
11906 if (!(token instanceof ServiceRecord)) {
11907 throw new IllegalArgumentException("Invalid service token");
11908 }
11909 ServiceRecord r = (ServiceRecord)token;
11910
11911 final long origId = Binder.clearCallingIdentity();
11912
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011913 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 + " " + intent + ": " + service);
11915 if (r != null) {
11916 Intent.FilterComparison filter
11917 = new Intent.FilterComparison(intent);
11918 IntentBindRecord b = r.bindings.get(filter);
11919 if (b != null && !b.received) {
11920 b.binder = service;
11921 b.requested = true;
11922 b.received = true;
11923 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011924 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011925 = r.connections.values().iterator();
11926 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011927 ArrayList<ConnectionRecord> clist = it.next();
11928 for (int i=0; i<clist.size(); i++) {
11929 ConnectionRecord c = clist.get(i);
11930 if (!filter.equals(c.binding.intent.intent)) {
11931 if (DEBUG_SERVICE) Slog.v(
11932 TAG, "Not publishing to: " + c);
11933 if (DEBUG_SERVICE) Slog.v(
11934 TAG, "Bound intent: " + c.binding.intent.intent);
11935 if (DEBUG_SERVICE) Slog.v(
11936 TAG, "Published intent: " + intent);
11937 continue;
11938 }
11939 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11940 try {
11941 c.conn.connected(r.name, service);
11942 } catch (Exception e) {
11943 Slog.w(TAG, "Failure sending service " + r.name +
11944 " to connection " + c.conn.asBinder() +
11945 " (in " + c.binding.client.processName + ")", e);
11946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 }
11948 }
11949 }
11950 }
11951
11952 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11953
11954 Binder.restoreCallingIdentity(origId);
11955 }
11956 }
11957 }
11958
11959 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11960 // Refuse possible leaked file descriptors
11961 if (intent != null && intent.hasFileDescriptors() == true) {
11962 throw new IllegalArgumentException("File descriptors passed in Intent");
11963 }
11964
11965 synchronized(this) {
11966 if (!(token instanceof ServiceRecord)) {
11967 throw new IllegalArgumentException("Invalid service token");
11968 }
11969 ServiceRecord r = (ServiceRecord)token;
11970
11971 final long origId = Binder.clearCallingIdentity();
11972
11973 if (r != null) {
11974 Intent.FilterComparison filter
11975 = new Intent.FilterComparison(intent);
11976 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011977 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 + " at " + b + ": apps="
11979 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020011980
11981 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011982 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020011983 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 // Applications have already bound since the last
11985 // unbind, so just rebind right here.
11986 requestServiceBindingLocked(r, b, true);
11987 } else {
11988 // Note to tell the service the next time there is
11989 // a new client.
11990 b.doRebind = true;
11991 }
11992 }
11993
Per Edelberg78f9fff2010-08-30 20:01:35 +020011994 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995
11996 Binder.restoreCallingIdentity(origId);
11997 }
11998 }
11999 }
12000
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012001 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012002 synchronized(this) {
12003 if (!(token instanceof ServiceRecord)) {
12004 throw new IllegalArgumentException("Invalid service token");
12005 }
12006 ServiceRecord r = (ServiceRecord)token;
12007 boolean inStopping = mStoppingServices.contains(token);
12008 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012010 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012011 + " with incorrect token: given " + token
12012 + ", expected " + r);
12013 return;
12014 }
12015
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012016 if (type == 1) {
12017 // This is a call from a service start... take care of
12018 // book-keeping.
12019 r.callStart = true;
12020 switch (res) {
12021 case Service.START_STICKY_COMPATIBILITY:
12022 case Service.START_STICKY: {
12023 // We are done with the associated start arguments.
12024 r.findDeliveredStart(startId, true);
12025 // Don't stop if killed.
12026 r.stopIfKilled = false;
12027 break;
12028 }
12029 case Service.START_NOT_STICKY: {
12030 // We are done with the associated start arguments.
12031 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012032 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012033 // There is no more work, and this service
12034 // doesn't want to hang around if killed.
12035 r.stopIfKilled = true;
12036 }
12037 break;
12038 }
12039 case Service.START_REDELIVER_INTENT: {
12040 // We'll keep this item until they explicitly
12041 // call stop for it, but keep track of the fact
12042 // that it was delivered.
12043 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12044 if (si != null) {
12045 si.deliveryCount = 0;
12046 si.doneExecutingCount++;
12047 // Don't stop if killed.
12048 r.stopIfKilled = true;
12049 }
12050 break;
12051 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012052 case Service.START_TASK_REMOVED_COMPLETE: {
12053 // Special processing for onTaskRemoved(). Don't
12054 // impact normal onStartCommand() processing.
12055 r.findDeliveredStart(startId, true);
12056 break;
12057 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012058 default:
12059 throw new IllegalArgumentException(
12060 "Unknown service start result: " + res);
12061 }
12062 if (res == Service.START_STICKY_COMPATIBILITY) {
12063 r.callStart = false;
12064 }
12065 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012066 if (DEBUG_MU)
12067 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12068 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012069 final long origId = Binder.clearCallingIdentity();
12070 serviceDoneExecutingLocked(r, inStopping);
12071 Binder.restoreCallingIdentity(origId);
12072 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012073 Slog.w(TAG, "Done executing unknown service from pid "
12074 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076 }
12077 }
12078
12079 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012080 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12081 + ": nesting=" + r.executeNesting
12082 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012083 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084 r.executeNesting--;
12085 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012086 if (DEBUG_SERVICE) Slog.v(TAG,
12087 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 r.app.executingServices.remove(r);
12089 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012090 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12091 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12093 }
12094 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012095 if (DEBUG_SERVICE) Slog.v(TAG,
12096 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012097 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012098 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012099 }
12100 updateOomAdjLocked(r.app);
12101 }
12102 }
12103
12104 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012105 String anrMessage = null;
12106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 synchronized(this) {
12108 if (proc.executingServices.size() == 0 || proc.thread == null) {
12109 return;
12110 }
12111 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12112 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12113 ServiceRecord timeout = null;
12114 long nextTime = 0;
12115 while (it.hasNext()) {
12116 ServiceRecord sr = it.next();
12117 if (sr.executingStart < maxTime) {
12118 timeout = sr;
12119 break;
12120 }
12121 if (sr.executingStart > nextTime) {
12122 nextTime = sr.executingStart;
12123 }
12124 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012125 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012127 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 } else {
12129 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12130 msg.obj = proc;
12131 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12132 }
12133 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012134
12135 if (anrMessage != null) {
12136 appNotResponding(proc, null, null, anrMessage);
12137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 }
12139
12140 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012141 // BACKUP AND RESTORE
12142 // =========================================================
12143
12144 // Cause the target app to be launched if necessary and its backup agent
12145 // instantiated. The backup agent will invoke backupAgentCreated() on the
12146 // activity manager to announce its creation.
12147 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012148 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012149 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12150
12151 synchronized(this) {
12152 // !!! TODO: currently no check here that we're already bound
12153 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12154 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12155 synchronized (stats) {
12156 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12157 }
12158
Dianne Hackborne7f97212011-02-24 14:40:20 -080012159 // Backup agent is now in use, its package can't be stopped.
12160 try {
12161 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012162 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012163 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012164 } catch (IllegalArgumentException e) {
12165 Slog.w(TAG, "Failed trying to unstop package "
12166 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012167 }
12168
Christopher Tate181fafa2009-05-14 11:12:14 -070012169 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012170 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12171 ? new ComponentName(app.packageName, app.backupAgentName)
12172 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012173 // startProcessLocked() returns existing proc's record if it's already running
12174 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012175 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012176 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012177 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012178 return false;
12179 }
12180
12181 r.app = proc;
12182 mBackupTarget = r;
12183 mBackupAppName = app.packageName;
12184
Christopher Tate6fa95972009-06-05 18:43:55 -070012185 // Try not to kill the process during backup
12186 updateOomAdjLocked(proc);
12187
Christopher Tate181fafa2009-05-14 11:12:14 -070012188 // If the process is already attached, schedule the creation of the backup agent now.
12189 // If it is not yet live, this will be done when it attaches to the framework.
12190 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012191 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012192 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012193 proc.thread.scheduleCreateBackupAgent(app,
12194 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012195 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012196 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012197 }
12198 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012199 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012200 }
12201 // Invariants: at this point, the target app process exists and the application
12202 // is either already running or in the process of coming up. mBackupTarget and
12203 // mBackupAppName describe the app, so that when it binds back to the AM we
12204 // know that it's scheduled for a backup-agent operation.
12205 }
12206
12207 return true;
12208 }
12209
12210 // A backup agent has just come up
12211 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012212 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012213 + " = " + agent);
12214
12215 synchronized(this) {
12216 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012217 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012218 return;
12219 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012220 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012221
Dianne Hackborn06740692010-09-22 22:46:21 -070012222 long oldIdent = Binder.clearCallingIdentity();
12223 try {
12224 IBackupManager bm = IBackupManager.Stub.asInterface(
12225 ServiceManager.getService(Context.BACKUP_SERVICE));
12226 bm.agentConnected(agentPackageName, agent);
12227 } catch (RemoteException e) {
12228 // can't happen; the backup manager service is local
12229 } catch (Exception e) {
12230 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12231 e.printStackTrace();
12232 } finally {
12233 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012234 }
12235 }
12236
12237 // done with this agent
12238 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012239 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012240 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012241 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012242 return;
12243 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012244
12245 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012246 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012247 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012248 return;
12249 }
12250
Christopher Tate181fafa2009-05-14 11:12:14 -070012251 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012252 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012253 return;
12254 }
12255
Christopher Tate6fa95972009-06-05 18:43:55 -070012256 ProcessRecord proc = mBackupTarget.app;
12257 mBackupTarget = null;
12258 mBackupAppName = null;
12259
12260 // Not backing this app up any more; reset its OOM adjustment
12261 updateOomAdjLocked(proc);
12262
Christopher Tatec7b31e32009-06-10 15:49:30 -070012263 // If the app crashed during backup, 'thread' will be null here
12264 if (proc.thread != null) {
12265 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012266 proc.thread.scheduleDestroyBackupAgent(appInfo,
12267 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012268 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012269 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012270 e.printStackTrace();
12271 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012272 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012273 }
12274 }
12275 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 // BROADCASTS
12277 // =========================================================
12278
Josh Bartel7f208742010-02-25 11:01:44 -060012279 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012280 List cur) {
12281 final ContentResolver resolver = mContext.getContentResolver();
12282 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12283 if (list == null) {
12284 return cur;
12285 }
12286 int N = list.size();
12287 for (int i=0; i<N; i++) {
12288 Intent intent = list.get(i);
12289 if (filter.match(resolver, intent, true, TAG) >= 0) {
12290 if (cur == null) {
12291 cur = new ArrayList<Intent>();
12292 }
12293 cur.add(intent);
12294 }
12295 }
12296 return cur;
12297 }
12298
Christopher Tatef46723b2012-01-26 14:19:24 -080012299 boolean isPendingBroadcastProcessLocked(int pid) {
12300 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12301 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303
Christopher Tatef46723b2012-01-26 14:19:24 -080012304 void skipPendingBroadcastLocked(int pid) {
12305 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12306 for (BroadcastQueue queue : mBroadcastQueues) {
12307 queue.skipPendingBroadcastLocked(pid);
12308 }
12309 }
12310
12311 // The app just attached; send any pending broadcasts that it should receive
12312 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12313 boolean didSomething = false;
12314 for (BroadcastQueue queue : mBroadcastQueues) {
12315 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012316 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012317 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012318 }
12319
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012320 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012321 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012322 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012323 synchronized(this) {
12324 ProcessRecord callerApp = null;
12325 if (caller != null) {
12326 callerApp = getRecordForAppLocked(caller);
12327 if (callerApp == null) {
12328 throw new SecurityException(
12329 "Unable to find app for caller " + caller
12330 + " (pid=" + Binder.getCallingPid()
12331 + ") when registering receiver " + receiver);
12332 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012333 if (callerApp.info.uid != Process.SYSTEM_UID &&
12334 !callerApp.pkgList.contains(callerPackage)) {
12335 throw new SecurityException("Given caller package " + callerPackage
12336 + " is not running in process " + callerApp);
12337 }
12338 } else {
12339 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012340 }
12341
12342 List allSticky = null;
12343
12344 // Look for any matching sticky broadcasts...
12345 Iterator actions = filter.actionsIterator();
12346 if (actions != null) {
12347 while (actions.hasNext()) {
12348 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012349 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 }
12351 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012352 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012353 }
12354
12355 // The first sticky in the list is returned directly back to
12356 // the client.
12357 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12358
Joe Onorato8a9b2202010-02-26 18:56:32 -080012359 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012360 + ": " + sticky);
12361
12362 if (receiver == null) {
12363 return sticky;
12364 }
12365
12366 ReceiverList rl
12367 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12368 if (rl == null) {
12369 rl = new ReceiverList(this, callerApp,
12370 Binder.getCallingPid(),
12371 Binder.getCallingUid(), receiver);
12372 if (rl.app != null) {
12373 rl.app.receivers.add(rl);
12374 } else {
12375 try {
12376 receiver.asBinder().linkToDeath(rl, 0);
12377 } catch (RemoteException e) {
12378 return sticky;
12379 }
12380 rl.linkedToDeath = true;
12381 }
12382 mRegisteredReceivers.put(receiver.asBinder(), rl);
12383 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012384 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012385 rl.add(bf);
12386 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012387 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
12389 mReceiverResolver.addFilter(bf);
12390
12391 // Enqueue broadcasts for all existing stickies that match
12392 // this filter.
12393 if (allSticky != null) {
12394 ArrayList receivers = new ArrayList();
12395 receivers.add(bf);
12396
12397 int N = allSticky.size();
12398 for (int i=0; i<N; i++) {
12399 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012400 BroadcastQueue queue = broadcastQueueForIntent(intent);
12401 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012402 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012403 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012404 queue.enqueueParallelBroadcastLocked(r);
12405 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012406 }
12407 }
12408
12409 return sticky;
12410 }
12411 }
12412
12413 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012414 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012415
Christopher Tatef46723b2012-01-26 14:19:24 -080012416 final long origId = Binder.clearCallingIdentity();
12417 try {
12418 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012419
Christopher Tatef46723b2012-01-26 14:19:24 -080012420 synchronized(this) {
12421 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012422 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012423 if (rl != null) {
12424 if (rl.curBroadcast != null) {
12425 BroadcastRecord r = rl.curBroadcast;
12426 final boolean doNext = finishReceiverLocked(
12427 receiver.asBinder(), r.resultCode, r.resultData,
12428 r.resultExtras, r.resultAbort, true);
12429 if (doNext) {
12430 doTrim = true;
12431 r.queue.processNextBroadcast(false);
12432 }
12433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434
Christopher Tatef46723b2012-01-26 14:19:24 -080012435 if (rl.app != null) {
12436 rl.app.receivers.remove(rl);
12437 }
12438 removeReceiverLocked(rl);
12439 if (rl.linkedToDeath) {
12440 rl.linkedToDeath = false;
12441 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012443 }
12444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 // If we actually concluded any broadcasts, we might now be able
12447 // to trim the recipients' apps from our working set
12448 if (doTrim) {
12449 trimApplications();
12450 return;
12451 }
12452
12453 } finally {
12454 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012456 }
12457
12458 void removeReceiverLocked(ReceiverList rl) {
12459 mRegisteredReceivers.remove(rl.receiver.asBinder());
12460 int N = rl.size();
12461 for (int i=0; i<N; i++) {
12462 mReceiverResolver.removeFilter(rl.get(i));
12463 }
12464 }
12465
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012466 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12467 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12468 ProcessRecord r = mLruProcesses.get(i);
12469 if (r.thread != null) {
12470 try {
12471 r.thread.dispatchPackageBroadcast(cmd, packages);
12472 } catch (RemoteException ex) {
12473 }
12474 }
12475 }
12476 }
12477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 private final int broadcastIntentLocked(ProcessRecord callerApp,
12479 String callerPackage, Intent intent, String resolvedType,
12480 IIntentReceiver resultTo, int resultCode, String resultData,
12481 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012482 boolean ordered, boolean sticky, int callingPid, int callingUid,
12483 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012484 intent = new Intent(intent);
12485
Dianne Hackborne7f97212011-02-24 14:40:20 -080012486 // By default broadcasts do not go to stopped apps.
12487 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12488
Joe Onorato8a9b2202010-02-26 18:56:32 -080012489 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012491 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012492 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012493 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494 }
12495
12496 // Handle special intents: if this broadcast is from the package
12497 // manager about a package being removed, we need to remove all of
12498 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012499 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012501 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12502 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012503 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 || uidRemoved) {
12505 if (checkComponentPermission(
12506 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012507 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 == PackageManager.PERMISSION_GRANTED) {
12509 if (uidRemoved) {
12510 final Bundle intentExtras = intent.getExtras();
12511 final int uid = intentExtras != null
12512 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12513 if (uid >= 0) {
12514 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12515 synchronized (bs) {
12516 bs.removeUidStatsLocked(uid);
12517 }
12518 }
12519 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012520 // If resources are unvailble just force stop all
12521 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012522 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012523 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12524 if (list != null && (list.length > 0)) {
12525 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012526 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012527 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012528 sendPackageBroadcastLocked(
12529 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012530 }
12531 } else {
12532 Uri data = intent.getData();
12533 String ssp;
12534 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12535 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12536 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012537 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12538 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012539 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012540 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012541 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12542 new String[] {ssp});
12543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012544 }
12545 }
12546 }
12547 } else {
12548 String msg = "Permission Denial: " + intent.getAction()
12549 + " broadcast from " + callerPackage + " (pid=" + callingPid
12550 + ", uid=" + callingUid + ")"
12551 + " requires "
12552 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012553 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012554 throw new SecurityException(msg);
12555 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012556
12557 // Special case for adding a package: by default turn on compatibility
12558 // mode.
12559 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012560 Uri data = intent.getData();
12561 String ssp;
12562 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12563 mCompatModePackages.handlePackageAddedLocked(ssp,
12564 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012566 }
12567
12568 /*
12569 * If this is the time zone changed action, queue up a message that will reset the timezone
12570 * of all currently running processes. This message will get queued up before the broadcast
12571 * happens.
12572 */
12573 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12574 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12575 }
12576
Robert Greenwalt03595d02010-11-02 14:08:23 -070012577 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12578 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12579 }
12580
Robert Greenwalt434203a2010-10-11 16:00:27 -070012581 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12582 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12583 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12584 }
12585
Dianne Hackborn854060af2009-07-09 18:14:31 -070012586 /*
12587 * Prevent non-system code (defined here to be non-persistent
12588 * processes) from sending protected broadcasts.
12589 */
12590 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12591 || callingUid == Process.SHELL_UID || callingUid == 0) {
12592 // Always okay.
12593 } else if (callerApp == null || !callerApp.persistent) {
12594 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012595 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012596 intent.getAction())) {
12597 String msg = "Permission Denial: not allowed to send broadcast "
12598 + intent.getAction() + " from pid="
12599 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012600 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012601 throw new SecurityException(msg);
12602 }
12603 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012604 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012605 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012606 }
12607 }
12608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609 // Add to the sticky list if requested.
12610 if (sticky) {
12611 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12612 callingPid, callingUid)
12613 != PackageManager.PERMISSION_GRANTED) {
12614 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12615 + callingPid + ", uid=" + callingUid
12616 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012617 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012618 throw new SecurityException(msg);
12619 }
12620 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012621 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012622 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012623 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012624 }
12625 if (intent.getComponent() != null) {
12626 throw new SecurityException(
12627 "Sticky broadcasts can't target a specific component");
12628 }
12629 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12630 if (list == null) {
12631 list = new ArrayList<Intent>();
12632 mStickyBroadcasts.put(intent.getAction(), list);
12633 }
12634 int N = list.size();
12635 int i;
12636 for (i=0; i<N; i++) {
12637 if (intent.filterEquals(list.get(i))) {
12638 // This sticky already exists, replace it.
12639 list.set(i, new Intent(intent));
12640 break;
12641 }
12642 }
12643 if (i >= N) {
12644 list.add(new Intent(intent));
12645 }
12646 }
12647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 // Figure out who all will receive this broadcast.
12649 List receivers = null;
12650 List<BroadcastFilter> registeredReceivers = null;
12651 try {
12652 if (intent.getComponent() != null) {
12653 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012654 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012655 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 if (ai != null) {
12657 receivers = new ArrayList();
12658 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012659 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012660 receivers.add(ri);
12661 }
12662 } else {
12663 // Need to resolve the intent to interested receivers...
12664 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12665 == 0) {
12666 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012667 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012668 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012669 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012670 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12671 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012672 }
12673 } catch (RemoteException ex) {
12674 // pm is in same process, this will never happen.
12675 }
12676
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012677 final boolean replacePending =
12678 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12679
Joe Onorato8a9b2202010-02-26 18:56:32 -080012680 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012681 + " replacePending=" + replacePending);
12682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12684 if (!ordered && NR > 0) {
12685 // If we are not serializing this broadcast, then send the
12686 // registered receivers separately so they don't wait for the
12687 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012688 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12689 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012690 callerPackage, callingPid, callingUid, requiredPermission,
12691 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012692 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012693 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012694 TAG, "Enqueueing parallel broadcast " + r);
12695 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012696 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012697 queue.enqueueParallelBroadcastLocked(r);
12698 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012700 registeredReceivers = null;
12701 NR = 0;
12702 }
12703
12704 // Merge into one list.
12705 int ir = 0;
12706 if (receivers != null) {
12707 // A special case for PACKAGE_ADDED: do not allow the package
12708 // being added to see this broadcast. This prevents them from
12709 // using this as a back door to get run as soon as they are
12710 // installed. Maybe in the future we want to have a special install
12711 // broadcast or such for apps, but we'd like to deliberately make
12712 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012713 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012714 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12715 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12716 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012717 Uri data = intent.getData();
12718 if (data != null) {
12719 String pkgName = data.getSchemeSpecificPart();
12720 if (pkgName != null) {
12721 skipPackages = new String[] { pkgName };
12722 }
12723 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012724 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012725 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012726 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012727 if (skipPackages != null && (skipPackages.length > 0)) {
12728 for (String skipPackage : skipPackages) {
12729 if (skipPackage != null) {
12730 int NT = receivers.size();
12731 for (int it=0; it<NT; it++) {
12732 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12733 if (curt.activityInfo.packageName.equals(skipPackage)) {
12734 receivers.remove(it);
12735 it--;
12736 NT--;
12737 }
12738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012739 }
12740 }
12741 }
12742
12743 int NT = receivers != null ? receivers.size() : 0;
12744 int it = 0;
12745 ResolveInfo curt = null;
12746 BroadcastFilter curr = null;
12747 while (it < NT && ir < NR) {
12748 if (curt == null) {
12749 curt = (ResolveInfo)receivers.get(it);
12750 }
12751 if (curr == null) {
12752 curr = registeredReceivers.get(ir);
12753 }
12754 if (curr.getPriority() >= curt.priority) {
12755 // Insert this broadcast record into the final list.
12756 receivers.add(it, curr);
12757 ir++;
12758 curr = null;
12759 it++;
12760 NT++;
12761 } else {
12762 // Skip to the next ResolveInfo in the final list.
12763 it++;
12764 curt = null;
12765 }
12766 }
12767 }
12768 while (ir < NR) {
12769 if (receivers == null) {
12770 receivers = new ArrayList();
12771 }
12772 receivers.add(registeredReceivers.get(ir));
12773 ir++;
12774 }
12775
12776 if ((receivers != null && receivers.size() > 0)
12777 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012778 BroadcastQueue queue = broadcastQueueForIntent(intent);
12779 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012780 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012781 receivers, resultTo, resultCode, resultData, map, ordered,
12782 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012783 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012785 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 if (DEBUG_BROADCAST) {
12787 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012788 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012790 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012791 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012792 queue.enqueueOrderedBroadcastLocked(r);
12793 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 }
12796
Dianne Hackborna4972e92012-03-14 10:38:05 -070012797 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 }
12799
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012800 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 // Refuse possible leaked file descriptors
12802 if (intent != null && intent.hasFileDescriptors() == true) {
12803 throw new IllegalArgumentException("File descriptors passed in Intent");
12804 }
12805
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012806 int flags = intent.getFlags();
12807
12808 if (!mProcessesReady) {
12809 // if the caller really truly claims to know what they're doing, go
12810 // ahead and allow the broadcast without launching any receivers
12811 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12812 intent = new Intent(intent);
12813 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12814 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12815 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12816 + " before boot completion");
12817 throw new IllegalStateException("Cannot broadcast before boot completed");
12818 }
12819 }
12820
12821 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12822 throw new IllegalArgumentException(
12823 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12824 }
12825
12826 return intent;
12827 }
12828
12829 public final int broadcastIntent(IApplicationThread caller,
12830 Intent intent, String resolvedType, IIntentReceiver resultTo,
12831 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012832 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012833 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012834 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012835 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012837 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12838 final int callingPid = Binder.getCallingPid();
12839 final int callingUid = Binder.getCallingUid();
12840 final long origId = Binder.clearCallingIdentity();
12841 int res = broadcastIntentLocked(callerApp,
12842 callerApp != null ? callerApp.info.packageName : null,
12843 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012844 resultCode, resultData, map, requiredPermission, serialized, sticky,
12845 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012846 Binder.restoreCallingIdentity(origId);
12847 return res;
12848 }
12849 }
12850
12851 int broadcastIntentInPackage(String packageName, int uid,
12852 Intent intent, String resolvedType, IIntentReceiver resultTo,
12853 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012854 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012856 intent = verifyBroadcastLocked(intent);
12857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 final long origId = Binder.clearCallingIdentity();
12859 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12860 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012861 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012862 Binder.restoreCallingIdentity(origId);
12863 return res;
12864 }
12865 }
12866
Amith Yamasani742a6712011-05-04 14:49:28 -070012867 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12868 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 // Refuse possible leaked file descriptors
12870 if (intent != null && intent.hasFileDescriptors() == true) {
12871 throw new IllegalArgumentException("File descriptors passed in Intent");
12872 }
12873
12874 synchronized(this) {
12875 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12876 != PackageManager.PERMISSION_GRANTED) {
12877 String msg = "Permission Denial: unbroadcastIntent() from pid="
12878 + Binder.getCallingPid()
12879 + ", uid=" + Binder.getCallingUid()
12880 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012881 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012882 throw new SecurityException(msg);
12883 }
12884 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12885 if (list != null) {
12886 int N = list.size();
12887 int i;
12888 for (i=0; i<N; i++) {
12889 if (intent.filterEquals(list.get(i))) {
12890 list.remove(i);
12891 break;
12892 }
12893 }
12894 }
12895 }
12896 }
12897
12898 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12899 String resultData, Bundle resultExtras, boolean resultAbort,
12900 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012901 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12902 if (r == null) {
12903 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012904 return false;
12905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906
Christopher Tatef46723b2012-01-26 14:19:24 -080012907 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12908 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012909 }
12910
12911 public void finishReceiver(IBinder who, int resultCode, String resultData,
12912 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012913 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012914
12915 // Refuse possible leaked file descriptors
12916 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12917 throw new IllegalArgumentException("File descriptors passed in Bundle");
12918 }
12919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012920 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012921 try {
12922 boolean doNext = false;
12923 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924
Christopher Tatef46723b2012-01-26 14:19:24 -080012925 synchronized(this) {
12926 r = broadcastRecordForReceiverLocked(who);
12927 if (r != null) {
12928 doNext = r.queue.finishReceiverLocked(r, resultCode,
12929 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012932
Christopher Tatef46723b2012-01-26 14:19:24 -080012933 if (doNext) {
12934 r.queue.processNextBroadcast(false);
12935 }
12936 trimApplications();
12937 } finally {
12938 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012942 // =========================================================
12943 // INSTRUMENTATION
12944 // =========================================================
12945
12946 public boolean startInstrumentation(ComponentName className,
12947 String profileFile, int flags, Bundle arguments,
12948 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012949 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012950 // Refuse possible leaked file descriptors
12951 if (arguments != null && arguments.hasFileDescriptors()) {
12952 throw new IllegalArgumentException("File descriptors passed in Bundle");
12953 }
12954
12955 synchronized(this) {
12956 InstrumentationInfo ii = null;
12957 ApplicationInfo ai = null;
12958 try {
12959 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012960 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012961 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012962 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012963 } catch (PackageManager.NameNotFoundException e) {
12964 }
12965 if (ii == null) {
12966 reportStartInstrumentationFailure(watcher, className,
12967 "Unable to find instrumentation info for: " + className);
12968 return false;
12969 }
12970 if (ai == null) {
12971 reportStartInstrumentationFailure(watcher, className,
12972 "Unable to find instrumentation target package: " + ii.targetPackage);
12973 return false;
12974 }
12975
12976 int match = mContext.getPackageManager().checkSignatures(
12977 ii.targetPackage, ii.packageName);
12978 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
12979 String msg = "Permission Denial: starting instrumentation "
12980 + className + " from pid="
12981 + Binder.getCallingPid()
12982 + ", uid=" + Binder.getCallingPid()
12983 + " not allowed because package " + ii.packageName
12984 + " does not have a signature matching the target "
12985 + ii.targetPackage;
12986 reportStartInstrumentationFailure(watcher, className, msg);
12987 throw new SecurityException(msg);
12988 }
12989
Amith Yamasani483f3b02012-03-13 16:08:00 -070012990 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012991 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070012992 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070012993 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012994 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012995 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012996 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012997 app.instrumentationProfileFile = profileFile;
12998 app.instrumentationArguments = arguments;
12999 app.instrumentationWatcher = watcher;
13000 app.instrumentationResultClass = className;
13001 Binder.restoreCallingIdentity(origId);
13002 }
13003
13004 return true;
13005 }
13006
13007 /**
13008 * Report errors that occur while attempting to start Instrumentation. Always writes the
13009 * error to the logs, but if somebody is watching, send the report there too. This enables
13010 * the "am" command to report errors with more information.
13011 *
13012 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13013 * @param cn The component name of the instrumentation.
13014 * @param report The error report.
13015 */
13016 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13017 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013018 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013019 try {
13020 if (watcher != null) {
13021 Bundle results = new Bundle();
13022 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13023 results.putString("Error", report);
13024 watcher.instrumentationStatus(cn, -1, results);
13025 }
13026 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013027 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013028 }
13029 }
13030
13031 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13032 if (app.instrumentationWatcher != null) {
13033 try {
13034 // NOTE: IInstrumentationWatcher *must* be oneway here
13035 app.instrumentationWatcher.instrumentationFinished(
13036 app.instrumentationClass,
13037 resultCode,
13038 results);
13039 } catch (RemoteException e) {
13040 }
13041 }
13042 app.instrumentationWatcher = null;
13043 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013044 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 app.instrumentationProfileFile = null;
13046 app.instrumentationArguments = null;
13047
Amith Yamasani483f3b02012-03-13 16:08:00 -070013048 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049 }
13050
13051 public void finishInstrumentation(IApplicationThread target,
13052 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013053 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 // Refuse possible leaked file descriptors
13055 if (results != null && results.hasFileDescriptors()) {
13056 throw new IllegalArgumentException("File descriptors passed in Intent");
13057 }
13058
13059 synchronized(this) {
13060 ProcessRecord app = getRecordForAppLocked(target);
13061 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013062 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013063 return;
13064 }
13065 final long origId = Binder.clearCallingIdentity();
13066 finishInstrumentationLocked(app, resultCode, results);
13067 Binder.restoreCallingIdentity(origId);
13068 }
13069 }
13070
13071 // =========================================================
13072 // CONFIGURATION
13073 // =========================================================
13074
13075 public ConfigurationInfo getDeviceConfigurationInfo() {
13076 ConfigurationInfo config = new ConfigurationInfo();
13077 synchronized (this) {
13078 config.reqTouchScreen = mConfiguration.touchscreen;
13079 config.reqKeyboardType = mConfiguration.keyboard;
13080 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013081 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13082 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013083 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13084 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013085 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13086 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013087 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13088 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013089 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 }
13091 return config;
13092 }
13093
13094 public Configuration getConfiguration() {
13095 Configuration ci;
13096 synchronized(this) {
13097 ci = new Configuration(mConfiguration);
13098 }
13099 return ci;
13100 }
13101
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013102 public void updatePersistentConfiguration(Configuration values) {
13103 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13104 "updateConfiguration()");
13105 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13106 "updateConfiguration()");
13107 if (values == null) {
13108 throw new NullPointerException("Configuration must not be null");
13109 }
13110
13111 synchronized(this) {
13112 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013113 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013114 Binder.restoreCallingIdentity(origId);
13115 }
13116 }
13117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 public void updateConfiguration(Configuration values) {
13119 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13120 "updateConfiguration()");
13121
13122 synchronized(this) {
13123 if (values == null && mWindowManager != null) {
13124 // sentinel: fetch the current configuration from the window manager
13125 values = mWindowManager.computeNewConfiguration();
13126 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013127
13128 if (mWindowManager != null) {
13129 mProcessList.applyDisplaySize(mWindowManager);
13130 }
13131
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013133 if (values != null) {
13134 Settings.System.clearConfiguration(values);
13135 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013136 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 Binder.restoreCallingIdentity(origId);
13138 }
13139 }
13140
13141 /**
13142 * Do either or both things: (1) change the current configuration, and (2)
13143 * make sure the given activity is running with the (now) current
13144 * configuration. Returns true if the activity has been left running, or
13145 * false if <var>starting</var> is being destroyed to match the new
13146 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013147 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013149 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013150 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013151 // do nothing if we are headless
13152 if (mHeadless) return true;
13153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013154 int changes = 0;
13155
13156 boolean kept = true;
13157
13158 if (values != null) {
13159 Configuration newConfig = new Configuration(mConfiguration);
13160 changes = newConfig.updateFrom(values);
13161 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013162 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013163 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013164 }
13165
Doug Zongker2bec3d42009-12-04 12:52:44 -080013166 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013167
Dianne Hackborn813075a62011-11-14 17:45:19 -080013168 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013169 saveLocaleLocked(values.locale,
13170 !values.locale.equals(mConfiguration.locale),
13171 values.userSetLocale);
13172 }
13173
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013174 mConfigurationSeq++;
13175 if (mConfigurationSeq <= 0) {
13176 mConfigurationSeq = 1;
13177 }
13178 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013180 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013181
13182 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013183
13184 // TODO: If our config changes, should we auto dismiss any currently
13185 // showing dialogs?
13186 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013187
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013188 AttributeCache ac = AttributeCache.instance();
13189 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013190 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013192
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013193 // Make sure all resources in our process are updated
13194 // right now, so that anyone who is going to retrieve
13195 // resource values after we return will be sure to get
13196 // the new ones. This is especially important during
13197 // boot, where the first config change needs to guarantee
13198 // all resources have that config before following boot
13199 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013200 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013201
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013202 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013203 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013204 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013205 mHandler.sendMessage(msg);
13206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013207
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013208 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13209 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 try {
13211 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013212 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013213 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013214 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215 }
13216 } catch (Exception e) {
13217 }
13218 }
13219 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013220 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13221 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013222 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013223 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013224 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13225 broadcastIntentLocked(null, null,
13226 new Intent(Intent.ACTION_LOCALE_CHANGED),
13227 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013228 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 }
13231 }
13232
13233 if (changes != 0 && starting == null) {
13234 // If the configuration changed, and the caller is not already
13235 // in the process of starting an activity, then find the top
13236 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013237 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 }
13239
13240 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013241 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013242 // And we need to make sure at this point that all other activities
13243 // are made visible with the correct configuration.
13244 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 }
13246
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013247 if (values != null && mWindowManager != null) {
13248 mWindowManager.setNewConfiguration(mConfiguration);
13249 }
13250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 return kept;
13252 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013253
13254 /**
13255 * Decide based on the configuration whether we should shouw the ANR,
13256 * crash, etc dialogs. The idea is that if there is no affordnace to
13257 * press the on-screen buttons, we shouldn't show the dialog.
13258 *
13259 * A thought: SystemUI might also want to get told about this, the Power
13260 * dialog / global actions also might want different behaviors.
13261 */
13262 private static final boolean shouldShowDialogs(Configuration config) {
13263 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13264 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013266
13267 /**
13268 * Save the locale. You must be inside a synchronized (this) block.
13269 */
13270 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13271 if(isDiff) {
13272 SystemProperties.set("user.language", l.getLanguage());
13273 SystemProperties.set("user.region", l.getCountry());
13274 }
13275
13276 if(isPersist) {
13277 SystemProperties.set("persist.sys.language", l.getLanguage());
13278 SystemProperties.set("persist.sys.country", l.getCountry());
13279 SystemProperties.set("persist.sys.localevar", l.getVariant());
13280 }
13281 }
13282
Adam Powelldd8fab22012-03-22 17:47:27 -070013283 @Override
13284 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13285 ActivityRecord srec = ActivityRecord.forToken(token);
13286 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13287 }
13288
13289 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13290 Intent resultData) {
13291 ComponentName dest = destIntent.getComponent();
13292
13293 synchronized (this) {
13294 ActivityRecord srec = ActivityRecord.forToken(token);
13295 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13296 final int start = history.indexOf(srec);
13297 if (start < 0) {
13298 // Current activity is not in history stack; do nothing.
13299 return false;
13300 }
13301 int finishTo = start - 1;
13302 ActivityRecord parent = null;
13303 boolean foundParentInTask = false;
13304 if (dest != null) {
13305 TaskRecord tr = srec.task;
13306 for (int i = start - 1; i >= 0; i--) {
13307 ActivityRecord r = history.get(i);
13308 if (tr != r.task) {
13309 // Couldn't find parent in the same task; stop at the one above this.
13310 // (Root of current task; in-app "home" behavior)
13311 // Always at least finish the current activity.
13312 finishTo = Math.min(start - 1, i + 1);
13313 parent = history.get(finishTo);
13314 break;
13315 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13316 r.info.name.equals(dest.getClassName())) {
13317 finishTo = i;
13318 parent = r;
13319 foundParentInTask = true;
13320 break;
13321 }
13322 }
13323 }
13324
13325 if (mController != null) {
13326 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13327 if (next != null) {
13328 // ask watcher if this is allowed
13329 boolean resumeOK = true;
13330 try {
13331 resumeOK = mController.activityResuming(next.packageName);
13332 } catch (RemoteException e) {
13333 mController = null;
13334 }
13335
13336 if (!resumeOK) {
13337 return false;
13338 }
13339 }
13340 }
13341 final long origId = Binder.clearCallingIdentity();
13342 for (int i = start; i > finishTo; i--) {
13343 ActivityRecord r = history.get(i);
13344 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13345 "navigate-up");
13346 // Only return the supplied result for the first activity finished
13347 resultCode = Activity.RESULT_CANCELED;
13348 resultData = null;
13349 }
13350
13351 if (parent != null && foundParentInTask) {
13352 final int parentLaunchMode = parent.info.launchMode;
13353 final int destIntentFlags = destIntent.getFlags();
13354 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13355 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13356 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13357 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13358 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13359 } else {
13360 try {
13361 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13362 destIntent.getComponent(), 0, UserId.getCallingUserId());
13363 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13364 null, aInfo, parent.appToken, null,
13365 0, -1, parent.launchedFromUid, 0, null, true, null);
13366 foundParentInTask = res == ActivityManager.START_SUCCESS;
13367 } catch (RemoteException e) {
13368 foundParentInTask = false;
13369 }
13370 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13371 resultData, "navigate-up");
13372 }
13373 }
13374 Binder.restoreCallingIdentity(origId);
13375 return foundParentInTask;
13376 }
13377 }
13378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013379 // =========================================================
13380 // LIFETIME MANAGEMENT
13381 // =========================================================
13382
Christopher Tatef46723b2012-01-26 14:19:24 -080013383 // Returns which broadcast queue the app is the current [or imminent] receiver
13384 // on, or 'null' if the app is not an active broadcast recipient.
13385 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13386 BroadcastRecord r = app.curReceiver;
13387 if (r != null) {
13388 return r.queue;
13389 }
13390
13391 // It's not the current receiver, but it might be starting up to become one
13392 synchronized (this) {
13393 for (BroadcastQueue queue : mBroadcastQueues) {
13394 r = queue.mPendingBroadcast;
13395 if (r != null && r.curApp == app) {
13396 // found it; report which queue it's in
13397 return queue;
13398 }
13399 }
13400 }
13401
13402 return null;
13403 }
13404
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013405 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013406 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013407 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013408 // This adjustment has already been computed. If we are calling
13409 // from the top, we may have already computed our adjustment with
13410 // an earlier hidden adjustment that isn't really for us... if
13411 // so, use the new hidden adjustment.
13412 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013413 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013414 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013415 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013416 }
13417
13418 if (app.thread == null) {
13419 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013420 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013421 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013422 }
13423
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013424 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13425 app.adjSource = null;
13426 app.adjTarget = null;
13427 app.empty = false;
13428 app.hidden = false;
13429
13430 final int activitiesSize = app.activities.size();
13431
Dianne Hackborn7d608422011-08-07 16:24:18 -070013432 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013433 // The max adjustment doesn't allow this app to be anything
13434 // below foreground, so it is not worth doing work for it.
13435 app.adjType = "fixed";
13436 app.adjSeq = mAdjSeq;
13437 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013438 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013439 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013440 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013441 // System process can do UI, and when they do we want to have
13442 // them trim their memory after the user leaves the UI. To
13443 // facilitate this, here we need to determine whether or not it
13444 // is currently showing UI.
13445 app.systemNoUi = true;
13446 if (app == TOP_APP) {
13447 app.systemNoUi = false;
13448 } else if (activitiesSize > 0) {
13449 for (int j = 0; j < activitiesSize; j++) {
13450 final ActivityRecord r = app.activities.get(j);
13451 if (r.visible) {
13452 app.systemNoUi = false;
13453 break;
13454 }
13455 }
13456 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013457 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013458 }
13459
13460 final boolean hadForegroundActivities = app.foregroundActivities;
13461
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013462 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013463 app.keeping = false;
13464 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013465
The Android Open Source Project4df24232009-03-05 14:34:35 -080013466 // Determine the importance of the process, starting with most
13467 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013468 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013469 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013470 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013471 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013472 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013473 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013474 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013475 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013476 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013477 } else if (app.instrumentationClass != null) {
13478 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013479 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013480 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013481 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013482 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013483 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013484 // counts as being in the foreground for OOM killer purposes.
13485 // It's placed in a sched group based on the nature of the
13486 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013487 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013488 schedGroup = (queue == mFgBroadcastQueue)
13489 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013490 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 } else if (app.executingServices.size() > 0) {
13492 // An app that is currently executing a service callback also
13493 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013494 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013495 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013496 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013497 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013498 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013499 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013500 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013501 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013502 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013503 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013504 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013505 // A very not-needed process. If this is lower in the lru list,
13506 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013507 adj = hiddenAdj;
13508 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013509 app.hidden = true;
13510 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013511 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013513
13514 // Examine all activities if not already foreground.
13515 if (!app.foregroundActivities && activitiesSize > 0) {
13516 for (int j = 0; j < activitiesSize; j++) {
13517 final ActivityRecord r = app.activities.get(j);
13518 if (r.visible) {
13519 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013520 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13521 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013522 app.adjType = "visible";
13523 }
13524 schedGroup = Process.THREAD_GROUP_DEFAULT;
13525 app.hidden = false;
13526 app.foregroundActivities = true;
13527 break;
13528 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13529 || r.state == ActivityState.STOPPING) {
13530 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013531 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13532 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013533 app.adjType = "stopping";
13534 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013535 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013536 app.foregroundActivities = true;
13537 }
13538 }
13539 }
13540
Dianne Hackborn7d608422011-08-07 16:24:18 -070013541 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013542 if (app.foregroundServices) {
13543 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013544 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013545 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013546 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013547 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013548 } else if (app.forcingToForeground != null) {
13549 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013550 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013551 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013552 app.adjType = "force-foreground";
13553 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013554 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013555 }
13556 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013557
Dianne Hackborn7d608422011-08-07 16:24:18 -070013558 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013559 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013560 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013561 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013562 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013563 app.adjType = "heavy";
13564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013565
Dianne Hackborn7d608422011-08-07 16:24:18 -070013566 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013567 // This process is hosting what we currently consider to be the
13568 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013569 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013570 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013571 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013572 app.adjType = "home";
13573 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013574
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013575 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13576 && app.activities.size() > 0) {
13577 // This was the previous process that showed UI to the user.
13578 // We want to try to keep it around more aggressively, to give
13579 // a good experience around switching between two apps.
13580 adj = ProcessList.PREVIOUS_APP_ADJ;
13581 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13582 app.hidden = false;
13583 app.adjType = "previous";
13584 }
13585
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013586 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13587 + " reason=" + app.adjType);
13588
The Android Open Source Project4df24232009-03-05 14:34:35 -080013589 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590 // there are applications dependent on our services or providers, but
13591 // this gives us a baseline and makes sure we don't get into an
13592 // infinite recursion.
13593 app.adjSeq = mAdjSeq;
13594 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595
Christopher Tate6fa95972009-06-05 18:43:55 -070013596 if (mBackupTarget != null && app == mBackupTarget.app) {
13597 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013598 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013599 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013600 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013601 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013602 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013603 }
13604 }
13605
Dianne Hackborn7d608422011-08-07 16:24:18 -070013606 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013607 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 final long now = SystemClock.uptimeMillis();
13609 // This process is more important if the top activity is
13610 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013611 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013612 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013613 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013614 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013615 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013616 // If this process has shown some UI, let it immediately
13617 // go to the LRU list because it may be pretty heavy with
13618 // UI stuff. We'll tag it with a label just to help
13619 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013620 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013621 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013622 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013623 } else {
13624 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13625 // This service has seen some activity within
13626 // recent memory, so we will keep its process ahead
13627 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013628 if (adj > ProcessList.SERVICE_ADJ) {
13629 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013630 app.adjType = "started-services";
13631 app.hidden = false;
13632 }
13633 }
13634 // If we have let the service slide into the background
13635 // state, still have some text describing what it is doing
13636 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013637 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013638 app.adjType = "started-bg-services";
13639 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013640 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013641 // Don't kill this process because it is doing work; it
13642 // has said it is doing work.
13643 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013644 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013645 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013646 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013647 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013648 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013649 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013650 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013651 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013652 // XXX should compute this based on the max of
13653 // all connected clients.
13654 ConnectionRecord cr = clist.get(i);
13655 if (cr.binding.client == app) {
13656 // Binding to ourself is not interesting.
13657 continue;
13658 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013659 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013660 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013661 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013662 int myHiddenAdj = hiddenAdj;
13663 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013664 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013665 myHiddenAdj = client.hiddenAdj;
13666 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013667 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013668 }
13669 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013670 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013671 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013672 String adjType = null;
13673 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13674 // Not doing bind OOM management, so treat
13675 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013676 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013677 // If this process has shown some UI, let it immediately
13678 // go to the LRU list because it may be pretty heavy with
13679 // UI stuff. We'll tag it with a label just to help
13680 // debug and understand what is going on.
13681 if (adj > clientAdj) {
13682 adjType = "bound-bg-ui-services";
13683 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013684 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013685 clientAdj = adj;
13686 } else {
13687 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13688 // This service has not seen activity within
13689 // recent memory, so allow it to drop to the
13690 // LRU list if there is no other reason to keep
13691 // it around. We'll also tag it with a label just
13692 // to help debug and undertand what is going on.
13693 if (adj > clientAdj) {
13694 adjType = "bound-bg-services";
13695 }
13696 clientAdj = adj;
13697 }
13698 }
13699 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013700 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013701 // If this process has recently shown UI, and
13702 // the process that is binding to it is less
13703 // important than being visible, then we don't
13704 // care about the binding as much as we care
13705 // about letting this process get into the LRU
13706 // list to be killed and restarted if needed for
13707 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013708 if (app.hasShownUi && app != mHomeProcess
13709 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013710 adjType = "bound-bg-ui-services";
13711 } else {
13712 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13713 |Context.BIND_IMPORTANT)) != 0) {
13714 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013715 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13716 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13717 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13718 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13719 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013720 adj = clientAdj;
13721 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013722 app.pendingUiClean = true;
13723 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13724 adj = ProcessList.VISIBLE_APP_ADJ;
13725 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013726 }
13727 if (!client.hidden) {
13728 app.hidden = false;
13729 }
13730 if (client.keeping) {
13731 app.keeping = true;
13732 }
13733 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013734 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013735 }
13736 if (adjType != null) {
13737 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013738 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13739 .REASON_SERVICE_IN_USE;
13740 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013741 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013742 app.adjTarget = s.name;
13743 }
13744 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13745 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13746 schedGroup = Process.THREAD_GROUP_DEFAULT;
13747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013748 }
13749 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013750 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13751 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013752 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013753 (a.visible || a.state == ActivityState.RESUMED
13754 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013755 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013756 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13757 schedGroup = Process.THREAD_GROUP_DEFAULT;
13758 }
13759 app.hidden = false;
13760 app.adjType = "service";
13761 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13762 .REASON_SERVICE_IN_USE;
13763 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013764 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013765 app.adjTarget = s.name;
13766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013768 }
13769 }
13770 }
13771 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013772
Dianne Hackborn287952c2010-09-22 22:34:31 -070013773 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013774 // would like to avoid killing it unless it would prevent the current
13775 // application from running. By default we put the process in
13776 // with the rest of the background processes; as we scan through
13777 // its services we may bump it up from there.
13778 if (adj > hiddenAdj) {
13779 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013780 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013781 app.adjType = "bg-services";
13782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013783 }
13784
Dianne Hackborn7d608422011-08-07 16:24:18 -070013785 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013786 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013787 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013788 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013789 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013790 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013791 if (cpr.clients.size() != 0) {
13792 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013793 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013794 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013795 if (client == app) {
13796 // Being our own client is not interesting.
13797 continue;
13798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013799 int myHiddenAdj = hiddenAdj;
13800 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013801 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013802 myHiddenAdj = client.hiddenAdj;
13803 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013804 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013805 }
13806 }
13807 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013808 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013809 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013810 if (app.hasShownUi && app != mHomeProcess
13811 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013812 app.adjType = "bg-ui-provider";
13813 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013814 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13815 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013816 app.adjType = "provider";
13817 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013818 if (!client.hidden) {
13819 app.hidden = false;
13820 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013821 if (client.keeping) {
13822 app.keeping = true;
13823 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013824 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13825 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013826 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013827 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013828 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013829 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013830 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13831 schedGroup = Process.THREAD_GROUP_DEFAULT;
13832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013833 }
13834 }
13835 // If the provider has external (non-framework) process
13836 // dependencies, ensure that its adjustment is at least
13837 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013838 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013839 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13840 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013841 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013842 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013843 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013844 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013845 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013846 }
13847 }
13848 }
13849 }
13850
13851 app.curRawAdj = adj;
13852
Joe Onorato8a9b2202010-02-26 18:56:32 -080013853 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013854 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13855 if (adj > app.maxAdj) {
13856 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013857 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013858 schedGroup = Process.THREAD_GROUP_DEFAULT;
13859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013860 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013861 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013862 app.keeping = true;
13863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013864
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013865 if (app.hasAboveClient) {
13866 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13867 // then we need to drop its adjustment to be lower than the service's
13868 // in order to honor the request. We want to drop it by one adjustment
13869 // level... but there is special meaning applied to various levels so
13870 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013871 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013872 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013873 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13874 adj = ProcessList.VISIBLE_APP_ADJ;
13875 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13876 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13877 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13878 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013879 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013880 adj++;
13881 }
13882 }
13883
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013884 if (adj == ProcessList.SERVICE_ADJ) {
13885 if (doingAll) {
13886 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13887 mNewNumServiceProcs++;
13888 }
13889 if (app.serviceb) {
13890 adj = ProcessList.SERVICE_B_ADJ;
13891 }
13892 } else {
13893 app.serviceb = false;
13894 }
13895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013896 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013897 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013898
13899 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013900 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13901 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013902 }
13903
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013904 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013905 }
13906
13907 /**
13908 * Ask a given process to GC right now.
13909 */
13910 final void performAppGcLocked(ProcessRecord app) {
13911 try {
13912 app.lastRequestedGc = SystemClock.uptimeMillis();
13913 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013914 if (app.reportLowMemory) {
13915 app.reportLowMemory = false;
13916 app.thread.scheduleLowMemory();
13917 } else {
13918 app.thread.processInBackground();
13919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013920 }
13921 } catch (Exception e) {
13922 // whatever.
13923 }
13924 }
13925
13926 /**
13927 * Returns true if things are idle enough to perform GCs.
13928 */
Josh Bartel7f208742010-02-25 11:01:44 -060013929 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013930 boolean processingBroadcasts = false;
13931 for (BroadcastQueue q : mBroadcastQueues) {
13932 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13933 processingBroadcasts = true;
13934 }
13935 }
13936 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013937 && (mSleeping || (mMainStack.mResumedActivity != null &&
13938 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013939 }
13940
13941 /**
13942 * Perform GCs on all processes that are waiting for it, but only
13943 * if things are idle.
13944 */
13945 final void performAppGcsLocked() {
13946 final int N = mProcessesToGc.size();
13947 if (N <= 0) {
13948 return;
13949 }
Josh Bartel7f208742010-02-25 11:01:44 -060013950 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013951 while (mProcessesToGc.size() > 0) {
13952 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013953 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013954 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13955 <= SystemClock.uptimeMillis()) {
13956 // To avoid spamming the system, we will GC processes one
13957 // at a time, waiting a few seconds between each.
13958 performAppGcLocked(proc);
13959 scheduleAppGcsLocked();
13960 return;
13961 } else {
13962 // It hasn't been long enough since we last GCed this
13963 // process... put it in the list to wait for its time.
13964 addProcessToGcListLocked(proc);
13965 break;
13966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013967 }
13968 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013969
13970 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013971 }
13972 }
13973
13974 /**
13975 * If all looks good, perform GCs on all processes waiting for them.
13976 */
13977 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013978 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013979 performAppGcsLocked();
13980 return;
13981 }
13982 // Still not idle, wait some more.
13983 scheduleAppGcsLocked();
13984 }
13985
13986 /**
13987 * Schedule the execution of all pending app GCs.
13988 */
13989 final void scheduleAppGcsLocked() {
13990 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013991
13992 if (mProcessesToGc.size() > 0) {
13993 // Schedule a GC for the time to the next process.
13994 ProcessRecord proc = mProcessesToGc.get(0);
13995 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13996
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013997 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013998 long now = SystemClock.uptimeMillis();
13999 if (when < (now+GC_TIMEOUT)) {
14000 when = now + GC_TIMEOUT;
14001 }
14002 mHandler.sendMessageAtTime(msg, when);
14003 }
14004 }
14005
14006 /**
14007 * Add a process to the array of processes waiting to be GCed. Keeps the
14008 * list in sorted order by the last GC time. The process can't already be
14009 * on the list.
14010 */
14011 final void addProcessToGcListLocked(ProcessRecord proc) {
14012 boolean added = false;
14013 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14014 if (mProcessesToGc.get(i).lastRequestedGc <
14015 proc.lastRequestedGc) {
14016 added = true;
14017 mProcessesToGc.add(i+1, proc);
14018 break;
14019 }
14020 }
14021 if (!added) {
14022 mProcessesToGc.add(0, proc);
14023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014024 }
14025
14026 /**
14027 * Set up to ask a process to GC itself. This will either do it
14028 * immediately, or put it on the list of processes to gc the next
14029 * time things are idle.
14030 */
14031 final void scheduleAppGcLocked(ProcessRecord app) {
14032 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014033 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014034 return;
14035 }
14036 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014037 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014038 scheduleAppGcsLocked();
14039 }
14040 }
14041
Dianne Hackborn287952c2010-09-22 22:34:31 -070014042 final void checkExcessivePowerUsageLocked(boolean doKills) {
14043 updateCpuStatsNow();
14044
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014045 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014046 boolean doWakeKills = doKills;
14047 boolean doCpuKills = doKills;
14048 if (mLastPowerCheckRealtime == 0) {
14049 doWakeKills = false;
14050 }
14051 if (mLastPowerCheckUptime == 0) {
14052 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014053 }
14054 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014055 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014056 }
14057 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014058 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14059 final long curUptime = SystemClock.uptimeMillis();
14060 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14061 mLastPowerCheckRealtime = curRealtime;
14062 mLastPowerCheckUptime = curUptime;
14063 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14064 doWakeKills = false;
14065 }
14066 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14067 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014068 }
14069 int i = mLruProcesses.size();
14070 while (i > 0) {
14071 i--;
14072 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014073 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014074 long wtime;
14075 synchronized (stats) {
14076 wtime = stats.getProcessWakeTime(app.info.uid,
14077 app.pid, curRealtime);
14078 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014079 long wtimeUsed = wtime - app.lastWakeTime;
14080 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14081 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014082 StringBuilder sb = new StringBuilder(128);
14083 sb.append("Wake for ");
14084 app.toShortString(sb);
14085 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014086 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014087 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014088 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014089 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014090 sb.append((wtimeUsed*100)/realtimeSince);
14091 sb.append("%)");
14092 Slog.i(TAG, sb.toString());
14093 sb.setLength(0);
14094 sb.append("CPU for ");
14095 app.toShortString(sb);
14096 sb.append(": over ");
14097 TimeUtils.formatDuration(uptimeSince, sb);
14098 sb.append(" used ");
14099 TimeUtils.formatDuration(cputimeUsed, sb);
14100 sb.append(" (");
14101 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014102 sb.append("%)");
14103 Slog.i(TAG, sb.toString());
14104 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014105 // If a process has held a wake lock for more
14106 // than 50% of the time during this period,
14107 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014108 if (doWakeKills && realtimeSince > 0
14109 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14110 synchronized (stats) {
14111 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14112 realtimeSince, wtimeUsed);
14113 }
14114 Slog.w(TAG, "Excessive wake lock in " + app.processName
14115 + " (pid " + app.pid + "): held " + wtimeUsed
14116 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014117 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14118 app.processName, app.setAdj, "excessive wake lock");
14119 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014120 } else if (doCpuKills && uptimeSince > 0
14121 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14122 synchronized (stats) {
14123 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14124 uptimeSince, cputimeUsed);
14125 }
14126 Slog.w(TAG, "Excessive CPU in " + app.processName
14127 + " (pid " + app.pid + "): used " + cputimeUsed
14128 + " during " + uptimeSince);
14129 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14130 app.processName, app.setAdj, "excessive cpu");
14131 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014132 } else {
14133 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014134 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014135 }
14136 }
14137 }
14138 }
14139
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014140 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014141 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014142 app.hiddenAdj = hiddenAdj;
14143
14144 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014145 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014146 }
14147
Dianne Hackborn287952c2010-09-22 22:34:31 -070014148 final boolean wasKeeping = app.keeping;
14149
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014150 boolean success = true;
14151
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014152 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153
Jeff Brown10e89712011-07-08 18:52:57 -070014154 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014155 if (false) {
14156 // Removing for now. Forcing GCs is not so useful anymore
14157 // with Dalvik, and the new memory level hint facility is
14158 // better for what we need to do these days.
14159 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14160 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14161 // If this app is transitioning from foreground to
14162 // non-foreground, have it do a gc.
14163 scheduleAppGcLocked(app);
14164 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14165 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14166 // Likewise do a gc when an app is moving in to the
14167 // background (such as a service stopping).
14168 scheduleAppGcLocked(app);
14169 }
Jeff Brown10e89712011-07-08 18:52:57 -070014170 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014171
Jeff Brown10e89712011-07-08 18:52:57 -070014172 if (wasKeeping && !app.keeping) {
14173 // This app is no longer something we want to keep. Note
14174 // its current wake lock time to later know to kill it if
14175 // it is not behaving well.
14176 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14177 synchronized (stats) {
14178 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14179 app.pid, SystemClock.elapsedRealtime());
14180 }
14181 app.lastCpuTime = app.curCpuTime;
14182 }
14183
14184 app.setRawAdj = app.curRawAdj;
14185 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014186
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014187 if (app.curAdj != app.setAdj) {
14188 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014189 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014190 TAG, "Set " + app.pid + " " + app.processName +
14191 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014192 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014193 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014194 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014195 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014196 }
14197 }
14198 if (app.setSchedGroup != app.curSchedGroup) {
14199 app.setSchedGroup = app.curSchedGroup;
14200 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14201 "Setting process group of " + app.processName
14202 + " to " + app.curSchedGroup);
14203 if (app.waitingToKill != null &&
14204 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14205 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14206 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14207 app.processName, app.setAdj, app.waitingToKill);
14208 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014209 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014210 } else {
14211 if (true) {
14212 long oldId = Binder.clearCallingIdentity();
14213 try {
14214 Process.setProcessGroup(app.pid, app.curSchedGroup);
14215 } catch (Exception e) {
14216 Slog.w(TAG, "Failed setting process group of " + app.pid
14217 + " to " + app.curSchedGroup);
14218 e.printStackTrace();
14219 } finally {
14220 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014221 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014222 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014223 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014224 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014225 app.thread.setSchedulingGroup(app.curSchedGroup);
14226 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014227 }
14228 }
14229 }
14230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014231 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014232 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014233 }
14234
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014235 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014236 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014237 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014238 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014239 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014240 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014241 }
14242 }
14243 return resumedActivity;
14244 }
14245
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014246 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014247 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014248 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14249 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014250 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14251 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014252
14253 mAdjSeq++;
14254
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014255 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014256 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14257 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014258 if (nowHidden != wasHidden) {
14259 // Changed to/from hidden state, so apps after it in the LRU
14260 // list may also be changed.
14261 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014262 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014263 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014264 }
14265
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014266 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014267 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014268 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14269
14270 if (false) {
14271 RuntimeException e = new RuntimeException();
14272 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014273 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014274 }
14275
14276 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014277 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014278
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014279 // Let's determine how many processes we have running vs.
14280 // how many slots we have for background processes; we may want
14281 // to put multiple processes in a slot of there are enough of
14282 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014283 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014284 int factor = (mLruProcesses.size()-4)/numSlots;
14285 if (factor < 1) factor = 1;
14286 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014287 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014288
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014289 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014290 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014291 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014292 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014293 while (i > 0) {
14294 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014295 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014296 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014297 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14298 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014299 && app.curAdj == curHiddenAdj) {
14300 step++;
14301 if (step >= factor) {
14302 step = 0;
14303 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014304 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014305 }
14306 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014307 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014308 numHidden++;
14309 if (numHidden > mProcessLimit) {
14310 Slog.i(TAG, "No longer want " + app.processName
14311 + " (pid " + app.pid + "): hidden #" + numHidden);
14312 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14313 app.processName, app.setAdj, "too many background");
14314 app.killedBackground = true;
14315 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014316 }
14317 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014318 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14319 // If this is an isolated process, and there are no
14320 // services running in it, then the process is no longer
14321 // needed. We agressively kill these because we can by
14322 // definition not re-use the same process again, and it is
14323 // good to avoid having whatever code was running in them
14324 // left sitting around after no longer needed.
14325 Slog.i(TAG, "Isolated process " + app.processName
14326 + " (pid " + app.pid + ") no longer needed");
14327 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14328 app.processName, app.setAdj, "isolated not needed");
14329 app.killedBackground = true;
14330 Process.killProcessQuiet(app.pid);
14331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014332 }
14333 }
14334
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014335 mNumServiceProcs = mNewNumServiceProcs;
14336
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014337 // Now determine the memory trimming level of background processes.
14338 // Unfortunately we need to start at the back of the list to do this
14339 // properly. We only do this if the number of background apps we
14340 // are managing to keep around is less than half the maximum we desire;
14341 // if we are keeping a good number around, we'll let them use whatever
14342 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014343 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014344 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014345 factor = numHidden/3;
14346 int minFactor = 2;
14347 if (mHomeProcess != null) minFactor++;
14348 if (mPreviousProcess != null) minFactor++;
14349 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014350 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014351 int fgTrimLevel;
14352 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14353 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14354 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14355 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14356 } else {
14357 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14358 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014359 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014360 for (i=0; i<N; i++) {
14361 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014362 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14363 && app.curAdj != ProcessList.SERVICE_B_ADJ
14364 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014365 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14366 try {
14367 app.thread.scheduleTrimMemory(curLevel);
14368 } catch (RemoteException e) {
14369 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014370 if (false) {
14371 // For now we won't do this; our memory trimming seems
14372 // to be good enough at this point that destroying
14373 // activities causes more harm than good.
14374 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14375 && app != mHomeProcess && app != mPreviousProcess) {
14376 // For these apps we will also finish their activities
14377 // to help them free memory.
14378 mMainStack.destroyActivitiesLocked(app, false, "trim");
14379 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014380 }
14381 }
14382 app.trimMemoryLevel = curLevel;
14383 step++;
14384 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014385 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014386 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014387 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14388 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014389 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014390 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14391 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014392 break;
14393 }
14394 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014395 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014396 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014397 && app.thread != null) {
14398 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014399 app.thread.scheduleTrimMemory(
14400 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014401 } catch (RemoteException e) {
14402 }
14403 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014404 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014405 } else {
14406 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14407 && app.pendingUiClean) {
14408 // If this application is now in the background and it
14409 // had done UI, then give it the special trim level to
14410 // have it free UI resources.
14411 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14412 if (app.trimMemoryLevel < level && app.thread != null) {
14413 try {
14414 app.thread.scheduleTrimMemory(level);
14415 } catch (RemoteException e) {
14416 }
14417 }
14418 app.pendingUiClean = false;
14419 }
14420 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014421 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014422 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014423 } catch (RemoteException e) {
14424 }
14425 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014426 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014427 }
14428 }
14429 } else {
14430 final int N = mLruProcesses.size();
14431 for (i=0; i<N; i++) {
14432 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014433 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014434 && app.pendingUiClean) {
14435 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14436 && app.thread != null) {
14437 try {
14438 app.thread.scheduleTrimMemory(
14439 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14440 } catch (RemoteException e) {
14441 }
14442 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014443 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014444 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014445 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014446 }
14447 }
14448
14449 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014450 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014452 }
14453
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014454 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014455 synchronized (this) {
14456 int i;
14457
14458 // First remove any unused application processes whose package
14459 // has been removed.
14460 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14461 final ProcessRecord app = mRemovedProcesses.get(i);
14462 if (app.activities.size() == 0
14463 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014464 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014465 TAG, "Exiting empty application process "
14466 + app.processName + " ("
14467 + (app.thread != null ? app.thread.asBinder() : null)
14468 + ")\n");
14469 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014470 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14471 app.processName, app.setAdj, "empty");
14472 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014473 } else {
14474 try {
14475 app.thread.scheduleExit();
14476 } catch (Exception e) {
14477 // Ignore exceptions.
14478 }
14479 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014480 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014481 mRemovedProcesses.remove(i);
14482
14483 if (app.persistent) {
14484 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014485 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014486 }
14487 }
14488 }
14489 }
14490
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014491 // Now update the oom adj for all processes.
14492 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014493 }
14494 }
14495
14496 /** This method sends the specified signal to each of the persistent apps */
14497 public void signalPersistentProcesses(int sig) throws RemoteException {
14498 if (sig != Process.SIGNAL_USR1) {
14499 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14500 }
14501
14502 synchronized (this) {
14503 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14504 != PackageManager.PERMISSION_GRANTED) {
14505 throw new SecurityException("Requires permission "
14506 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14507 }
14508
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014509 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14510 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014511 if (r.thread != null && r.persistent) {
14512 Process.sendSignal(r.pid, sig);
14513 }
14514 }
14515 }
14516 }
14517
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014518 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14519 if (proc == null || proc == mProfileProc) {
14520 proc = mProfileProc;
14521 path = mProfileFile;
14522 profileType = mProfileType;
14523 clearProfilerLocked();
14524 }
14525 if (proc == null) {
14526 return;
14527 }
14528 try {
14529 proc.thread.profilerControl(false, path, null, profileType);
14530 } catch (RemoteException e) {
14531 throw new IllegalStateException("Process disappeared");
14532 }
14533 }
14534
14535 private void clearProfilerLocked() {
14536 if (mProfileFd != null) {
14537 try {
14538 mProfileFd.close();
14539 } catch (IOException e) {
14540 }
14541 }
14542 mProfileApp = null;
14543 mProfileProc = null;
14544 mProfileFile = null;
14545 mProfileType = 0;
14546 mAutoStopProfiler = false;
14547 }
14548
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014549 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014550 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014551
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014552 try {
14553 synchronized (this) {
14554 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14555 // its own permission.
14556 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14557 != PackageManager.PERMISSION_GRANTED) {
14558 throw new SecurityException("Requires permission "
14559 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014560 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014561
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014562 if (start && fd == null) {
14563 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014564 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014565
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014566 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014567 if (process != null) {
14568 try {
14569 int pid = Integer.parseInt(process);
14570 synchronized (mPidsSelfLocked) {
14571 proc = mPidsSelfLocked.get(pid);
14572 }
14573 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014574 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014575
14576 if (proc == null) {
14577 HashMap<String, SparseArray<ProcessRecord>> all
14578 = mProcessNames.getMap();
14579 SparseArray<ProcessRecord> procs = all.get(process);
14580 if (procs != null && procs.size() > 0) {
14581 proc = procs.valueAt(0);
14582 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014583 }
14584 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014585
14586 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014587 throw new IllegalArgumentException("Unknown process: " + process);
14588 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014589
14590 if (start) {
14591 stopProfilerLocked(null, null, 0);
14592 setProfileApp(proc.info, proc.processName, path, fd, false);
14593 mProfileProc = proc;
14594 mProfileType = profileType;
14595 try {
14596 fd = fd.dup();
14597 } catch (IOException e) {
14598 fd = null;
14599 }
14600 proc.thread.profilerControl(start, path, fd, profileType);
14601 fd = null;
14602 mProfileFd = null;
14603 } else {
14604 stopProfilerLocked(proc, path, profileType);
14605 if (fd != null) {
14606 try {
14607 fd.close();
14608 } catch (IOException e) {
14609 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014610 }
14611 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014612
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014613 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014614 }
14615 } catch (RemoteException e) {
14616 throw new IllegalStateException("Process disappeared");
14617 } finally {
14618 if (fd != null) {
14619 try {
14620 fd.close();
14621 } catch (IOException e) {
14622 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014623 }
14624 }
14625 }
Andy McFadden824c5102010-07-09 16:26:57 -070014626
14627 public boolean dumpHeap(String process, boolean managed,
14628 String path, ParcelFileDescriptor fd) throws RemoteException {
14629
14630 try {
14631 synchronized (this) {
14632 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14633 // its own permission (same as profileControl).
14634 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14635 != PackageManager.PERMISSION_GRANTED) {
14636 throw new SecurityException("Requires permission "
14637 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14638 }
14639
14640 if (fd == null) {
14641 throw new IllegalArgumentException("null fd");
14642 }
14643
14644 ProcessRecord proc = null;
14645 try {
14646 int pid = Integer.parseInt(process);
14647 synchronized (mPidsSelfLocked) {
14648 proc = mPidsSelfLocked.get(pid);
14649 }
14650 } catch (NumberFormatException e) {
14651 }
14652
14653 if (proc == null) {
14654 HashMap<String, SparseArray<ProcessRecord>> all
14655 = mProcessNames.getMap();
14656 SparseArray<ProcessRecord> procs = all.get(process);
14657 if (procs != null && procs.size() > 0) {
14658 proc = procs.valueAt(0);
14659 }
14660 }
14661
14662 if (proc == null || proc.thread == null) {
14663 throw new IllegalArgumentException("Unknown process: " + process);
14664 }
14665
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014666 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14667 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014668 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14669 throw new SecurityException("Process not debuggable: " + proc);
14670 }
14671 }
14672
14673 proc.thread.dumpHeap(managed, path, fd);
14674 fd = null;
14675 return true;
14676 }
14677 } catch (RemoteException e) {
14678 throw new IllegalStateException("Process disappeared");
14679 } finally {
14680 if (fd != null) {
14681 try {
14682 fd.close();
14683 } catch (IOException e) {
14684 }
14685 }
14686 }
14687 }
14688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014689 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14690 public void monitor() {
14691 synchronized (this) { }
14692 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014693
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014694 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014695 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14696 ProcessRecord processRecord = mLruProcesses.get(i);
14697 try {
14698 if (processRecord.thread != null) {
14699 processRecord.thread.setCoreSettings(settings);
14700 }
14701 } catch (RemoteException re) {
14702 /* ignore */
14703 }
14704 }
14705 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014706
14707 // Multi-user methods
14708
Amith Yamasani742a6712011-05-04 14:49:28 -070014709 private int mCurrentUserId;
14710 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14711
14712 public boolean switchUser(int userId) {
14713 final int callingUid = Binder.getCallingUid();
14714 if (callingUid != 0 && callingUid != Process.myUid()) {
14715 Slog.e(TAG, "Trying to switch user from unauthorized app");
14716 return false;
14717 }
14718 if (mCurrentUserId == userId)
14719 return true;
14720
14721 synchronized (this) {
14722 // Check if user is already logged in, otherwise check if user exists first before
14723 // adding to the list of logged in users.
14724 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14725 if (!userExists(userId)) {
14726 return false;
14727 }
14728 mLoggedInUsers.append(userId, userId);
14729 }
14730
14731 mCurrentUserId = userId;
14732 boolean haveActivities = mMainStack.switchUser(userId);
14733 if (!haveActivities) {
14734 startHomeActivityLocked(userId);
14735 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014736
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014737 }
Amith Yamasani13593602012-03-22 16:16:17 -070014738
14739 // Inform of user switch
14740 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14741 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14742 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14743
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014744 return true;
14745 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014746
Amith Yamasani52f1d752012-03-28 18:19:29 -070014747 @Override
14748 public UserInfo getCurrentUser() throws RemoteException {
14749 final int callingUid = Binder.getCallingUid();
14750 if (callingUid != 0 && callingUid != Process.myUid()) {
14751 Slog.e(TAG, "Trying to get user from unauthorized app");
14752 return null;
14753 }
14754 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14755 }
14756
Amith Yamasani13593602012-03-22 16:16:17 -070014757 private void onUserRemoved(Intent intent) {
14758 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14759 if (extraUserId < 1) return;
14760
14761 // Kill all the processes for the user
14762 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14763 synchronized (this) {
14764 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14765 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14766 SparseArray<ProcessRecord> uids = uidMap.getValue();
14767 for (int i = 0; i < uids.size(); i++) {
14768 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14769 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14770 }
14771 }
14772 }
14773
14774 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14775 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14776 false, false, true, true, extraUserId);
14777 }
14778 }
14779 }
14780
Amith Yamasani742a6712011-05-04 14:49:28 -070014781 private boolean userExists(int userId) {
14782 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014783 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14784 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014785 } catch (RemoteException re) {
14786 // Won't happen, in same process
14787 }
14788
14789 return false;
14790 }
14791
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014792 private void checkValidCaller(int uid, int userId) {
14793 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14794
14795 throw new SecurityException("Caller uid=" + uid
14796 + " is not privileged to communicate with user=" + userId);
14797 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014798
14799 private int applyUserId(int uid, int userId) {
14800 return UserId.getUid(userId, uid);
14801 }
14802
14803 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014804 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014805 ApplicationInfo newInfo = new ApplicationInfo(info);
14806 newInfo.uid = applyUserId(info.uid, userId);
14807 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14808 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14809 + info.packageName;
14810 }
14811 return newInfo;
14812 }
14813
14814 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014815 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014816 || userId < 1) {
14817 return aInfo;
14818 }
14819
14820 ActivityInfo info = new ActivityInfo(aInfo);
14821 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14822 return info;
14823 }
14824
14825 static class ServiceMap {
14826
14827 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14828 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14829 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14830 mServicesByIntentPerUser = new SparseArray<
14831 HashMap<Intent.FilterComparison, ServiceRecord>>();
14832
14833 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14834 // TODO: Deal with global services
14835 if (DEBUG_MU)
14836 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14837 return getServices(callingUser).get(name);
14838 }
14839
14840 ServiceRecord getServiceByName(ComponentName name) {
14841 return getServiceByName(name, -1);
14842 }
14843
14844 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14845 // TODO: Deal with global services
14846 if (DEBUG_MU)
14847 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14848 return getServicesByIntent(callingUser).get(filter);
14849 }
14850
14851 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14852 return getServiceByIntent(filter, -1);
14853 }
14854
14855 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14856 // TODO: Deal with global services
14857 getServices(callingUser).put(name, value);
14858 }
14859
14860 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14861 ServiceRecord value) {
14862 // TODO: Deal with global services
14863 getServicesByIntent(callingUser).put(filter, value);
14864 }
14865
14866 void removeServiceByName(ComponentName name, int callingUser) {
14867 // TODO: Deal with global services
14868 ServiceRecord removed = getServices(callingUser).remove(name);
14869 if (DEBUG_MU)
14870 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14871 + " removed=" + removed);
14872 }
14873
14874 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14875 // TODO: Deal with global services
14876 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14877 if (DEBUG_MU)
14878 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14879 + " removed=" + removed);
14880 }
14881
14882 Collection<ServiceRecord> getAllServices(int callingUser) {
14883 // TODO: Deal with global services
14884 return getServices(callingUser).values();
14885 }
14886
14887 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14888 HashMap map = mServicesByNamePerUser.get(callingUser);
14889 if (map == null) {
14890 map = new HashMap<ComponentName, ServiceRecord>();
14891 mServicesByNamePerUser.put(callingUser, map);
14892 }
14893 return map;
14894 }
14895
14896 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14897 int callingUser) {
14898 HashMap map = mServicesByIntentPerUser.get(callingUser);
14899 if (map == null) {
14900 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14901 mServicesByIntentPerUser.put(callingUser, map);
14902 }
14903 return map;
14904 }
14905 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014906}