blob: 2da827e0c07819e1eae03c95a5d34273012a8e45 [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 Hackbornd3e677b2012-04-05 14:58:18 -070010265 final int[] SINGLE_LONG_FORMAT = new int[] {
10266 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10267 };
10268 long[] longOut = new long[1];
10269 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10270 SINGLE_LONG_FORMAT, null, longOut, null);
10271 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10272 longOut[0] = 0;
10273 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10274 SINGLE_LONG_FORMAT, null, longOut, null);
10275 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10276 longOut[0] = 0;
10277 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10278 SINGLE_LONG_FORMAT, null, longOut, null);
10279 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10280 longOut[0] = 0;
10281 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10282 SINGLE_LONG_FORMAT, null, longOut, null);
10283 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10284 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10285 pw.print(shared); pw.println(" kB");
10286 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10287 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010289 }
10290
10291 /**
10292 * Searches array of arguments for the specified string
10293 * @param args array of argument strings
10294 * @param value value to search for
10295 * @return true if the value is contained in the array
10296 */
10297 private static boolean scanArgs(String[] args, String value) {
10298 if (args != null) {
10299 for (String arg : args) {
10300 if (value.equals(arg)) {
10301 return true;
10302 }
10303 }
10304 }
10305 return false;
10306 }
10307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010308 private final void killServicesLocked(ProcessRecord app,
10309 boolean allowRestart) {
10310 // Report disconnected services.
10311 if (false) {
10312 // XXX we are letting the client link to the service for
10313 // death notifications.
10314 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010315 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010317 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010318 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010319 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010320 = r.connections.values().iterator();
10321 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010322 ArrayList<ConnectionRecord> cl = jt.next();
10323 for (int i=0; i<cl.size(); i++) {
10324 ConnectionRecord c = cl.get(i);
10325 if (c.binding.client != app) {
10326 try {
10327 //c.conn.connected(r.className, null);
10328 } catch (Exception e) {
10329 // todo: this should be asynchronous!
10330 Slog.w(TAG, "Exception thrown disconnected servce "
10331 + r.shortName
10332 + " from app " + app.processName, e);
10333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010334 }
10335 }
10336 }
10337 }
10338 }
10339 }
10340 }
10341
10342 // Clean up any connections this application has to other services.
10343 if (app.connections.size() > 0) {
10344 Iterator<ConnectionRecord> it = app.connections.iterator();
10345 while (it.hasNext()) {
10346 ConnectionRecord r = it.next();
10347 removeConnectionLocked(r, app, null);
10348 }
10349 }
10350 app.connections.clear();
10351
10352 if (app.services.size() != 0) {
10353 // Any services running in the application need to be placed
10354 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010355 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010356 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010357 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010358 synchronized (sr.stats.getBatteryStats()) {
10359 sr.stats.stopLaunchedLocked();
10360 }
10361 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010362 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010363 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010364 if (mStoppingServices.remove(sr)) {
10365 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10366 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010367
10368 boolean hasClients = sr.bindings.size() > 0;
10369 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010370 Iterator<IntentBindRecord> bindings
10371 = sr.bindings.values().iterator();
10372 while (bindings.hasNext()) {
10373 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010374 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010375 + ": shouldUnbind=" + b.hasBound);
10376 b.binder = null;
10377 b.requested = b.received = b.hasBound = false;
10378 }
10379 }
10380
Dianne Hackborn070783f2010-12-29 16:46:28 -080010381 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10382 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010383 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010384 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010385 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 sr.crashCount, sr.shortName, app.pid);
10387 bringDownServiceLocked(sr, true);
10388 } else if (!allowRestart) {
10389 bringDownServiceLocked(sr, true);
10390 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010391 boolean canceled = scheduleServiceRestartLocked(sr, true);
10392
10393 // Should the service remain running? Note that in the
10394 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010395 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010396 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10397 if (sr.pendingStarts.size() == 0) {
10398 sr.startRequested = false;
10399 if (!hasClients) {
10400 // Whoops, no reason to restart!
10401 bringDownServiceLocked(sr, true);
10402 }
10403 }
10404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010405 }
10406 }
10407
10408 if (!allowRestart) {
10409 app.services.clear();
10410 }
10411 }
10412
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010413 // Make sure we have no more records on the stopping list.
10414 int i = mStoppingServices.size();
10415 while (i > 0) {
10416 i--;
10417 ServiceRecord sr = mStoppingServices.get(i);
10418 if (sr.app == app) {
10419 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010420 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010421 }
10422 }
10423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010424 app.executingServices.clear();
10425 }
10426
10427 private final void removeDyingProviderLocked(ProcessRecord proc,
10428 ContentProviderRecord cpr) {
10429 synchronized (cpr) {
10430 cpr.launchingApp = null;
10431 cpr.notifyAll();
10432 }
10433
Amith Yamasani742a6712011-05-04 14:49:28 -070010434 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010435 String names[] = cpr.info.authority.split(";");
10436 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010437 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 }
10439
10440 Iterator<ProcessRecord> cit = cpr.clients.iterator();
10441 while (cit.hasNext()) {
10442 ProcessRecord capp = cit.next();
10443 if (!capp.persistent && capp.thread != null
10444 && capp.pid != 0
10445 && capp.pid != MY_PID) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070010446 Slog.i(TAG, "Kill " + capp.processName
10447 + " (pid " + capp.pid + "): provider " + cpr.info.name
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010448 + " in dying process " + (proc != null ? proc.processName : "??"));
Dianne Hackborn8633e682010-04-22 16:03:41 -070010449 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010450 capp.processName, capp.setAdj, "dying provider "
10451 + cpr.name.toShortString());
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010452 Process.killProcessQuiet(capp.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010453 }
10454 }
10455
10456 mLaunchingProviders.remove(cpr);
10457 }
10458
10459 /**
10460 * Main code for cleaning up a process when it has gone away. This is
10461 * called both as a result of the process dying, or directly when stopping
10462 * a process when running in single process mode.
10463 */
10464 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010465 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010466 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010467 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010468 }
10469
Dianne Hackborn36124872009-10-08 16:22:03 -070010470 mProcessesToGc.remove(app);
10471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010472 // Dismiss any open dialogs.
10473 if (app.crashDialog != null) {
10474 app.crashDialog.dismiss();
10475 app.crashDialog = null;
10476 }
10477 if (app.anrDialog != null) {
10478 app.anrDialog.dismiss();
10479 app.anrDialog = null;
10480 }
10481 if (app.waitDialog != null) {
10482 app.waitDialog.dismiss();
10483 app.waitDialog = null;
10484 }
10485
10486 app.crashing = false;
10487 app.notResponding = false;
10488
10489 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010490 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010491 app.thread = null;
10492 app.forcingToForeground = null;
10493 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010494 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010495 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010496 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010497
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010498 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499
10500 boolean restart = false;
10501
10502 int NL = mLaunchingProviders.size();
10503
10504 // Remove published content providers.
10505 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010506 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010507 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010508 ContentProviderRecord cpr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010509 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010510 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010511
10512 // See if someone is waiting for this provider... in which
10513 // case we don't remove it, but just let it restart.
10514 int i = 0;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010515 if (!app.bad && allowRestart) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 for (; i<NL; i++) {
10517 if (mLaunchingProviders.get(i) == cpr) {
10518 restart = true;
10519 break;
10520 }
10521 }
10522 } else {
10523 i = NL;
10524 }
10525
10526 if (i >= NL) {
10527 removeDyingProviderLocked(app, cpr);
10528 NL = mLaunchingProviders.size();
10529 }
10530 }
10531 app.pubProviders.clear();
10532 }
10533
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010534 // Take care of any launching providers waiting for this process.
10535 if (checkAppInLaunchingProvidersLocked(app, false)) {
10536 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010537 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 // Unregister from connected content providers.
10540 if (!app.conProviders.isEmpty()) {
Dianne Hackborn0c3154d2009-10-06 17:18:05 -070010541 Iterator it = app.conProviders.keySet().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010542 while (it.hasNext()) {
10543 ContentProviderRecord cpr = (ContentProviderRecord)it.next();
10544 cpr.clients.remove(app);
10545 }
10546 app.conProviders.clear();
10547 }
10548
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010549 // At this point there may be remaining entries in mLaunchingProviders
10550 // where we were the only one waiting, so they are no longer of use.
10551 // Look for these and clean up if found.
10552 // XXX Commented out for now. Trying to figure out a way to reproduce
10553 // the actual situation to identify what is actually going on.
10554 if (false) {
10555 for (int i=0; i<NL; i++) {
10556 ContentProviderRecord cpr = (ContentProviderRecord)
10557 mLaunchingProviders.get(i);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080010558 if (cpr.clients.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010559 synchronized (cpr) {
10560 cpr.launchingApp = null;
10561 cpr.notifyAll();
10562 }
10563 }
10564 }
10565 }
10566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010567 skipCurrentReceiverLocked(app);
10568
10569 // Unregister any receivers.
10570 if (app.receivers.size() > 0) {
10571 Iterator<ReceiverList> it = app.receivers.iterator();
10572 while (it.hasNext()) {
10573 removeReceiverLocked(it.next());
10574 }
10575 app.receivers.clear();
10576 }
10577
Christopher Tate181fafa2009-05-14 11:12:14 -070010578 // If the app is undergoing backup, tell the backup manager about it
10579 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010580 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010581 try {
10582 IBackupManager bm = IBackupManager.Stub.asInterface(
10583 ServiceManager.getService(Context.BACKUP_SERVICE));
10584 bm.agentDisconnected(app.info.packageName);
10585 } catch (RemoteException e) {
10586 // can't happen; backup manager is local
10587 }
10588 }
10589
Jeff Sharkey287bd832011-05-28 19:36:26 -070010590 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 // If the caller is restarting this app, then leave it in its
10593 // current lists and let the caller take care of it.
10594 if (restarting) {
10595 return;
10596 }
10597
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010598 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010599 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010601 mProcessNames.remove(app.processName, app.uid);
10602 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010603 if (mHeavyWeightProcess == app) {
10604 mHeavyWeightProcess = null;
10605 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010607 } else if (!app.removed) {
10608 // This app is persistent, so we need to keep its record around.
10609 // If it is not already on the pending app list, add it there
10610 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10612 mPersistentStartingProcesses.add(app);
10613 restart = true;
10614 }
10615 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010616 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10617 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010618 mProcessesOnHold.remove(app);
10619
The Android Open Source Project4df24232009-03-05 14:34:35 -080010620 if (app == mHomeProcess) {
10621 mHomeProcess = null;
10622 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010623 if (app == mPreviousProcess) {
10624 mPreviousProcess = null;
10625 }
10626
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010627 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 // We have components that still need to be running in the
10629 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010630 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010631 startProcessLocked(app, "restart", app.processName);
10632 } else if (app.pid > 0 && app.pid != MY_PID) {
10633 // Goodbye!
10634 synchronized (mPidsSelfLocked) {
10635 mPidsSelfLocked.remove(app.pid);
10636 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10637 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010638 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 }
10640 }
10641
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010642 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10643 // Look through the content providers we are waiting to have launched,
10644 // and if any run in this process then either schedule a restart of
10645 // the process or kill the client waiting for it if this process has
10646 // gone bad.
10647 int NL = mLaunchingProviders.size();
10648 boolean restart = false;
10649 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010650 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010651 if (cpr.launchingApp == app) {
10652 if (!alwaysBad && !app.bad) {
10653 restart = true;
10654 } else {
10655 removeDyingProviderLocked(app, cpr);
10656 NL = mLaunchingProviders.size();
10657 }
10658 }
10659 }
10660 return restart;
10661 }
10662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 // =========================================================
10664 // SERVICES
10665 // =========================================================
10666
10667 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10668 ActivityManager.RunningServiceInfo info =
10669 new ActivityManager.RunningServiceInfo();
10670 info.service = r.name;
10671 if (r.app != null) {
10672 info.pid = r.app.pid;
10673 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010674 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 info.process = r.processName;
10676 info.foreground = r.isForeground;
10677 info.activeSince = r.createTime;
10678 info.started = r.startRequested;
10679 info.clientCount = r.connections.size();
10680 info.crashCount = r.crashCount;
10681 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010682 if (r.isForeground) {
10683 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10684 }
10685 if (r.startRequested) {
10686 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10687 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010688 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010689 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10690 }
10691 if (r.app != null && r.app.persistent) {
10692 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10693 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010694
10695 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10696 for (int i=0; i<connl.size(); i++) {
10697 ConnectionRecord conn = connl.get(i);
10698 if (conn.clientLabel != 0) {
10699 info.clientPackage = conn.binding.client.info.packageName;
10700 info.clientLabel = conn.clientLabel;
10701 return info;
10702 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010703 }
10704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010705 return info;
10706 }
10707
10708 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10709 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010710 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711 synchronized (this) {
10712 ArrayList<ActivityManager.RunningServiceInfo> res
10713 = new ArrayList<ActivityManager.RunningServiceInfo>();
10714
Amith Yamasani742a6712011-05-04 14:49:28 -070010715 int userId = UserId.getUserId(Binder.getCallingUid());
10716 if (mServiceMap.getAllServices(userId).size() > 0) {
10717 Iterator<ServiceRecord> it
10718 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010719 while (it.hasNext() && res.size() < maxNum) {
10720 res.add(makeRunningServiceInfoLocked(it.next()));
10721 }
10722 }
10723
10724 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10725 ServiceRecord r = mRestartingServices.get(i);
10726 ActivityManager.RunningServiceInfo info =
10727 makeRunningServiceInfoLocked(r);
10728 info.restarting = r.nextRestartTime;
10729 res.add(info);
10730 }
10731
10732 return res;
10733 }
10734 }
10735
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010736 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010737 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010738 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010739 int userId = UserId.getUserId(Binder.getCallingUid());
10740 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010741 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010742 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
10743 for (int i=0; i<conn.size(); i++) {
10744 if (conn.get(i).clientIntent != null) {
10745 return conn.get(i).clientIntent;
10746 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010747 }
10748 }
10749 }
10750 }
10751 return null;
10752 }
10753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010754 private final ServiceRecord findServiceLocked(ComponentName name,
10755 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010756 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010757 return r == token ? r : null;
10758 }
10759
10760 private final class ServiceLookupResult {
10761 final ServiceRecord record;
10762 final String permission;
10763
10764 ServiceLookupResult(ServiceRecord _record, String _permission) {
10765 record = _record;
10766 permission = _permission;
10767 }
10768 };
10769
10770 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070010771 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 ServiceRecord r = null;
10773 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070010774 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 }
10776 if (r == null) {
10777 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070010778 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010779 }
10780
10781 if (r == null) {
10782 try {
10783 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010784 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010785 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 ServiceInfo sInfo =
10787 rInfo != null ? rInfo.serviceInfo : null;
10788 if (sInfo == null) {
10789 return null;
10790 }
10791
10792 ComponentName name = new ComponentName(
10793 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070010794 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 } catch (RemoteException ex) {
10796 // pm is in same process, this will never happen.
10797 }
10798 }
10799 if (r != null) {
10800 int callingPid = Binder.getCallingPid();
10801 int callingUid = Binder.getCallingUid();
10802 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010803 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010805 if (!r.exported) {
10806 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10807 + " from pid=" + callingPid
10808 + ", uid=" + callingUid
10809 + " that is not exported from uid " + r.appInfo.uid);
10810 return new ServiceLookupResult(null, "not exported from uid "
10811 + r.appInfo.uid);
10812 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010813 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 + " from pid=" + callingPid
10815 + ", uid=" + callingUid
10816 + " requires " + r.permission);
10817 return new ServiceLookupResult(null, r.permission);
10818 }
10819 return new ServiceLookupResult(r, null);
10820 }
10821 return null;
10822 }
10823
10824 private class ServiceRestarter implements Runnable {
10825 private ServiceRecord mService;
10826
10827 void setService(ServiceRecord service) {
10828 mService = service;
10829 }
10830
10831 public void run() {
10832 synchronized(ActivityManagerService.this) {
10833 performServiceRestartLocked(mService);
10834 }
10835 }
10836 }
10837
10838 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010839 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070010841 if (DEBUG_SERVICE)
10842 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010843 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070010844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010846 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010847 }
Amith Yamasani742a6712011-05-04 14:49:28 -070010848 if (r == null) {
10849 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010850 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 if (r == null) {
10853 try {
10854 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070010855 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070010856 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 ServiceInfo sInfo =
10858 rInfo != null ? rInfo.serviceInfo : null;
10859 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010860 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010861 ": not found");
10862 return null;
10863 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010864 if (userId > 0) {
10865 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070010866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 ComponentName name = new ComponentName(
10868 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010869 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010870 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010871 Intent.FilterComparison filter = new Intent.FilterComparison(
10872 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010873 ServiceRestarter res = new ServiceRestarter();
10874 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10875 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10876 synchronized (stats) {
10877 ss = stats.getServiceStatsLocked(
10878 sInfo.applicationInfo.uid, sInfo.packageName,
10879 sInfo.name);
10880 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080010881 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010882 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070010883 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
10884 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010885
10886 // Make sure this component isn't in the pending list.
10887 int N = mPendingServices.size();
10888 for (int i=0; i<N; i++) {
10889 ServiceRecord pr = mPendingServices.get(i);
10890 if (pr.name.equals(name)) {
10891 mPendingServices.remove(i);
10892 i--;
10893 N--;
10894 }
10895 }
10896 }
10897 } catch (RemoteException ex) {
10898 // pm is in same process, this will never happen.
10899 }
10900 }
10901 if (r != null) {
10902 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010903 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010905 if (!r.exported) {
10906 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
10907 + " from pid=" + callingPid
10908 + ", uid=" + callingUid
10909 + " that is not exported from uid " + r.appInfo.uid);
10910 return new ServiceLookupResult(null, "not exported from uid "
10911 + r.appInfo.uid);
10912 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080010913 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080010914 + " from pid=" + callingPid
10915 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 + " requires " + r.permission);
10917 return new ServiceLookupResult(null, r.permission);
10918 }
10919 return new ServiceLookupResult(r, null);
10920 }
10921 return null;
10922 }
10923
Dianne Hackborn287952c2010-09-22 22:34:31 -070010924 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
10925 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
10926 + why + " of " + r + " in app " + r.app);
10927 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
10928 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010929 long now = SystemClock.uptimeMillis();
10930 if (r.executeNesting == 0 && r.app != null) {
10931 if (r.app.executingServices.size() == 0) {
10932 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
10933 msg.obj = r.app;
10934 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
10935 }
10936 r.app.executingServices.add(r);
10937 }
10938 r.executeNesting++;
10939 r.executingStart = now;
10940 }
10941
10942 private final void sendServiceArgsLocked(ServiceRecord r,
10943 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010944 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010945 if (N == 0) {
10946 return;
10947 }
10948
Dianne Hackborn39792d22010-08-19 18:01:52 -070010949 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010950 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070010951 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010952 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
10953 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080010954 if (si.intent == null && N > 1) {
10955 // If somehow we got a dummy null intent in the middle,
10956 // then skip it. DO NOT skip a null intent when it is
10957 // the only one in the list -- this is to support the
10958 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010959 continue;
10960 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070010961 si.deliveredTime = SystemClock.uptimeMillis();
10962 r.deliveredStarts.add(si);
10963 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080010964 if (si.neededGrants != null) {
10965 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
10966 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070010967 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070010968 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010969 if (!oomAdjusted) {
10970 oomAdjusted = true;
10971 updateOomAdjLocked(r.app);
10972 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010973 int flags = 0;
10974 if (si.deliveryCount > 0) {
10975 flags |= Service.START_FLAG_RETRY;
10976 }
10977 if (si.doneExecutingCount > 0) {
10978 flags |= Service.START_FLAG_REDELIVERY;
10979 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070010980 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010981 } catch (RemoteException e) {
10982 // Remote process gone... we'll let the normal cleanup take
10983 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010984 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010985 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010986 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010987 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010988 break;
10989 }
10990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 }
10992
10993 private final boolean requestServiceBindingLocked(ServiceRecord r,
10994 IntentBindRecord i, boolean rebind) {
10995 if (r.app == null || r.app.thread == null) {
10996 // If service is not currently running, can't yet bind.
10997 return false;
10998 }
10999 if ((!i.requested || rebind) && i.apps.size() > 0) {
11000 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011001 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011002 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11003 if (!rebind) {
11004 i.requested = true;
11005 }
11006 i.hasBound = true;
11007 i.doRebind = false;
11008 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011009 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011010 return false;
11011 }
11012 }
11013 return true;
11014 }
11015
11016 private final void requestServiceBindingsLocked(ServiceRecord r) {
11017 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11018 while (bindings.hasNext()) {
11019 IntentBindRecord i = bindings.next();
11020 if (!requestServiceBindingLocked(r, i, false)) {
11021 break;
11022 }
11023 }
11024 }
11025
11026 private final void realStartServiceLocked(ServiceRecord r,
11027 ProcessRecord app) throws RemoteException {
11028 if (app.thread == null) {
11029 throw new RemoteException();
11030 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011031 if (DEBUG_MU)
11032 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011033 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011034 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011035 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036
11037 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011038 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011039 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040
11041 boolean created = false;
11042 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011043 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011044 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011045 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011047 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048 synchronized (r.stats.getBatteryStats()) {
11049 r.stats.startLaunchedLocked();
11050 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011051 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011052 app.thread.scheduleCreateService(r, r.serviceInfo,
11053 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011054 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 created = true;
11056 } finally {
11057 if (!created) {
11058 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011059 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011060 }
11061 }
11062
11063 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011064
11065 // If the service is in the started state, and there are no
11066 // pending arguments, then fake up one so its onStartCommand() will
11067 // be called.
11068 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011069 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011070 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011071 }
11072
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011073 sendServiceArgsLocked(r, true);
11074 }
11075
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011076 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11077 boolean allowCancel) {
11078 boolean canceled = false;
11079
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011080 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011081 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011082 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011083
Dianne Hackborn070783f2010-12-29 16:46:28 -080011084 if ((r.serviceInfo.applicationInfo.flags
11085 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11086 minDuration /= 4;
11087 }
11088
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011089 // Any delivered but not yet finished starts should be put back
11090 // on the pending list.
11091 final int N = r.deliveredStarts.size();
11092 if (N > 0) {
11093 for (int i=N-1; i>=0; i--) {
11094 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011095 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011096 if (si.intent == null) {
11097 // We'll generate this again if needed.
11098 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11099 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11100 r.pendingStarts.add(0, si);
11101 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11102 dur *= 2;
11103 if (minDuration < dur) minDuration = dur;
11104 if (resetTime < dur) resetTime = dur;
11105 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011106 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011107 + r.name);
11108 canceled = true;
11109 }
11110 }
11111 r.deliveredStarts.clear();
11112 }
11113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011114 r.totalRestartCount++;
11115 if (r.restartDelay == 0) {
11116 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011117 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 } else {
11119 // If it has been a "reasonably long time" since the service
11120 // was started, then reset our restart duration back to
11121 // the beginning, so we don't infinitely increase the duration
11122 // on a service that just occasionally gets killed (which is
11123 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011124 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011125 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011126 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011127 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011128 if ((r.serviceInfo.applicationInfo.flags
11129 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11130 // Services in peristent processes will restart much more
11131 // quickly, since they are pretty important. (Think SystemUI).
11132 r.restartDelay += minDuration/2;
11133 } else {
11134 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11135 if (r.restartDelay < minDuration) {
11136 r.restartDelay = minDuration;
11137 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011139 }
11140 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011141
11142 r.nextRestartTime = now + r.restartDelay;
11143
11144 // Make sure that we don't end up restarting a bunch of services
11145 // all at the same time.
11146 boolean repeat;
11147 do {
11148 repeat = false;
11149 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11150 ServiceRecord r2 = mRestartingServices.get(i);
11151 if (r2 != r && r.nextRestartTime
11152 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11153 && r.nextRestartTime
11154 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11155 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11156 r.restartDelay = r.nextRestartTime - now;
11157 repeat = true;
11158 break;
11159 }
11160 }
11161 } while (repeat);
11162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163 if (!mRestartingServices.contains(r)) {
11164 mRestartingServices.add(r);
11165 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011166
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011167 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011168
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011170 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011171 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011172 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011174 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175 r.shortName, r.restartDelay);
11176
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011177 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 }
11179
11180 final void performServiceRestartLocked(ServiceRecord r) {
11181 if (!mRestartingServices.contains(r)) {
11182 return;
11183 }
11184 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11185 }
11186
11187 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11188 if (r.restartDelay == 0) {
11189 return false;
11190 }
11191 r.resetRestartCounter();
11192 mRestartingServices.remove(r);
11193 mHandler.removeCallbacks(r.restarter);
11194 return true;
11195 }
11196
11197 private final boolean bringUpServiceLocked(ServiceRecord r,
11198 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011199 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011200 //r.dump(" ");
11201
Dianne Hackborn36124872009-10-08 16:22:03 -070011202 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011203 sendServiceArgsLocked(r, false);
11204 return true;
11205 }
11206
11207 if (!whileRestarting && r.restartDelay > 0) {
11208 // If waiting for a restart, then do nothing.
11209 return true;
11210 }
11211
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011212 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011214 // We are now bringing the service up, so no longer in the
11215 // restarting state.
11216 mRestartingServices.remove(r);
11217
Dianne Hackborne7f97212011-02-24 14:40:20 -080011218 // Service is now being launched, its package can't be stopped.
11219 try {
11220 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011221 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011222 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011223 } catch (IllegalArgumentException e) {
11224 Slog.w(TAG, "Failed trying to unstop package "
11225 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011226 }
11227
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011228 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011229 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011230 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011231
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011232 if (!isolated) {
11233 app = getProcessRecordLocked(appName, r.appInfo.uid);
11234 if (DEBUG_MU)
11235 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11236 if (app != null && app.thread != null) {
11237 try {
11238 app.addPackage(r.appInfo.packageName);
11239 realStartServiceLocked(r, app);
11240 return true;
11241 } catch (RemoteException e) {
11242 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11243 }
11244
11245 // If a dead object exception was thrown -- fall through to
11246 // restart the application.
11247 }
11248 } else {
11249 // If this service runs in an isolated process, then each time
11250 // we call startProcessLocked() we will get a new isolated
11251 // process, starting another process if we are currently waiting
11252 // for a previous process to come up. To deal with this, we store
11253 // in the service any current isolated process it is running in or
11254 // waiting to have come up.
11255 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 }
11257
Dianne Hackborn36124872009-10-08 16:22:03 -070011258 // Not running -- get it started, and enqueue this service record
11259 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011260 if (app == null) {
11261 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11262 "service", r.name, false, isolated)) == null) {
11263 Slog.w(TAG, "Unable to launch app "
11264 + r.appInfo.packageName + "/"
11265 + r.appInfo.uid + " for service "
11266 + r.intent.getIntent() + ": process is bad");
11267 bringDownServiceLocked(r, true);
11268 return false;
11269 }
11270 if (isolated) {
11271 r.isolatedProc = app;
11272 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011273 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011275 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011276 mPendingServices.add(r);
11277 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011279 return true;
11280 }
11281
11282 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011283 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 //r.dump(" ");
11285
11286 // Does it still need to run?
11287 if (!force && r.startRequested) {
11288 return;
11289 }
11290 if (r.connections.size() > 0) {
11291 if (!force) {
11292 // XXX should probably keep a count of the number of auto-create
11293 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011294 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011296 ArrayList<ConnectionRecord> cr = it.next();
11297 for (int i=0; i<cr.size(); i++) {
11298 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11299 return;
11300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011301 }
11302 }
11303 }
11304
11305 // Report to all of the connections that the service is no longer
11306 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011307 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011309 ArrayList<ConnectionRecord> c = it.next();
11310 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011311 ConnectionRecord cr = c.get(i);
11312 // There is still a connection to the service that is
11313 // being brought down. Mark it as dead.
11314 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011315 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011316 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011317 } catch (Exception e) {
11318 Slog.w(TAG, "Failure disconnecting service " + r.name +
11319 " to connection " + c.get(i).conn.asBinder() +
11320 " (in " + c.get(i).binding.client.processName + ")", e);
11321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011322 }
11323 }
11324 }
11325
11326 // Tell the service that it has been unbound.
11327 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11328 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11329 while (it.hasNext()) {
11330 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011331 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011332 + ": hasBound=" + ibr.hasBound);
11333 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11334 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011335 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011336 updateOomAdjLocked(r.app);
11337 ibr.hasBound = false;
11338 r.app.thread.scheduleUnbindService(r,
11339 ibr.intent.getIntent());
11340 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011341 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011342 + r.shortName, e);
11343 serviceDoneExecutingLocked(r, true);
11344 }
11345 }
11346 }
11347 }
11348
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011349 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011350 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011351 System.identityHashCode(r), r.shortName,
11352 (r.app != null) ? r.app.pid : -1);
11353
Amith Yamasani742a6712011-05-04 14:49:28 -070011354 mServiceMap.removeServiceByName(r.name, r.userId);
11355 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011356 r.totalRestartCount = 0;
11357 unscheduleServiceRestartLocked(r);
11358
11359 // Also make sure it is not on the pending list.
11360 int N = mPendingServices.size();
11361 for (int i=0; i<N; i++) {
11362 if (mPendingServices.get(i) == r) {
11363 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011364 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 i--;
11366 N--;
11367 }
11368 }
11369
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011370 r.cancelNotification();
11371 r.isForeground = false;
11372 r.foregroundId = 0;
11373 r.foregroundNoti = null;
11374
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011375 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011376 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011377 r.pendingStarts.clear();
11378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 if (r.app != null) {
11380 synchronized (r.stats.getBatteryStats()) {
11381 r.stats.stopLaunchedLocked();
11382 }
11383 r.app.services.remove(r);
11384 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011385 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011386 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 mStoppingServices.add(r);
11388 updateOomAdjLocked(r.app);
11389 r.app.thread.scheduleStopService(r);
11390 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011391 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392 + r.shortName, e);
11393 serviceDoneExecutingLocked(r, true);
11394 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011395 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011396 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011397 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011398 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 }
11400 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011401 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011402 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011403 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011404
11405 if (r.bindings.size() > 0) {
11406 r.bindings.clear();
11407 }
11408
11409 if (r.restarter instanceof ServiceRestarter) {
11410 ((ServiceRestarter)r.restarter).setService(null);
11411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 }
11413
11414 ComponentName startServiceLocked(IApplicationThread caller,
11415 Intent service, String resolvedType,
11416 int callingPid, int callingUid) {
11417 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011418 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011419 + " type=" + resolvedType + " args=" + service.getExtras());
11420
11421 if (caller != null) {
11422 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11423 if (callerApp == null) {
11424 throw new SecurityException(
11425 "Unable to find app for caller " + caller
11426 + " (pid=" + Binder.getCallingPid()
11427 + ") when starting service " + service);
11428 }
11429 }
11430
11431 ServiceLookupResult res =
11432 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011433 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 if (res == null) {
11435 return null;
11436 }
11437 if (res.record == null) {
11438 return new ComponentName("!", res.permission != null
11439 ? res.permission : "private to package");
11440 }
11441 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011442 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11443 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011445 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 }
11447 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011448 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011449 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011450 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011451 r.lastActivity = SystemClock.uptimeMillis();
11452 synchronized (r.stats.getBatteryStats()) {
11453 r.stats.startRunningLocked();
11454 }
11455 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11456 return new ComponentName("!", "Service process is bad");
11457 }
11458 return r.name;
11459 }
11460 }
11461
11462 public ComponentName startService(IApplicationThread caller, Intent service,
11463 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011464 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011465 // Refuse possible leaked file descriptors
11466 if (service != null && service.hasFileDescriptors() == true) {
11467 throw new IllegalArgumentException("File descriptors passed in Intent");
11468 }
11469
Amith Yamasani742a6712011-05-04 14:49:28 -070011470 if (DEBUG_SERVICE)
11471 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011472 synchronized(this) {
11473 final int callingPid = Binder.getCallingPid();
11474 final int callingUid = Binder.getCallingUid();
11475 final long origId = Binder.clearCallingIdentity();
11476 ComponentName res = startServiceLocked(caller, service,
11477 resolvedType, callingPid, callingUid);
11478 Binder.restoreCallingIdentity(origId);
11479 return res;
11480 }
11481 }
11482
11483 ComponentName startServiceInPackage(int uid,
11484 Intent service, String resolvedType) {
11485 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011486 if (DEBUG_SERVICE)
11487 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011488 final long origId = Binder.clearCallingIdentity();
11489 ComponentName res = startServiceLocked(null, service,
11490 resolvedType, -1, uid);
11491 Binder.restoreCallingIdentity(origId);
11492 return res;
11493 }
11494 }
11495
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011496 private void stopServiceLocked(ServiceRecord service) {
11497 synchronized (service.stats.getBatteryStats()) {
11498 service.stats.stopRunningLocked();
11499 }
11500 service.startRequested = false;
11501 service.callStart = false;
11502 bringDownServiceLocked(service, false);
11503 }
11504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011505 public int stopService(IApplicationThread caller, Intent service,
11506 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011507 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011508 // Refuse possible leaked file descriptors
11509 if (service != null && service.hasFileDescriptors() == true) {
11510 throw new IllegalArgumentException("File descriptors passed in Intent");
11511 }
11512
11513 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011514 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011515 + " type=" + resolvedType);
11516
11517 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11518 if (caller != null && callerApp == null) {
11519 throw new SecurityException(
11520 "Unable to find app for caller " + caller
11521 + " (pid=" + Binder.getCallingPid()
11522 + ") when stopping service " + service);
11523 }
11524
11525 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011526 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11527 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011528 if (r != null) {
11529 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011531 try {
11532 stopServiceLocked(r.record);
11533 } finally {
11534 Binder.restoreCallingIdentity(origId);
11535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011536 return 1;
11537 }
11538 return -1;
11539 }
11540 }
11541
11542 return 0;
11543 }
11544
11545 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011546 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 // Refuse possible leaked file descriptors
11548 if (service != null && service.hasFileDescriptors() == true) {
11549 throw new IllegalArgumentException("File descriptors passed in Intent");
11550 }
11551
11552 IBinder ret = null;
11553
11554 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011555 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11556 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011557
11558 if (r != null) {
11559 // r.record is null if findServiceLocked() failed the caller permission check
11560 if (r.record == null) {
11561 throw new SecurityException(
11562 "Permission Denial: Accessing service " + r.record.name
11563 + " from pid=" + Binder.getCallingPid()
11564 + ", uid=" + Binder.getCallingUid()
11565 + " requires " + r.permission);
11566 }
11567 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11568 if (ib != null) {
11569 ret = ib.binder;
11570 }
11571 }
11572 }
11573
11574 return ret;
11575 }
11576
11577 public boolean stopServiceToken(ComponentName className, IBinder token,
11578 int startId) {
11579 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011580 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011581 + " " + token + " startId=" + startId);
11582 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011583 if (r != null) {
11584 if (startId >= 0) {
11585 // Asked to only stop if done with all work. Note that
11586 // to avoid leaks, we will take this as dropping all
11587 // start items up to and including this one.
11588 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11589 if (si != null) {
11590 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011591 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11592 cur.removeUriPermissionsLocked();
11593 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011594 break;
11595 }
11596 }
11597 }
11598
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011599 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011600 return false;
11601 }
11602
11603 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011604 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011605 + " is last, but have " + r.deliveredStarts.size()
11606 + " remaining args");
11607 }
11608 }
11609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 synchronized (r.stats.getBatteryStats()) {
11611 r.stats.stopRunningLocked();
11612 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011613 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 }
11615 final long origId = Binder.clearCallingIdentity();
11616 bringDownServiceLocked(r, false);
11617 Binder.restoreCallingIdentity(origId);
11618 return true;
11619 }
11620 }
11621 return false;
11622 }
11623
11624 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011625 int id, Notification notification, boolean removeNotification) {
11626 final long origId = Binder.clearCallingIdentity();
11627 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 synchronized(this) {
11629 ServiceRecord r = findServiceLocked(className, token);
11630 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011631 if (id != 0) {
11632 if (notification == null) {
11633 throw new IllegalArgumentException("null notification");
11634 }
11635 if (r.foregroundId != id) {
11636 r.cancelNotification();
11637 r.foregroundId = id;
11638 }
11639 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11640 r.foregroundNoti = notification;
11641 r.isForeground = true;
11642 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011643 if (r.app != null) {
11644 updateServiceForegroundLocked(r.app, true);
11645 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011646 } else {
11647 if (r.isForeground) {
11648 r.isForeground = false;
11649 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011650 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011651 updateServiceForegroundLocked(r.app, true);
11652 }
11653 }
11654 if (removeNotification) {
11655 r.cancelNotification();
11656 r.foregroundId = 0;
11657 r.foregroundNoti = null;
11658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 }
11660 }
11661 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011662 } finally {
11663 Binder.restoreCallingIdentity(origId);
11664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011665 }
11666
11667 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11668 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011669 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670 if (sr.isForeground) {
11671 anyForeground = true;
11672 break;
11673 }
11674 }
11675 if (anyForeground != proc.foregroundServices) {
11676 proc.foregroundServices = anyForeground;
11677 if (oomAdj) {
11678 updateOomAdjLocked();
11679 }
11680 }
11681 }
11682
11683 public int bindService(IApplicationThread caller, IBinder token,
11684 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011685 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011686 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 // Refuse possible leaked file descriptors
11688 if (service != null && service.hasFileDescriptors() == true) {
11689 throw new IllegalArgumentException("File descriptors passed in Intent");
11690 }
11691
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011692 checkValidCaller(Binder.getCallingUid(), userId);
11693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011694 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011695 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011696 + " type=" + resolvedType + " conn=" + connection.asBinder()
11697 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011698 if (DEBUG_MU)
11699 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11700 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11702 if (callerApp == null) {
11703 throw new SecurityException(
11704 "Unable to find app for caller " + caller
11705 + " (pid=" + Binder.getCallingPid()
11706 + ") when binding service " + service);
11707 }
11708
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011709 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011711 activity = mMainStack.isInStackLocked(token);
11712 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011713 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 return 0;
11715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011716 }
11717
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011718 int clientLabel = 0;
11719 PendingIntent clientIntent = null;
11720
11721 if (callerApp.info.uid == Process.SYSTEM_UID) {
11722 // Hacky kind of thing -- allow system stuff to tell us
11723 // what they are, so we can report this elsewhere for
11724 // others to know why certain services are running.
11725 try {
11726 clientIntent = (PendingIntent)service.getParcelableExtra(
11727 Intent.EXTRA_CLIENT_INTENT);
11728 } catch (RuntimeException e) {
11729 }
11730 if (clientIntent != null) {
11731 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
11732 if (clientLabel != 0) {
11733 // There are no useful extras in the intent, trash them.
11734 // System code calling with this stuff just needs to know
11735 // this will happen.
11736 service = service.cloneFilter();
11737 }
11738 }
11739 }
11740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 ServiceLookupResult res =
11742 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011743 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 if (res == null) {
11745 return 0;
11746 }
11747 if (res.record == null) {
11748 return -1;
11749 }
11750 ServiceRecord s = res.record;
11751
11752 final long origId = Binder.clearCallingIdentity();
11753
11754 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011755 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011756 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 }
11758
11759 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
11760 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011761 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011762
11763 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011764 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11765 if (clist == null) {
11766 clist = new ArrayList<ConnectionRecord>();
11767 s.connections.put(binder, clist);
11768 }
11769 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 b.connections.add(c);
11771 if (activity != null) {
11772 if (activity.connections == null) {
11773 activity.connections = new HashSet<ConnectionRecord>();
11774 }
11775 activity.connections.add(c);
11776 }
11777 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011778 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11779 b.client.hasAboveClient = true;
11780 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011781 clist = mServiceConnections.get(binder);
11782 if (clist == null) {
11783 clist = new ArrayList<ConnectionRecord>();
11784 mServiceConnections.put(binder, clist);
11785 }
11786 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787
11788 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
11789 s.lastActivity = SystemClock.uptimeMillis();
11790 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
11791 return 0;
11792 }
11793 }
11794
11795 if (s.app != null) {
11796 // This could have made the service more important.
11797 updateOomAdjLocked(s.app);
11798 }
11799
Joe Onorato8a9b2202010-02-26 18:56:32 -080011800 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 + ": received=" + b.intent.received
11802 + " apps=" + b.intent.apps.size()
11803 + " doRebind=" + b.intent.doRebind);
11804
11805 if (s.app != null && b.intent.received) {
11806 // Service is already running, so we can immediately
11807 // publish the connection.
11808 try {
11809 c.conn.connected(s.name, b.intent.binder);
11810 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011811 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011812 + " to connection " + c.conn.asBinder()
11813 + " (in " + c.binding.client.processName + ")", e);
11814 }
11815
11816 // If this is the first app connected back to this binding,
11817 // and the service had previously asked to be told when
11818 // rebound, then do so.
11819 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
11820 requestServiceBindingLocked(s, b.intent, true);
11821 }
11822 } else if (!b.intent.requested) {
11823 requestServiceBindingLocked(s, b.intent, false);
11824 }
11825
11826 Binder.restoreCallingIdentity(origId);
11827 }
11828
11829 return 1;
11830 }
11831
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070011832 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011833 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 IBinder binder = c.conn.asBinder();
11835 AppBindRecord b = c.binding;
11836 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011837 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
11838 if (clist != null) {
11839 clist.remove(c);
11840 if (clist.size() == 0) {
11841 s.connections.remove(binder);
11842 }
11843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 b.connections.remove(c);
11845 if (c.activity != null && c.activity != skipAct) {
11846 if (c.activity.connections != null) {
11847 c.activity.connections.remove(c);
11848 }
11849 }
11850 if (b.client != skipApp) {
11851 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070011852 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
11853 b.client.updateHasAboveClientLocked();
11854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011856 clist = mServiceConnections.get(binder);
11857 if (clist != null) {
11858 clist.remove(c);
11859 if (clist.size() == 0) {
11860 mServiceConnections.remove(binder);
11861 }
11862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863
11864 if (b.connections.size() == 0) {
11865 b.intent.apps.remove(b.client);
11866 }
11867
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011868 if (!c.serviceDead) {
11869 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
11870 + ": shouldUnbind=" + b.intent.hasBound);
11871 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
11872 && b.intent.hasBound) {
11873 try {
11874 bumpServiceExecutingLocked(s, "unbind");
11875 updateOomAdjLocked(s.app);
11876 b.intent.hasBound = false;
11877 // Assume the client doesn't want to know about a rebind;
11878 // we will deal with that later if it asks for one.
11879 b.intent.doRebind = false;
11880 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
11881 } catch (Exception e) {
11882 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
11883 serviceDoneExecutingLocked(s, true);
11884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011885 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011886
11887 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
11888 bringDownServiceLocked(s, false);
11889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011890 }
11891 }
11892
11893 public boolean unbindService(IServiceConnection connection) {
11894 synchronized (this) {
11895 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011896 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011897 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
11898 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011899 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 + connection.asBinder());
11901 return false;
11902 }
11903
11904 final long origId = Binder.clearCallingIdentity();
11905
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011906 while (clist.size() > 0) {
11907 ConnectionRecord r = clist.get(0);
11908 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011910 if (r.binding.service.app != null) {
11911 // This could have made the service less important.
11912 updateOomAdjLocked(r.binding.service.app);
11913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011914 }
11915
11916 Binder.restoreCallingIdentity(origId);
11917 }
11918
11919 return true;
11920 }
11921
11922 public void publishService(IBinder token, Intent intent, IBinder service) {
11923 // Refuse possible leaked file descriptors
11924 if (intent != null && intent.hasFileDescriptors() == true) {
11925 throw new IllegalArgumentException("File descriptors passed in Intent");
11926 }
11927
11928 synchronized(this) {
11929 if (!(token instanceof ServiceRecord)) {
11930 throw new IllegalArgumentException("Invalid service token");
11931 }
11932 ServiceRecord r = (ServiceRecord)token;
11933
11934 final long origId = Binder.clearCallingIdentity();
11935
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011936 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011937 + " " + intent + ": " + service);
11938 if (r != null) {
11939 Intent.FilterComparison filter
11940 = new Intent.FilterComparison(intent);
11941 IntentBindRecord b = r.bindings.get(filter);
11942 if (b != null && !b.received) {
11943 b.binder = service;
11944 b.requested = true;
11945 b.received = true;
11946 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011947 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011948 = r.connections.values().iterator();
11949 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011950 ArrayList<ConnectionRecord> clist = it.next();
11951 for (int i=0; i<clist.size(); i++) {
11952 ConnectionRecord c = clist.get(i);
11953 if (!filter.equals(c.binding.intent.intent)) {
11954 if (DEBUG_SERVICE) Slog.v(
11955 TAG, "Not publishing to: " + c);
11956 if (DEBUG_SERVICE) Slog.v(
11957 TAG, "Bound intent: " + c.binding.intent.intent);
11958 if (DEBUG_SERVICE) Slog.v(
11959 TAG, "Published intent: " + intent);
11960 continue;
11961 }
11962 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
11963 try {
11964 c.conn.connected(r.name, service);
11965 } catch (Exception e) {
11966 Slog.w(TAG, "Failure sending service " + r.name +
11967 " to connection " + c.conn.asBinder() +
11968 " (in " + c.binding.client.processName + ")", e);
11969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 }
11971 }
11972 }
11973 }
11974
11975 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
11976
11977 Binder.restoreCallingIdentity(origId);
11978 }
11979 }
11980 }
11981
11982 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
11983 // Refuse possible leaked file descriptors
11984 if (intent != null && intent.hasFileDescriptors() == true) {
11985 throw new IllegalArgumentException("File descriptors passed in Intent");
11986 }
11987
11988 synchronized(this) {
11989 if (!(token instanceof ServiceRecord)) {
11990 throw new IllegalArgumentException("Invalid service token");
11991 }
11992 ServiceRecord r = (ServiceRecord)token;
11993
11994 final long origId = Binder.clearCallingIdentity();
11995
11996 if (r != null) {
11997 Intent.FilterComparison filter
11998 = new Intent.FilterComparison(intent);
11999 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012000 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 + " at " + b + ": apps="
12002 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012003
12004 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012005 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012006 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012007 // Applications have already bound since the last
12008 // unbind, so just rebind right here.
12009 requestServiceBindingLocked(r, b, true);
12010 } else {
12011 // Note to tell the service the next time there is
12012 // a new client.
12013 b.doRebind = true;
12014 }
12015 }
12016
Per Edelberg78f9fff2010-08-30 20:01:35 +020012017 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012018
12019 Binder.restoreCallingIdentity(origId);
12020 }
12021 }
12022 }
12023
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012024 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012025 synchronized(this) {
12026 if (!(token instanceof ServiceRecord)) {
12027 throw new IllegalArgumentException("Invalid service token");
12028 }
12029 ServiceRecord r = (ServiceRecord)token;
12030 boolean inStopping = mStoppingServices.contains(token);
12031 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012033 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012034 + " with incorrect token: given " + token
12035 + ", expected " + r);
12036 return;
12037 }
12038
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012039 if (type == 1) {
12040 // This is a call from a service start... take care of
12041 // book-keeping.
12042 r.callStart = true;
12043 switch (res) {
12044 case Service.START_STICKY_COMPATIBILITY:
12045 case Service.START_STICKY: {
12046 // We are done with the associated start arguments.
12047 r.findDeliveredStart(startId, true);
12048 // Don't stop if killed.
12049 r.stopIfKilled = false;
12050 break;
12051 }
12052 case Service.START_NOT_STICKY: {
12053 // We are done with the associated start arguments.
12054 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012055 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012056 // There is no more work, and this service
12057 // doesn't want to hang around if killed.
12058 r.stopIfKilled = true;
12059 }
12060 break;
12061 }
12062 case Service.START_REDELIVER_INTENT: {
12063 // We'll keep this item until they explicitly
12064 // call stop for it, but keep track of the fact
12065 // that it was delivered.
12066 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12067 if (si != null) {
12068 si.deliveryCount = 0;
12069 si.doneExecutingCount++;
12070 // Don't stop if killed.
12071 r.stopIfKilled = true;
12072 }
12073 break;
12074 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012075 case Service.START_TASK_REMOVED_COMPLETE: {
12076 // Special processing for onTaskRemoved(). Don't
12077 // impact normal onStartCommand() processing.
12078 r.findDeliveredStart(startId, true);
12079 break;
12080 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012081 default:
12082 throw new IllegalArgumentException(
12083 "Unknown service start result: " + res);
12084 }
12085 if (res == Service.START_STICKY_COMPATIBILITY) {
12086 r.callStart = false;
12087 }
12088 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012089 if (DEBUG_MU)
12090 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12091 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012092 final long origId = Binder.clearCallingIdentity();
12093 serviceDoneExecutingLocked(r, inStopping);
12094 Binder.restoreCallingIdentity(origId);
12095 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012096 Slog.w(TAG, "Done executing unknown service from pid "
12097 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012098 }
12099 }
12100 }
12101
12102 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012103 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12104 + ": nesting=" + r.executeNesting
12105 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012106 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 r.executeNesting--;
12108 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012109 if (DEBUG_SERVICE) Slog.v(TAG,
12110 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 r.app.executingServices.remove(r);
12112 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012113 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12114 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12116 }
12117 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012118 if (DEBUG_SERVICE) Slog.v(TAG,
12119 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012120 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012121 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 }
12123 updateOomAdjLocked(r.app);
12124 }
12125 }
12126
12127 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012128 String anrMessage = null;
12129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012130 synchronized(this) {
12131 if (proc.executingServices.size() == 0 || proc.thread == null) {
12132 return;
12133 }
12134 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12135 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12136 ServiceRecord timeout = null;
12137 long nextTime = 0;
12138 while (it.hasNext()) {
12139 ServiceRecord sr = it.next();
12140 if (sr.executingStart < maxTime) {
12141 timeout = sr;
12142 break;
12143 }
12144 if (sr.executingStart > nextTime) {
12145 nextTime = sr.executingStart;
12146 }
12147 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012148 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012149 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012150 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151 } else {
12152 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12153 msg.obj = proc;
12154 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12155 }
12156 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012157
12158 if (anrMessage != null) {
12159 appNotResponding(proc, null, null, anrMessage);
12160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012161 }
12162
12163 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012164 // BACKUP AND RESTORE
12165 // =========================================================
12166
12167 // Cause the target app to be launched if necessary and its backup agent
12168 // instantiated. The backup agent will invoke backupAgentCreated() on the
12169 // activity manager to announce its creation.
12170 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012171 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012172 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12173
12174 synchronized(this) {
12175 // !!! TODO: currently no check here that we're already bound
12176 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12177 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12178 synchronized (stats) {
12179 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12180 }
12181
Dianne Hackborne7f97212011-02-24 14:40:20 -080012182 // Backup agent is now in use, its package can't be stopped.
12183 try {
12184 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012185 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012186 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012187 } catch (IllegalArgumentException e) {
12188 Slog.w(TAG, "Failed trying to unstop package "
12189 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012190 }
12191
Christopher Tate181fafa2009-05-14 11:12:14 -070012192 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012193 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12194 ? new ComponentName(app.packageName, app.backupAgentName)
12195 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012196 // startProcessLocked() returns existing proc's record if it's already running
12197 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012198 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012199 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012200 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012201 return false;
12202 }
12203
12204 r.app = proc;
12205 mBackupTarget = r;
12206 mBackupAppName = app.packageName;
12207
Christopher Tate6fa95972009-06-05 18:43:55 -070012208 // Try not to kill the process during backup
12209 updateOomAdjLocked(proc);
12210
Christopher Tate181fafa2009-05-14 11:12:14 -070012211 // If the process is already attached, schedule the creation of the backup agent now.
12212 // If it is not yet live, this will be done when it attaches to the framework.
12213 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012214 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012215 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012216 proc.thread.scheduleCreateBackupAgent(app,
12217 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012218 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012219 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012220 }
12221 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012222 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012223 }
12224 // Invariants: at this point, the target app process exists and the application
12225 // is either already running or in the process of coming up. mBackupTarget and
12226 // mBackupAppName describe the app, so that when it binds back to the AM we
12227 // know that it's scheduled for a backup-agent operation.
12228 }
12229
12230 return true;
12231 }
12232
12233 // A backup agent has just come up
12234 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012235 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012236 + " = " + agent);
12237
12238 synchronized(this) {
12239 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012240 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012241 return;
12242 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012243 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012244
Dianne Hackborn06740692010-09-22 22:46:21 -070012245 long oldIdent = Binder.clearCallingIdentity();
12246 try {
12247 IBackupManager bm = IBackupManager.Stub.asInterface(
12248 ServiceManager.getService(Context.BACKUP_SERVICE));
12249 bm.agentConnected(agentPackageName, agent);
12250 } catch (RemoteException e) {
12251 // can't happen; the backup manager service is local
12252 } catch (Exception e) {
12253 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12254 e.printStackTrace();
12255 } finally {
12256 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012257 }
12258 }
12259
12260 // done with this agent
12261 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012262 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012263 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012264 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012265 return;
12266 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012267
12268 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012269 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012270 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012271 return;
12272 }
12273
Christopher Tate181fafa2009-05-14 11:12:14 -070012274 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012275 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012276 return;
12277 }
12278
Christopher Tate6fa95972009-06-05 18:43:55 -070012279 ProcessRecord proc = mBackupTarget.app;
12280 mBackupTarget = null;
12281 mBackupAppName = null;
12282
12283 // Not backing this app up any more; reset its OOM adjustment
12284 updateOomAdjLocked(proc);
12285
Christopher Tatec7b31e32009-06-10 15:49:30 -070012286 // If the app crashed during backup, 'thread' will be null here
12287 if (proc.thread != null) {
12288 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012289 proc.thread.scheduleDestroyBackupAgent(appInfo,
12290 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012291 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012292 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012293 e.printStackTrace();
12294 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012295 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012296 }
12297 }
12298 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012299 // BROADCASTS
12300 // =========================================================
12301
Josh Bartel7f208742010-02-25 11:01:44 -060012302 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012303 List cur) {
12304 final ContentResolver resolver = mContext.getContentResolver();
12305 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12306 if (list == null) {
12307 return cur;
12308 }
12309 int N = list.size();
12310 for (int i=0; i<N; i++) {
12311 Intent intent = list.get(i);
12312 if (filter.match(resolver, intent, true, TAG) >= 0) {
12313 if (cur == null) {
12314 cur = new ArrayList<Intent>();
12315 }
12316 cur.add(intent);
12317 }
12318 }
12319 return cur;
12320 }
12321
Christopher Tatef46723b2012-01-26 14:19:24 -080012322 boolean isPendingBroadcastProcessLocked(int pid) {
12323 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12324 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012326
Christopher Tatef46723b2012-01-26 14:19:24 -080012327 void skipPendingBroadcastLocked(int pid) {
12328 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12329 for (BroadcastQueue queue : mBroadcastQueues) {
12330 queue.skipPendingBroadcastLocked(pid);
12331 }
12332 }
12333
12334 // The app just attached; send any pending broadcasts that it should receive
12335 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12336 boolean didSomething = false;
12337 for (BroadcastQueue queue : mBroadcastQueues) {
12338 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012339 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012340 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012341 }
12342
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012343 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012344 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012345 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012346 synchronized(this) {
12347 ProcessRecord callerApp = null;
12348 if (caller != null) {
12349 callerApp = getRecordForAppLocked(caller);
12350 if (callerApp == null) {
12351 throw new SecurityException(
12352 "Unable to find app for caller " + caller
12353 + " (pid=" + Binder.getCallingPid()
12354 + ") when registering receiver " + receiver);
12355 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012356 if (callerApp.info.uid != Process.SYSTEM_UID &&
12357 !callerApp.pkgList.contains(callerPackage)) {
12358 throw new SecurityException("Given caller package " + callerPackage
12359 + " is not running in process " + callerApp);
12360 }
12361 } else {
12362 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012363 }
12364
12365 List allSticky = null;
12366
12367 // Look for any matching sticky broadcasts...
12368 Iterator actions = filter.actionsIterator();
12369 if (actions != null) {
12370 while (actions.hasNext()) {
12371 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012372 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 }
12374 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012375 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012376 }
12377
12378 // The first sticky in the list is returned directly back to
12379 // the client.
12380 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12381
Joe Onorato8a9b2202010-02-26 18:56:32 -080012382 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012383 + ": " + sticky);
12384
12385 if (receiver == null) {
12386 return sticky;
12387 }
12388
12389 ReceiverList rl
12390 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12391 if (rl == null) {
12392 rl = new ReceiverList(this, callerApp,
12393 Binder.getCallingPid(),
12394 Binder.getCallingUid(), receiver);
12395 if (rl.app != null) {
12396 rl.app.receivers.add(rl);
12397 } else {
12398 try {
12399 receiver.asBinder().linkToDeath(rl, 0);
12400 } catch (RemoteException e) {
12401 return sticky;
12402 }
12403 rl.linkedToDeath = true;
12404 }
12405 mRegisteredReceivers.put(receiver.asBinder(), rl);
12406 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012407 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012408 rl.add(bf);
12409 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012410 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012411 }
12412 mReceiverResolver.addFilter(bf);
12413
12414 // Enqueue broadcasts for all existing stickies that match
12415 // this filter.
12416 if (allSticky != null) {
12417 ArrayList receivers = new ArrayList();
12418 receivers.add(bf);
12419
12420 int N = allSticky.size();
12421 for (int i=0; i<N; i++) {
12422 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012423 BroadcastQueue queue = broadcastQueueForIntent(intent);
12424 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012425 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012426 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012427 queue.enqueueParallelBroadcastLocked(r);
12428 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 }
12430 }
12431
12432 return sticky;
12433 }
12434 }
12435
12436 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012437 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012438
Christopher Tatef46723b2012-01-26 14:19:24 -080012439 final long origId = Binder.clearCallingIdentity();
12440 try {
12441 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442
Christopher Tatef46723b2012-01-26 14:19:24 -080012443 synchronized(this) {
12444 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012445 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 if (rl != null) {
12447 if (rl.curBroadcast != null) {
12448 BroadcastRecord r = rl.curBroadcast;
12449 final boolean doNext = finishReceiverLocked(
12450 receiver.asBinder(), r.resultCode, r.resultData,
12451 r.resultExtras, r.resultAbort, true);
12452 if (doNext) {
12453 doTrim = true;
12454 r.queue.processNextBroadcast(false);
12455 }
12456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457
Christopher Tatef46723b2012-01-26 14:19:24 -080012458 if (rl.app != null) {
12459 rl.app.receivers.remove(rl);
12460 }
12461 removeReceiverLocked(rl);
12462 if (rl.linkedToDeath) {
12463 rl.linkedToDeath = false;
12464 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 }
12467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012468
Christopher Tatef46723b2012-01-26 14:19:24 -080012469 // If we actually concluded any broadcasts, we might now be able
12470 // to trim the recipients' apps from our working set
12471 if (doTrim) {
12472 trimApplications();
12473 return;
12474 }
12475
12476 } finally {
12477 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479 }
12480
12481 void removeReceiverLocked(ReceiverList rl) {
12482 mRegisteredReceivers.remove(rl.receiver.asBinder());
12483 int N = rl.size();
12484 for (int i=0; i<N; i++) {
12485 mReceiverResolver.removeFilter(rl.get(i));
12486 }
12487 }
12488
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012489 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12490 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12491 ProcessRecord r = mLruProcesses.get(i);
12492 if (r.thread != null) {
12493 try {
12494 r.thread.dispatchPackageBroadcast(cmd, packages);
12495 } catch (RemoteException ex) {
12496 }
12497 }
12498 }
12499 }
12500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012501 private final int broadcastIntentLocked(ProcessRecord callerApp,
12502 String callerPackage, Intent intent, String resolvedType,
12503 IIntentReceiver resultTo, int resultCode, String resultData,
12504 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012505 boolean ordered, boolean sticky, int callingPid, int callingUid,
12506 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012507 intent = new Intent(intent);
12508
Dianne Hackborne7f97212011-02-24 14:40:20 -080012509 // By default broadcasts do not go to stopped apps.
12510 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12511
Joe Onorato8a9b2202010-02-26 18:56:32 -080012512 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012513 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012514 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012516 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012517 }
12518
12519 // Handle special intents: if this broadcast is from the package
12520 // manager about a package being removed, we need to remove all of
12521 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012522 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012524 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12525 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012526 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012527 || uidRemoved) {
12528 if (checkComponentPermission(
12529 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012530 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012531 == PackageManager.PERMISSION_GRANTED) {
12532 if (uidRemoved) {
12533 final Bundle intentExtras = intent.getExtras();
12534 final int uid = intentExtras != null
12535 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12536 if (uid >= 0) {
12537 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12538 synchronized (bs) {
12539 bs.removeUidStatsLocked(uid);
12540 }
12541 }
12542 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012543 // If resources are unvailble just force stop all
12544 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012545 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012546 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12547 if (list != null && (list.length > 0)) {
12548 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012549 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012550 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012551 sendPackageBroadcastLocked(
12552 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012553 }
12554 } else {
12555 Uri data = intent.getData();
12556 String ssp;
12557 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12558 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12559 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012560 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12561 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012562 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012563 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012564 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12565 new String[] {ssp});
12566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012567 }
12568 }
12569 }
12570 } else {
12571 String msg = "Permission Denial: " + intent.getAction()
12572 + " broadcast from " + callerPackage + " (pid=" + callingPid
12573 + ", uid=" + callingUid + ")"
12574 + " requires "
12575 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012576 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012577 throw new SecurityException(msg);
12578 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012579
12580 // Special case for adding a package: by default turn on compatibility
12581 // mode.
12582 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012583 Uri data = intent.getData();
12584 String ssp;
12585 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12586 mCompatModePackages.handlePackageAddedLocked(ssp,
12587 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012588 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 }
12590
12591 /*
12592 * If this is the time zone changed action, queue up a message that will reset the timezone
12593 * of all currently running processes. This message will get queued up before the broadcast
12594 * happens.
12595 */
12596 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12597 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12598 }
12599
Robert Greenwalt03595d02010-11-02 14:08:23 -070012600 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12601 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12602 }
12603
Robert Greenwalt434203a2010-10-11 16:00:27 -070012604 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12605 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12606 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12607 }
12608
Dianne Hackborn854060af2009-07-09 18:14:31 -070012609 /*
12610 * Prevent non-system code (defined here to be non-persistent
12611 * processes) from sending protected broadcasts.
12612 */
12613 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12614 || callingUid == Process.SHELL_UID || callingUid == 0) {
12615 // Always okay.
12616 } else if (callerApp == null || !callerApp.persistent) {
12617 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012618 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012619 intent.getAction())) {
12620 String msg = "Permission Denial: not allowed to send broadcast "
12621 + intent.getAction() + " from pid="
12622 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012623 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012624 throw new SecurityException(msg);
12625 }
12626 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012627 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012628 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012629 }
12630 }
12631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 // Add to the sticky list if requested.
12633 if (sticky) {
12634 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12635 callingPid, callingUid)
12636 != PackageManager.PERMISSION_GRANTED) {
12637 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12638 + callingPid + ", uid=" + callingUid
12639 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012640 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012641 throw new SecurityException(msg);
12642 }
12643 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012644 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012645 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012646 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012647 }
12648 if (intent.getComponent() != null) {
12649 throw new SecurityException(
12650 "Sticky broadcasts can't target a specific component");
12651 }
12652 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12653 if (list == null) {
12654 list = new ArrayList<Intent>();
12655 mStickyBroadcasts.put(intent.getAction(), list);
12656 }
12657 int N = list.size();
12658 int i;
12659 for (i=0; i<N; i++) {
12660 if (intent.filterEquals(list.get(i))) {
12661 // This sticky already exists, replace it.
12662 list.set(i, new Intent(intent));
12663 break;
12664 }
12665 }
12666 if (i >= N) {
12667 list.add(new Intent(intent));
12668 }
12669 }
12670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 // Figure out who all will receive this broadcast.
12672 List receivers = null;
12673 List<BroadcastFilter> registeredReceivers = null;
12674 try {
12675 if (intent.getComponent() != null) {
12676 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012677 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012678 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012679 if (ai != null) {
12680 receivers = new ArrayList();
12681 ResolveInfo ri = new ResolveInfo();
Amith Yamasani742a6712011-05-04 14:49:28 -070012682 ri.activityInfo = getActivityInfoForUser(ai, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 receivers.add(ri);
12684 }
12685 } else {
12686 // Need to resolve the intent to interested receivers...
12687 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12688 == 0) {
12689 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012690 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012691 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012692 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012693 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12694 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012695 }
12696 } catch (RemoteException ex) {
12697 // pm is in same process, this will never happen.
12698 }
12699
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012700 final boolean replacePending =
12701 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12702
Joe Onorato8a9b2202010-02-26 18:56:32 -080012703 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012704 + " replacePending=" + replacePending);
12705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012706 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12707 if (!ordered && NR > 0) {
12708 // If we are not serializing this broadcast, then send the
12709 // registered receivers separately so they don't wait for the
12710 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012711 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12712 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012713 callerPackage, callingPid, callingUid, requiredPermission,
12714 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012715 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012716 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080012717 TAG, "Enqueueing parallel broadcast " + r);
12718 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012719 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012720 queue.enqueueParallelBroadcastLocked(r);
12721 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 registeredReceivers = null;
12724 NR = 0;
12725 }
12726
12727 // Merge into one list.
12728 int ir = 0;
12729 if (receivers != null) {
12730 // A special case for PACKAGE_ADDED: do not allow the package
12731 // being added to see this broadcast. This prevents them from
12732 // using this as a back door to get run as soon as they are
12733 // installed. Maybe in the future we want to have a special install
12734 // broadcast or such for apps, but we'd like to deliberately make
12735 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012736 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012737 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
12738 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
12739 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012740 Uri data = intent.getData();
12741 if (data != null) {
12742 String pkgName = data.getSchemeSpecificPart();
12743 if (pkgName != null) {
12744 skipPackages = new String[] { pkgName };
12745 }
12746 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012747 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012748 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070012749 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012750 if (skipPackages != null && (skipPackages.length > 0)) {
12751 for (String skipPackage : skipPackages) {
12752 if (skipPackage != null) {
12753 int NT = receivers.size();
12754 for (int it=0; it<NT; it++) {
12755 ResolveInfo curt = (ResolveInfo)receivers.get(it);
12756 if (curt.activityInfo.packageName.equals(skipPackage)) {
12757 receivers.remove(it);
12758 it--;
12759 NT--;
12760 }
12761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012762 }
12763 }
12764 }
12765
12766 int NT = receivers != null ? receivers.size() : 0;
12767 int it = 0;
12768 ResolveInfo curt = null;
12769 BroadcastFilter curr = null;
12770 while (it < NT && ir < NR) {
12771 if (curt == null) {
12772 curt = (ResolveInfo)receivers.get(it);
12773 }
12774 if (curr == null) {
12775 curr = registeredReceivers.get(ir);
12776 }
12777 if (curr.getPriority() >= curt.priority) {
12778 // Insert this broadcast record into the final list.
12779 receivers.add(it, curr);
12780 ir++;
12781 curr = null;
12782 it++;
12783 NT++;
12784 } else {
12785 // Skip to the next ResolveInfo in the final list.
12786 it++;
12787 curt = null;
12788 }
12789 }
12790 }
12791 while (ir < NR) {
12792 if (receivers == null) {
12793 receivers = new ArrayList();
12794 }
12795 receivers.add(registeredReceivers.get(ir));
12796 ir++;
12797 }
12798
12799 if ((receivers != null && receivers.size() > 0)
12800 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012801 BroadcastQueue queue = broadcastQueueForIntent(intent);
12802 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012804 receivers, resultTo, resultCode, resultData, map, ordered,
12805 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012806 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012807 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080012808 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012809 if (DEBUG_BROADCAST) {
12810 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012811 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012812 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012813 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012814 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012815 queue.enqueueOrderedBroadcastLocked(r);
12816 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012818 }
12819
Dianne Hackborna4972e92012-03-14 10:38:05 -070012820 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 }
12822
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012823 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012824 // Refuse possible leaked file descriptors
12825 if (intent != null && intent.hasFileDescriptors() == true) {
12826 throw new IllegalArgumentException("File descriptors passed in Intent");
12827 }
12828
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012829 int flags = intent.getFlags();
12830
12831 if (!mProcessesReady) {
12832 // if the caller really truly claims to know what they're doing, go
12833 // ahead and allow the broadcast without launching any receivers
12834 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
12835 intent = new Intent(intent);
12836 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
12837 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
12838 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
12839 + " before boot completion");
12840 throw new IllegalStateException("Cannot broadcast before boot completed");
12841 }
12842 }
12843
12844 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
12845 throw new IllegalArgumentException(
12846 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
12847 }
12848
12849 return intent;
12850 }
12851
12852 public final int broadcastIntent(IApplicationThread caller,
12853 Intent intent, String resolvedType, IIntentReceiver resultTo,
12854 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012855 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012856 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012857 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012858 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070012859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12861 final int callingPid = Binder.getCallingPid();
12862 final int callingUid = Binder.getCallingUid();
12863 final long origId = Binder.clearCallingIdentity();
12864 int res = broadcastIntentLocked(callerApp,
12865 callerApp != null ? callerApp.info.packageName : null,
12866 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070012867 resultCode, resultData, map, requiredPermission, serialized, sticky,
12868 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012869 Binder.restoreCallingIdentity(origId);
12870 return res;
12871 }
12872 }
12873
12874 int broadcastIntentInPackage(String packageName, int uid,
12875 Intent intent, String resolvedType, IIntentReceiver resultTo,
12876 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070012877 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012878 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070012879 intent = verifyBroadcastLocked(intent);
12880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 final long origId = Binder.clearCallingIdentity();
12882 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
12883 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012884 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 Binder.restoreCallingIdentity(origId);
12886 return res;
12887 }
12888 }
12889
Amith Yamasani742a6712011-05-04 14:49:28 -070012890 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
12891 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012892 // Refuse possible leaked file descriptors
12893 if (intent != null && intent.hasFileDescriptors() == true) {
12894 throw new IllegalArgumentException("File descriptors passed in Intent");
12895 }
12896
12897 synchronized(this) {
12898 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
12899 != PackageManager.PERMISSION_GRANTED) {
12900 String msg = "Permission Denial: unbroadcastIntent() from pid="
12901 + Binder.getCallingPid()
12902 + ", uid=" + Binder.getCallingUid()
12903 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012904 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012905 throw new SecurityException(msg);
12906 }
12907 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12908 if (list != null) {
12909 int N = list.size();
12910 int i;
12911 for (i=0; i<N; i++) {
12912 if (intent.filterEquals(list.get(i))) {
12913 list.remove(i);
12914 break;
12915 }
12916 }
12917 }
12918 }
12919 }
12920
12921 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
12922 String resultData, Bundle resultExtras, boolean resultAbort,
12923 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080012924 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
12925 if (r == null) {
12926 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 return false;
12928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929
Christopher Tatef46723b2012-01-26 14:19:24 -080012930 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
12931 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012932 }
12933
12934 public void finishReceiver(IBinder who, int resultCode, String resultData,
12935 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012936 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937
12938 // Refuse possible leaked file descriptors
12939 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
12940 throw new IllegalArgumentException("File descriptors passed in Bundle");
12941 }
12942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080012944 try {
12945 boolean doNext = false;
12946 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947
Christopher Tatef46723b2012-01-26 14:19:24 -080012948 synchronized(this) {
12949 r = broadcastRecordForReceiverLocked(who);
12950 if (r != null) {
12951 doNext = r.queue.finishReceiverLocked(r, resultCode,
12952 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012954 }
Jeff Brown4d94a762010-09-23 11:33:28 -070012955
Christopher Tatef46723b2012-01-26 14:19:24 -080012956 if (doNext) {
12957 r.queue.processNextBroadcast(false);
12958 }
12959 trimApplications();
12960 } finally {
12961 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012965 // =========================================================
12966 // INSTRUMENTATION
12967 // =========================================================
12968
12969 public boolean startInstrumentation(ComponentName className,
12970 String profileFile, int flags, Bundle arguments,
12971 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012972 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012973 // Refuse possible leaked file descriptors
12974 if (arguments != null && arguments.hasFileDescriptors()) {
12975 throw new IllegalArgumentException("File descriptors passed in Bundle");
12976 }
12977
12978 synchronized(this) {
12979 InstrumentationInfo ii = null;
12980 ApplicationInfo ai = null;
12981 try {
12982 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070012983 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012985 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 } catch (PackageManager.NameNotFoundException e) {
12987 }
12988 if (ii == null) {
12989 reportStartInstrumentationFailure(watcher, className,
12990 "Unable to find instrumentation info for: " + className);
12991 return false;
12992 }
12993 if (ai == null) {
12994 reportStartInstrumentationFailure(watcher, className,
12995 "Unable to find instrumentation target package: " + ii.targetPackage);
12996 return false;
12997 }
12998
12999 int match = mContext.getPackageManager().checkSignatures(
13000 ii.targetPackage, ii.packageName);
13001 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13002 String msg = "Permission Denial: starting instrumentation "
13003 + className + " from pid="
13004 + Binder.getCallingPid()
13005 + ", uid=" + Binder.getCallingPid()
13006 + " not allowed because package " + ii.packageName
13007 + " does not have a signature matching the target "
13008 + ii.targetPackage;
13009 reportStartInstrumentationFailure(watcher, className, msg);
13010 throw new SecurityException(msg);
13011 }
13012
Amith Yamasani483f3b02012-03-13 16:08:00 -070013013 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013015 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013016 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013017 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013018 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013019 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 app.instrumentationProfileFile = profileFile;
13021 app.instrumentationArguments = arguments;
13022 app.instrumentationWatcher = watcher;
13023 app.instrumentationResultClass = className;
13024 Binder.restoreCallingIdentity(origId);
13025 }
13026
13027 return true;
13028 }
13029
13030 /**
13031 * Report errors that occur while attempting to start Instrumentation. Always writes the
13032 * error to the logs, but if somebody is watching, send the report there too. This enables
13033 * the "am" command to report errors with more information.
13034 *
13035 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13036 * @param cn The component name of the instrumentation.
13037 * @param report The error report.
13038 */
13039 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13040 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013041 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013042 try {
13043 if (watcher != null) {
13044 Bundle results = new Bundle();
13045 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13046 results.putString("Error", report);
13047 watcher.instrumentationStatus(cn, -1, results);
13048 }
13049 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013050 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013051 }
13052 }
13053
13054 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13055 if (app.instrumentationWatcher != null) {
13056 try {
13057 // NOTE: IInstrumentationWatcher *must* be oneway here
13058 app.instrumentationWatcher.instrumentationFinished(
13059 app.instrumentationClass,
13060 resultCode,
13061 results);
13062 } catch (RemoteException e) {
13063 }
13064 }
13065 app.instrumentationWatcher = null;
13066 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013067 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013068 app.instrumentationProfileFile = null;
13069 app.instrumentationArguments = null;
13070
Amith Yamasani483f3b02012-03-13 16:08:00 -070013071 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013072 }
13073
13074 public void finishInstrumentation(IApplicationThread target,
13075 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013076 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013077 // Refuse possible leaked file descriptors
13078 if (results != null && results.hasFileDescriptors()) {
13079 throw new IllegalArgumentException("File descriptors passed in Intent");
13080 }
13081
13082 synchronized(this) {
13083 ProcessRecord app = getRecordForAppLocked(target);
13084 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013085 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013086 return;
13087 }
13088 final long origId = Binder.clearCallingIdentity();
13089 finishInstrumentationLocked(app, resultCode, results);
13090 Binder.restoreCallingIdentity(origId);
13091 }
13092 }
13093
13094 // =========================================================
13095 // CONFIGURATION
13096 // =========================================================
13097
13098 public ConfigurationInfo getDeviceConfigurationInfo() {
13099 ConfigurationInfo config = new ConfigurationInfo();
13100 synchronized (this) {
13101 config.reqTouchScreen = mConfiguration.touchscreen;
13102 config.reqKeyboardType = mConfiguration.keyboard;
13103 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013104 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13105 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013106 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13107 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013108 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13109 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13111 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013112 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013113 }
13114 return config;
13115 }
13116
13117 public Configuration getConfiguration() {
13118 Configuration ci;
13119 synchronized(this) {
13120 ci = new Configuration(mConfiguration);
13121 }
13122 return ci;
13123 }
13124
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013125 public void updatePersistentConfiguration(Configuration values) {
13126 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13127 "updateConfiguration()");
13128 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13129 "updateConfiguration()");
13130 if (values == null) {
13131 throw new NullPointerException("Configuration must not be null");
13132 }
13133
13134 synchronized(this) {
13135 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013136 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013137 Binder.restoreCallingIdentity(origId);
13138 }
13139 }
13140
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013141 public void updateConfiguration(Configuration values) {
13142 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13143 "updateConfiguration()");
13144
13145 synchronized(this) {
13146 if (values == null && mWindowManager != null) {
13147 // sentinel: fetch the current configuration from the window manager
13148 values = mWindowManager.computeNewConfiguration();
13149 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013150
13151 if (mWindowManager != null) {
13152 mProcessList.applyDisplaySize(mWindowManager);
13153 }
13154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013156 if (values != null) {
13157 Settings.System.clearConfiguration(values);
13158 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013159 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013160 Binder.restoreCallingIdentity(origId);
13161 }
13162 }
13163
13164 /**
13165 * Do either or both things: (1) change the current configuration, and (2)
13166 * make sure the given activity is running with the (now) current
13167 * configuration. Returns true if the activity has been left running, or
13168 * false if <var>starting</var> is being destroyed to match the new
13169 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013170 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013171 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013172 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013173 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013174 // do nothing if we are headless
13175 if (mHeadless) return true;
13176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 int changes = 0;
13178
13179 boolean kept = true;
13180
13181 if (values != null) {
13182 Configuration newConfig = new Configuration(mConfiguration);
13183 changes = newConfig.updateFrom(values);
13184 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013185 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013186 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 }
13188
Doug Zongker2bec3d42009-12-04 12:52:44 -080013189 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190
Dianne Hackborn813075a62011-11-14 17:45:19 -080013191 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013192 saveLocaleLocked(values.locale,
13193 !values.locale.equals(mConfiguration.locale),
13194 values.userSetLocale);
13195 }
13196
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013197 mConfigurationSeq++;
13198 if (mConfigurationSeq <= 0) {
13199 mConfigurationSeq = 1;
13200 }
13201 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013202 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013203 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013204
13205 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013206
13207 // TODO: If our config changes, should we auto dismiss any currently
13208 // showing dialogs?
13209 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013210
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013211 AttributeCache ac = AttributeCache.instance();
13212 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013213 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013215
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013216 // Make sure all resources in our process are updated
13217 // right now, so that anyone who is going to retrieve
13218 // resource values after we return will be sure to get
13219 // the new ones. This is especially important during
13220 // boot, where the first config change needs to guarantee
13221 // all resources have that config before following boot
13222 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013223 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013224
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013225 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013226 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013227 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013228 mHandler.sendMessage(msg);
13229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013231 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13232 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013233 try {
13234 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013235 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013236 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013237 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238 }
13239 } catch (Exception e) {
13240 }
13241 }
13242 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013243 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13244 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013246 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013247 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13248 broadcastIntentLocked(null, null,
13249 new Intent(Intent.ACTION_LOCALE_CHANGED),
13250 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013251 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 }
13254 }
13255
13256 if (changes != 0 && starting == null) {
13257 // If the configuration changed, and the caller is not already
13258 // in the process of starting an activity, then find the top
13259 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013260 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 }
13262
13263 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013264 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013265 // And we need to make sure at this point that all other activities
13266 // are made visible with the correct configuration.
13267 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013268 }
13269
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013270 if (values != null && mWindowManager != null) {
13271 mWindowManager.setNewConfiguration(mConfiguration);
13272 }
13273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013274 return kept;
13275 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013276
13277 /**
13278 * Decide based on the configuration whether we should shouw the ANR,
13279 * crash, etc dialogs. The idea is that if there is no affordnace to
13280 * press the on-screen buttons, we shouldn't show the dialog.
13281 *
13282 * A thought: SystemUI might also want to get told about this, the Power
13283 * dialog / global actions also might want different behaviors.
13284 */
13285 private static final boolean shouldShowDialogs(Configuration config) {
13286 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13287 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013289
13290 /**
13291 * Save the locale. You must be inside a synchronized (this) block.
13292 */
13293 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13294 if(isDiff) {
13295 SystemProperties.set("user.language", l.getLanguage());
13296 SystemProperties.set("user.region", l.getCountry());
13297 }
13298
13299 if(isPersist) {
13300 SystemProperties.set("persist.sys.language", l.getLanguage());
13301 SystemProperties.set("persist.sys.country", l.getCountry());
13302 SystemProperties.set("persist.sys.localevar", l.getVariant());
13303 }
13304 }
13305
Adam Powelldd8fab22012-03-22 17:47:27 -070013306 @Override
13307 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13308 ActivityRecord srec = ActivityRecord.forToken(token);
13309 return srec.task.affinity != null && srec.task.affinity.equals(destAffinity);
13310 }
13311
13312 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13313 Intent resultData) {
13314 ComponentName dest = destIntent.getComponent();
13315
13316 synchronized (this) {
13317 ActivityRecord srec = ActivityRecord.forToken(token);
13318 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13319 final int start = history.indexOf(srec);
13320 if (start < 0) {
13321 // Current activity is not in history stack; do nothing.
13322 return false;
13323 }
13324 int finishTo = start - 1;
13325 ActivityRecord parent = null;
13326 boolean foundParentInTask = false;
13327 if (dest != null) {
13328 TaskRecord tr = srec.task;
13329 for (int i = start - 1; i >= 0; i--) {
13330 ActivityRecord r = history.get(i);
13331 if (tr != r.task) {
13332 // Couldn't find parent in the same task; stop at the one above this.
13333 // (Root of current task; in-app "home" behavior)
13334 // Always at least finish the current activity.
13335 finishTo = Math.min(start - 1, i + 1);
13336 parent = history.get(finishTo);
13337 break;
13338 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13339 r.info.name.equals(dest.getClassName())) {
13340 finishTo = i;
13341 parent = r;
13342 foundParentInTask = true;
13343 break;
13344 }
13345 }
13346 }
13347
13348 if (mController != null) {
13349 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13350 if (next != null) {
13351 // ask watcher if this is allowed
13352 boolean resumeOK = true;
13353 try {
13354 resumeOK = mController.activityResuming(next.packageName);
13355 } catch (RemoteException e) {
13356 mController = null;
13357 }
13358
13359 if (!resumeOK) {
13360 return false;
13361 }
13362 }
13363 }
13364 final long origId = Binder.clearCallingIdentity();
13365 for (int i = start; i > finishTo; i--) {
13366 ActivityRecord r = history.get(i);
13367 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13368 "navigate-up");
13369 // Only return the supplied result for the first activity finished
13370 resultCode = Activity.RESULT_CANCELED;
13371 resultData = null;
13372 }
13373
13374 if (parent != null && foundParentInTask) {
13375 final int parentLaunchMode = parent.info.launchMode;
13376 final int destIntentFlags = destIntent.getFlags();
13377 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13378 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13379 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13380 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
13381 parent.deliverNewIntentLocked(srec.app.uid, destIntent);
13382 } else {
13383 try {
13384 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13385 destIntent.getComponent(), 0, UserId.getCallingUserId());
13386 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13387 null, aInfo, parent.appToken, null,
13388 0, -1, parent.launchedFromUid, 0, null, true, null);
13389 foundParentInTask = res == ActivityManager.START_SUCCESS;
13390 } catch (RemoteException e) {
13391 foundParentInTask = false;
13392 }
13393 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13394 resultData, "navigate-up");
13395 }
13396 }
13397 Binder.restoreCallingIdentity(origId);
13398 return foundParentInTask;
13399 }
13400 }
13401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 // =========================================================
13403 // LIFETIME MANAGEMENT
13404 // =========================================================
13405
Christopher Tatef46723b2012-01-26 14:19:24 -080013406 // Returns which broadcast queue the app is the current [or imminent] receiver
13407 // on, or 'null' if the app is not an active broadcast recipient.
13408 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13409 BroadcastRecord r = app.curReceiver;
13410 if (r != null) {
13411 return r.queue;
13412 }
13413
13414 // It's not the current receiver, but it might be starting up to become one
13415 synchronized (this) {
13416 for (BroadcastQueue queue : mBroadcastQueues) {
13417 r = queue.mPendingBroadcast;
13418 if (r != null && r.curApp == app) {
13419 // found it; report which queue it's in
13420 return queue;
13421 }
13422 }
13423 }
13424
13425 return null;
13426 }
13427
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013428 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013429 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013430 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013431 // This adjustment has already been computed. If we are calling
13432 // from the top, we may have already computed our adjustment with
13433 // an earlier hidden adjustment that isn't really for us... if
13434 // so, use the new hidden adjustment.
13435 if (!recursed && app.hidden) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013436 app.curAdj = app.curRawAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013437 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013438 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013439 }
13440
13441 if (app.thread == null) {
13442 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013443 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013444 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013445 }
13446
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013447 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13448 app.adjSource = null;
13449 app.adjTarget = null;
13450 app.empty = false;
13451 app.hidden = false;
13452
13453 final int activitiesSize = app.activities.size();
13454
Dianne Hackborn7d608422011-08-07 16:24:18 -070013455 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013456 // The max adjustment doesn't allow this app to be anything
13457 // below foreground, so it is not worth doing work for it.
13458 app.adjType = "fixed";
13459 app.adjSeq = mAdjSeq;
13460 app.curRawAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013461 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013462 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013463 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013464 // System process can do UI, and when they do we want to have
13465 // them trim their memory after the user leaves the UI. To
13466 // facilitate this, here we need to determine whether or not it
13467 // is currently showing UI.
13468 app.systemNoUi = true;
13469 if (app == TOP_APP) {
13470 app.systemNoUi = false;
13471 } else if (activitiesSize > 0) {
13472 for (int j = 0; j < activitiesSize; j++) {
13473 final ActivityRecord r = app.activities.get(j);
13474 if (r.visible) {
13475 app.systemNoUi = false;
13476 break;
13477 }
13478 }
13479 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013480 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013481 }
13482
13483 final boolean hadForegroundActivities = app.foregroundActivities;
13484
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013485 app.foregroundActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013486 app.keeping = false;
13487 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013488
The Android Open Source Project4df24232009-03-05 14:34:35 -080013489 // Determine the importance of the process, starting with most
13490 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013492 int schedGroup;
Christopher Tatef46723b2012-01-26 14:19:24 -080013493 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013494 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013495 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013496 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013497 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013498 app.adjType = "top-activity";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013499 app.foregroundActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013500 } else if (app.instrumentationClass != null) {
13501 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013502 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013503 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013504 app.adjType = "instrumentation";
Christopher Tatef46723b2012-01-26 14:19:24 -080013505 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013506 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013507 // counts as being in the foreground for OOM killer purposes.
13508 // It's placed in a sched group based on the nature of the
13509 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013510 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013511 schedGroup = (queue == mFgBroadcastQueue)
13512 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013513 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013514 } else if (app.executingServices.size() > 0) {
13515 // An app that is currently executing a service callback also
13516 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013517 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013518 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013519 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013520 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013521 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013522 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013523 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013524 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013525 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013526 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013527 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013528 // A very not-needed process. If this is lower in the lru list,
13529 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013530 adj = hiddenAdj;
13531 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013532 app.hidden = true;
13533 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013534 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013535 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013536
13537 // Examine all activities if not already foreground.
13538 if (!app.foregroundActivities && activitiesSize > 0) {
13539 for (int j = 0; j < activitiesSize; j++) {
13540 final ActivityRecord r = app.activities.get(j);
13541 if (r.visible) {
13542 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013543 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13544 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013545 app.adjType = "visible";
13546 }
13547 schedGroup = Process.THREAD_GROUP_DEFAULT;
13548 app.hidden = false;
13549 app.foregroundActivities = true;
13550 break;
13551 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED
13552 || r.state == ActivityState.STOPPING) {
13553 // Only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013554 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13555 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013556 app.adjType = "stopping";
13557 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013558 app.hidden = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013559 app.foregroundActivities = true;
13560 }
13561 }
13562 }
13563
Dianne Hackborn7d608422011-08-07 16:24:18 -070013564 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013565 if (app.foregroundServices) {
13566 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013567 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013568 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013569 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013570 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013571 } else if (app.forcingToForeground != null) {
13572 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013573 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013574 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013575 app.adjType = "force-foreground";
13576 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013577 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013578 }
13579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013580
Dianne Hackborn7d608422011-08-07 16:24:18 -070013581 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013582 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013583 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013584 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013585 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013586 app.adjType = "heavy";
13587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013588
Dianne Hackborn7d608422011-08-07 16:24:18 -070013589 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013590 // This process is hosting what we currently consider to be the
13591 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013592 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013593 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013594 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013595 app.adjType = "home";
13596 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013597
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013598 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13599 && app.activities.size() > 0) {
13600 // This was the previous process that showed UI to the user.
13601 // We want to try to keep it around more aggressively, to give
13602 // a good experience around switching between two apps.
13603 adj = ProcessList.PREVIOUS_APP_ADJ;
13604 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13605 app.hidden = false;
13606 app.adjType = "previous";
13607 }
13608
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013609 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13610 + " reason=" + app.adjType);
13611
The Android Open Source Project4df24232009-03-05 14:34:35 -080013612 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 // there are applications dependent on our services or providers, but
13614 // this gives us a baseline and makes sure we don't get into an
13615 // infinite recursion.
13616 app.adjSeq = mAdjSeq;
13617 app.curRawAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013618
Christopher Tate6fa95972009-06-05 18:43:55 -070013619 if (mBackupTarget != null && app == mBackupTarget.app) {
13620 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013621 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013622 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013623 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013624 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013625 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013626 }
13627 }
13628
Dianne Hackborn7d608422011-08-07 16:24:18 -070013629 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013630 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013631 final long now = SystemClock.uptimeMillis();
13632 // This process is more important if the top activity is
13633 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013634 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013635 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013636 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013637 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013638 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013639 // If this process has shown some UI, let it immediately
13640 // go to the LRU list because it may be pretty heavy with
13641 // UI stuff. We'll tag it with a label just to help
13642 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013643 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013644 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013645 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013646 } else {
13647 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13648 // This service has seen some activity within
13649 // recent memory, so we will keep its process ahead
13650 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013651 if (adj > ProcessList.SERVICE_ADJ) {
13652 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013653 app.adjType = "started-services";
13654 app.hidden = false;
13655 }
13656 }
13657 // If we have let the service slide into the background
13658 // state, still have some text describing what it is doing
13659 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013660 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013661 app.adjType = "started-bg-services";
13662 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013663 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013664 // Don't kill this process because it is doing work; it
13665 // has said it is doing work.
13666 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013667 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013668 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013669 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013670 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013671 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013672 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013673 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013674 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013675 // XXX should compute this based on the max of
13676 // all connected clients.
13677 ConnectionRecord cr = clist.get(i);
13678 if (cr.binding.client == app) {
13679 // Binding to ourself is not interesting.
13680 continue;
13681 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013682 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013683 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013684 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013685 int myHiddenAdj = hiddenAdj;
13686 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013687 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013688 myHiddenAdj = client.hiddenAdj;
13689 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013690 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013691 }
13692 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013693 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013694 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013695 String adjType = null;
13696 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
13697 // Not doing bind OOM management, so treat
13698 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013699 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013700 // If this process has shown some UI, let it immediately
13701 // go to the LRU list because it may be pretty heavy with
13702 // UI stuff. We'll tag it with a label just to help
13703 // debug and understand what is going on.
13704 if (adj > clientAdj) {
13705 adjType = "bound-bg-ui-services";
13706 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013707 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013708 clientAdj = adj;
13709 } else {
13710 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13711 // This service has not seen activity within
13712 // recent memory, so allow it to drop to the
13713 // LRU list if there is no other reason to keep
13714 // it around. We'll also tag it with a label just
13715 // to help debug and undertand what is going on.
13716 if (adj > clientAdj) {
13717 adjType = "bound-bg-services";
13718 }
13719 clientAdj = adj;
13720 }
13721 }
13722 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013723 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013724 // If this process has recently shown UI, and
13725 // the process that is binding to it is less
13726 // important than being visible, then we don't
13727 // care about the binding as much as we care
13728 // about letting this process get into the LRU
13729 // list to be killed and restarted if needed for
13730 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013731 if (app.hasShownUi && app != mHomeProcess
13732 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013733 adjType = "bound-bg-ui-services";
13734 } else {
13735 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
13736 |Context.BIND_IMPORTANT)) != 0) {
13737 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013738 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
13739 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
13740 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13741 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13742 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013743 adj = clientAdj;
13744 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070013745 app.pendingUiClean = true;
13746 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13747 adj = ProcessList.VISIBLE_APP_ADJ;
13748 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013749 }
13750 if (!client.hidden) {
13751 app.hidden = false;
13752 }
13753 if (client.keeping) {
13754 app.keeping = true;
13755 }
13756 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013757 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013758 }
13759 if (adjType != null) {
13760 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013761 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13762 .REASON_SERVICE_IN_USE;
13763 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013764 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013765 app.adjTarget = s.name;
13766 }
13767 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13768 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13769 schedGroup = Process.THREAD_GROUP_DEFAULT;
13770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013771 }
13772 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013773 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
13774 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013775 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013776 (a.visible || a.state == ActivityState.RESUMED
13777 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013778 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013779 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
13780 schedGroup = Process.THREAD_GROUP_DEFAULT;
13781 }
13782 app.hidden = false;
13783 app.adjType = "service";
13784 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13785 .REASON_SERVICE_IN_USE;
13786 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013787 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013788 app.adjTarget = s.name;
13789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013791 }
13792 }
13793 }
13794 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013795
Dianne Hackborn287952c2010-09-22 22:34:31 -070013796 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013797 // would like to avoid killing it unless it would prevent the current
13798 // application from running. By default we put the process in
13799 // with the rest of the background processes; as we scan through
13800 // its services we may bump it up from there.
13801 if (adj > hiddenAdj) {
13802 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013803 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070013804 app.adjType = "bg-services";
13805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806 }
13807
Dianne Hackborn7d608422011-08-07 16:24:18 -070013808 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013809 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013810 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013811 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013812 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013813 ContentProviderRecord cpr = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013814 if (cpr.clients.size() != 0) {
13815 Iterator<ProcessRecord> kt = cpr.clients.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013816 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 ProcessRecord client = kt.next();
The Android Open Source Project10592532009-03-18 17:39:46 -070013818 if (client == app) {
13819 // Being our own client is not interesting.
13820 continue;
13821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013822 int myHiddenAdj = hiddenAdj;
13823 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013824 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013825 myHiddenAdj = client.hiddenAdj;
13826 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013827 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013828 }
13829 }
13830 int clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831 client, myHiddenAdj, TOP_APP, true, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 if (adj > clientAdj) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013833 if (app.hasShownUi && app != mHomeProcess
13834 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013835 app.adjType = "bg-ui-provider";
13836 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013837 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
13838 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013839 app.adjType = "provider";
13840 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013841 if (!client.hidden) {
13842 app.hidden = false;
13843 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013844 if (client.keeping) {
13845 app.keeping = true;
13846 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070013847 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
13848 .REASON_PROVIDER_IN_USE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013849 app.adjSource = client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070013850 app.adjSourceOom = clientAdj;
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013851 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013852 }
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013853 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
13854 schedGroup = Process.THREAD_GROUP_DEFAULT;
13855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013856 }
13857 }
13858 // If the provider has external (non-framework) process
13859 // dependencies, ensure that its adjustment is at least
13860 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080013861 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013862 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
13863 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013864 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013865 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013866 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013867 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070013868 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013869 }
13870 }
13871 }
13872 }
13873
13874 app.curRawAdj = adj;
13875
Joe Onorato8a9b2202010-02-26 18:56:32 -080013876 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013877 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
13878 if (adj > app.maxAdj) {
13879 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013880 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013881 schedGroup = Process.THREAD_GROUP_DEFAULT;
13882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013883 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013884 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013885 app.keeping = true;
13886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013887
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013888 if (app.hasAboveClient) {
13889 // If this process has bound to any services with BIND_ABOVE_CLIENT,
13890 // then we need to drop its adjustment to be lower than the service's
13891 // in order to honor the request. We want to drop it by one adjustment
13892 // level... but there is special meaning applied to various levels so
13893 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013894 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013895 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070013896 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
13897 adj = ProcessList.VISIBLE_APP_ADJ;
13898 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
13899 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
13900 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13901 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013902 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013903 adj++;
13904 }
13905 }
13906
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013907 if (adj == ProcessList.SERVICE_ADJ) {
13908 if (doingAll) {
13909 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
13910 mNewNumServiceProcs++;
13911 }
13912 if (app.serviceb) {
13913 adj = ProcessList.SERVICE_B_ADJ;
13914 }
13915 } else {
13916 app.serviceb = false;
13917 }
13918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013919 app.curAdj = adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013920 app.curSchedGroup = schedGroup;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013921
13922 if (hadForegroundActivities != app.foregroundActivities) {
Jeff Sharkey287bd832011-05-28 19:36:26 -070013923 mHandler.obtainMessage(DISPATCH_FOREGROUND_ACTIVITIES_CHANGED, app.pid, app.info.uid,
13924 app.foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013925 }
13926
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013927 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013928 }
13929
13930 /**
13931 * Ask a given process to GC right now.
13932 */
13933 final void performAppGcLocked(ProcessRecord app) {
13934 try {
13935 app.lastRequestedGc = SystemClock.uptimeMillis();
13936 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013937 if (app.reportLowMemory) {
13938 app.reportLowMemory = false;
13939 app.thread.scheduleLowMemory();
13940 } else {
13941 app.thread.processInBackground();
13942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013943 }
13944 } catch (Exception e) {
13945 // whatever.
13946 }
13947 }
13948
13949 /**
13950 * Returns true if things are idle enough to perform GCs.
13951 */
Josh Bartel7f208742010-02-25 11:01:44 -060013952 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013953 boolean processingBroadcasts = false;
13954 for (BroadcastQueue q : mBroadcastQueues) {
13955 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13956 processingBroadcasts = true;
13957 }
13958 }
13959 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013960 && (mSleeping || (mMainStack.mResumedActivity != null &&
13961 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013962 }
13963
13964 /**
13965 * Perform GCs on all processes that are waiting for it, but only
13966 * if things are idle.
13967 */
13968 final void performAppGcsLocked() {
13969 final int N = mProcessesToGc.size();
13970 if (N <= 0) {
13971 return;
13972 }
Josh Bartel7f208742010-02-25 11:01:44 -060013973 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013974 while (mProcessesToGc.size() > 0) {
13975 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013976 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013977 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13978 <= SystemClock.uptimeMillis()) {
13979 // To avoid spamming the system, we will GC processes one
13980 // at a time, waiting a few seconds between each.
13981 performAppGcLocked(proc);
13982 scheduleAppGcsLocked();
13983 return;
13984 } else {
13985 // It hasn't been long enough since we last GCed this
13986 // process... put it in the list to wait for its time.
13987 addProcessToGcListLocked(proc);
13988 break;
13989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013990 }
13991 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013992
13993 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013994 }
13995 }
13996
13997 /**
13998 * If all looks good, perform GCs on all processes waiting for them.
13999 */
14000 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014001 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014002 performAppGcsLocked();
14003 return;
14004 }
14005 // Still not idle, wait some more.
14006 scheduleAppGcsLocked();
14007 }
14008
14009 /**
14010 * Schedule the execution of all pending app GCs.
14011 */
14012 final void scheduleAppGcsLocked() {
14013 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014014
14015 if (mProcessesToGc.size() > 0) {
14016 // Schedule a GC for the time to the next process.
14017 ProcessRecord proc = mProcessesToGc.get(0);
14018 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14019
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014020 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014021 long now = SystemClock.uptimeMillis();
14022 if (when < (now+GC_TIMEOUT)) {
14023 when = now + GC_TIMEOUT;
14024 }
14025 mHandler.sendMessageAtTime(msg, when);
14026 }
14027 }
14028
14029 /**
14030 * Add a process to the array of processes waiting to be GCed. Keeps the
14031 * list in sorted order by the last GC time. The process can't already be
14032 * on the list.
14033 */
14034 final void addProcessToGcListLocked(ProcessRecord proc) {
14035 boolean added = false;
14036 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14037 if (mProcessesToGc.get(i).lastRequestedGc <
14038 proc.lastRequestedGc) {
14039 added = true;
14040 mProcessesToGc.add(i+1, proc);
14041 break;
14042 }
14043 }
14044 if (!added) {
14045 mProcessesToGc.add(0, proc);
14046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014047 }
14048
14049 /**
14050 * Set up to ask a process to GC itself. This will either do it
14051 * immediately, or put it on the list of processes to gc the next
14052 * time things are idle.
14053 */
14054 final void scheduleAppGcLocked(ProcessRecord app) {
14055 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014056 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014057 return;
14058 }
14059 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014060 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014061 scheduleAppGcsLocked();
14062 }
14063 }
14064
Dianne Hackborn287952c2010-09-22 22:34:31 -070014065 final void checkExcessivePowerUsageLocked(boolean doKills) {
14066 updateCpuStatsNow();
14067
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014068 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014069 boolean doWakeKills = doKills;
14070 boolean doCpuKills = doKills;
14071 if (mLastPowerCheckRealtime == 0) {
14072 doWakeKills = false;
14073 }
14074 if (mLastPowerCheckUptime == 0) {
14075 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014076 }
14077 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014078 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014079 }
14080 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014081 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14082 final long curUptime = SystemClock.uptimeMillis();
14083 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14084 mLastPowerCheckRealtime = curRealtime;
14085 mLastPowerCheckUptime = curUptime;
14086 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14087 doWakeKills = false;
14088 }
14089 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14090 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014091 }
14092 int i = mLruProcesses.size();
14093 while (i > 0) {
14094 i--;
14095 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014096 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014097 long wtime;
14098 synchronized (stats) {
14099 wtime = stats.getProcessWakeTime(app.info.uid,
14100 app.pid, curRealtime);
14101 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014102 long wtimeUsed = wtime - app.lastWakeTime;
14103 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14104 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014105 StringBuilder sb = new StringBuilder(128);
14106 sb.append("Wake for ");
14107 app.toShortString(sb);
14108 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014109 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014110 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014111 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014112 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014113 sb.append((wtimeUsed*100)/realtimeSince);
14114 sb.append("%)");
14115 Slog.i(TAG, sb.toString());
14116 sb.setLength(0);
14117 sb.append("CPU for ");
14118 app.toShortString(sb);
14119 sb.append(": over ");
14120 TimeUtils.formatDuration(uptimeSince, sb);
14121 sb.append(" used ");
14122 TimeUtils.formatDuration(cputimeUsed, sb);
14123 sb.append(" (");
14124 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014125 sb.append("%)");
14126 Slog.i(TAG, sb.toString());
14127 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014128 // If a process has held a wake lock for more
14129 // than 50% of the time during this period,
14130 // that sounds pad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014131 if (doWakeKills && realtimeSince > 0
14132 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14133 synchronized (stats) {
14134 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14135 realtimeSince, wtimeUsed);
14136 }
14137 Slog.w(TAG, "Excessive wake lock in " + app.processName
14138 + " (pid " + app.pid + "): held " + wtimeUsed
14139 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014140 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14141 app.processName, app.setAdj, "excessive wake lock");
14142 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014143 } else if (doCpuKills && uptimeSince > 0
14144 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14145 synchronized (stats) {
14146 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14147 uptimeSince, cputimeUsed);
14148 }
14149 Slog.w(TAG, "Excessive CPU in " + app.processName
14150 + " (pid " + app.pid + "): used " + cputimeUsed
14151 + " during " + uptimeSince);
14152 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14153 app.processName, app.setAdj, "excessive cpu");
14154 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014155 } else {
14156 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014157 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014158 }
14159 }
14160 }
14161 }
14162
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014163 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014164 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014165 app.hiddenAdj = hiddenAdj;
14166
14167 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014168 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014169 }
14170
Dianne Hackborn287952c2010-09-22 22:34:31 -070014171 final boolean wasKeeping = app.keeping;
14172
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014173 boolean success = true;
14174
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014175 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014176
Jeff Brown10e89712011-07-08 18:52:57 -070014177 if (app.curRawAdj != app.setRawAdj) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070014178 if (false) {
14179 // Removing for now. Forcing GCs is not so useful anymore
14180 // with Dalvik, and the new memory level hint facility is
14181 // better for what we need to do these days.
14182 if (app.curRawAdj > ProcessList.FOREGROUND_APP_ADJ
14183 && app.setRawAdj <= ProcessList.FOREGROUND_APP_ADJ) {
14184 // If this app is transitioning from foreground to
14185 // non-foreground, have it do a gc.
14186 scheduleAppGcLocked(app);
14187 } else if (app.curRawAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14188 && app.setRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14189 // Likewise do a gc when an app is moving in to the
14190 // background (such as a service stopping).
14191 scheduleAppGcLocked(app);
14192 }
Jeff Brown10e89712011-07-08 18:52:57 -070014193 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014194
Jeff Brown10e89712011-07-08 18:52:57 -070014195 if (wasKeeping && !app.keeping) {
14196 // This app is no longer something we want to keep. Note
14197 // its current wake lock time to later know to kill it if
14198 // it is not behaving well.
14199 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14200 synchronized (stats) {
14201 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14202 app.pid, SystemClock.elapsedRealtime());
14203 }
14204 app.lastCpuTime = app.curCpuTime;
14205 }
14206
14207 app.setRawAdj = app.curRawAdj;
14208 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014209
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014210 if (app.curAdj != app.setAdj) {
14211 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014212 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014213 TAG, "Set " + app.pid + " " + app.processName +
14214 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014215 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014216 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014217 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014218 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014219 }
14220 }
14221 if (app.setSchedGroup != app.curSchedGroup) {
14222 app.setSchedGroup = app.curSchedGroup;
14223 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14224 "Setting process group of " + app.processName
14225 + " to " + app.curSchedGroup);
14226 if (app.waitingToKill != null &&
14227 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14228 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14229 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14230 app.processName, app.setAdj, app.waitingToKill);
14231 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014232 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014233 } else {
14234 if (true) {
14235 long oldId = Binder.clearCallingIdentity();
14236 try {
14237 Process.setProcessGroup(app.pid, app.curSchedGroup);
14238 } catch (Exception e) {
14239 Slog.w(TAG, "Failed setting process group of " + app.pid
14240 + " to " + app.curSchedGroup);
14241 e.printStackTrace();
14242 } finally {
14243 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014244 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014245 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014246 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014247 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014248 app.thread.setSchedulingGroup(app.curSchedGroup);
14249 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014250 }
14251 }
14252 }
14253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014254 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014255 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014256 }
14257
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014258 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014259 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014260 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014261 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014262 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014263 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014264 }
14265 }
14266 return resumedActivity;
14267 }
14268
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014269 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014270 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014271 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14272 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014273 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14274 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014275
14276 mAdjSeq++;
14277
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014278 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014279 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14280 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014281 if (nowHidden != wasHidden) {
14282 // Changed to/from hidden state, so apps after it in the LRU
14283 // list may also be changed.
14284 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014285 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014286 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014287 }
14288
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014289 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014290 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014291 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14292
14293 if (false) {
14294 RuntimeException e = new RuntimeException();
14295 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014296 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014297 }
14298
14299 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014300 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014301
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014302 // Let's determine how many processes we have running vs.
14303 // how many slots we have for background processes; we may want
14304 // to put multiple processes in a slot of there are enough of
14305 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014306 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014307 int factor = (mLruProcesses.size()-4)/numSlots;
14308 if (factor < 1) factor = 1;
14309 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014310 int numHidden = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014311
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014312 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014313 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014314 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014315 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014316 while (i > 0) {
14317 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014318 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014319 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014320 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14321 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014322 && app.curAdj == curHiddenAdj) {
14323 step++;
14324 if (step >= factor) {
14325 step = 0;
14326 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014328 }
14329 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014330 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014331 numHidden++;
14332 if (numHidden > mProcessLimit) {
14333 Slog.i(TAG, "No longer want " + app.processName
14334 + " (pid " + app.pid + "): hidden #" + numHidden);
14335 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14336 app.processName, app.setAdj, "too many background");
14337 app.killedBackground = true;
14338 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014339 }
14340 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014341 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14342 // If this is an isolated process, and there are no
14343 // services running in it, then the process is no longer
14344 // needed. We agressively kill these because we can by
14345 // definition not re-use the same process again, and it is
14346 // good to avoid having whatever code was running in them
14347 // left sitting around after no longer needed.
14348 Slog.i(TAG, "Isolated process " + app.processName
14349 + " (pid " + app.pid + ") no longer needed");
14350 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14351 app.processName, app.setAdj, "isolated not needed");
14352 app.killedBackground = true;
14353 Process.killProcessQuiet(app.pid);
14354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014355 }
14356 }
14357
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014358 mNumServiceProcs = mNewNumServiceProcs;
14359
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014360 // Now determine the memory trimming level of background processes.
14361 // Unfortunately we need to start at the back of the list to do this
14362 // properly. We only do this if the number of background apps we
14363 // are managing to keep around is less than half the maximum we desire;
14364 // if we are keeping a good number around, we'll let them use whatever
14365 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014366 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014367 final int N = mLruProcesses.size();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014368 factor = numHidden/3;
14369 int minFactor = 2;
14370 if (mHomeProcess != null) minFactor++;
14371 if (mPreviousProcess != null) minFactor++;
14372 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014373 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014374 int fgTrimLevel;
14375 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14376 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14377 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14378 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14379 } else {
14380 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14381 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014382 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014383 for (i=0; i<N; i++) {
14384 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014385 if (app.curAdj >= ProcessList.HOME_APP_ADJ
14386 && app.curAdj != ProcessList.SERVICE_B_ADJ
14387 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014388 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14389 try {
14390 app.thread.scheduleTrimMemory(curLevel);
14391 } catch (RemoteException e) {
14392 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014393 if (false) {
14394 // For now we won't do this; our memory trimming seems
14395 // to be good enough at this point that destroying
14396 // activities causes more harm than good.
14397 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14398 && app != mHomeProcess && app != mPreviousProcess) {
14399 // For these apps we will also finish their activities
14400 // to help them free memory.
14401 mMainStack.destroyActivitiesLocked(app, false, "trim");
14402 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014403 }
14404 }
14405 app.trimMemoryLevel = curLevel;
14406 step++;
14407 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014408 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014409 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014410 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14411 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014412 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014413 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14414 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014415 break;
14416 }
14417 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014418 } else if (app.curAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014419 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014420 && app.thread != null) {
14421 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014422 app.thread.scheduleTrimMemory(
14423 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014424 } catch (RemoteException e) {
14425 }
14426 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014427 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014428 } else {
14429 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
14430 && app.pendingUiClean) {
14431 // If this application is now in the background and it
14432 // had done UI, then give it the special trim level to
14433 // have it free UI resources.
14434 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14435 if (app.trimMemoryLevel < level && app.thread != null) {
14436 try {
14437 app.thread.scheduleTrimMemory(level);
14438 } catch (RemoteException e) {
14439 }
14440 }
14441 app.pendingUiClean = false;
14442 }
14443 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014444 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014445 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014446 } catch (RemoteException e) {
14447 }
14448 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014449 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014450 }
14451 }
14452 } else {
14453 final int N = mLruProcesses.size();
14454 for (i=0; i<N; i++) {
14455 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014456 if ((app.curAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014457 && app.pendingUiClean) {
14458 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14459 && app.thread != null) {
14460 try {
14461 app.thread.scheduleTrimMemory(
14462 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14463 } catch (RemoteException e) {
14464 }
14465 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014466 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014467 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014468 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014469 }
14470 }
14471
14472 if (mAlwaysFinishActivities) {
Dianne Hackborn28695e02011-11-02 21:59:51 -070014473 mMainStack.destroyActivitiesLocked(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014475 }
14476
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014477 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014478 synchronized (this) {
14479 int i;
14480
14481 // First remove any unused application processes whose package
14482 // has been removed.
14483 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14484 final ProcessRecord app = mRemovedProcesses.get(i);
14485 if (app.activities.size() == 0
14486 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014487 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014488 TAG, "Exiting empty application process "
14489 + app.processName + " ("
14490 + (app.thread != null ? app.thread.asBinder() : null)
14491 + ")\n");
14492 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014493 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14494 app.processName, app.setAdj, "empty");
14495 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014496 } else {
14497 try {
14498 app.thread.scheduleExit();
14499 } catch (Exception e) {
14500 // Ignore exceptions.
14501 }
14502 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014503 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014504 mRemovedProcesses.remove(i);
14505
14506 if (app.persistent) {
14507 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014508 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014509 }
14510 }
14511 }
14512 }
14513
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014514 // Now update the oom adj for all processes.
14515 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014516 }
14517 }
14518
14519 /** This method sends the specified signal to each of the persistent apps */
14520 public void signalPersistentProcesses(int sig) throws RemoteException {
14521 if (sig != Process.SIGNAL_USR1) {
14522 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14523 }
14524
14525 synchronized (this) {
14526 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14527 != PackageManager.PERMISSION_GRANTED) {
14528 throw new SecurityException("Requires permission "
14529 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14530 }
14531
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014532 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14533 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014534 if (r.thread != null && r.persistent) {
14535 Process.sendSignal(r.pid, sig);
14536 }
14537 }
14538 }
14539 }
14540
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014541 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14542 if (proc == null || proc == mProfileProc) {
14543 proc = mProfileProc;
14544 path = mProfileFile;
14545 profileType = mProfileType;
14546 clearProfilerLocked();
14547 }
14548 if (proc == null) {
14549 return;
14550 }
14551 try {
14552 proc.thread.profilerControl(false, path, null, profileType);
14553 } catch (RemoteException e) {
14554 throw new IllegalStateException("Process disappeared");
14555 }
14556 }
14557
14558 private void clearProfilerLocked() {
14559 if (mProfileFd != null) {
14560 try {
14561 mProfileFd.close();
14562 } catch (IOException e) {
14563 }
14564 }
14565 mProfileApp = null;
14566 mProfileProc = null;
14567 mProfileFile = null;
14568 mProfileType = 0;
14569 mAutoStopProfiler = false;
14570 }
14571
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014572 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014573 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014574
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014575 try {
14576 synchronized (this) {
14577 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14578 // its own permission.
14579 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14580 != PackageManager.PERMISSION_GRANTED) {
14581 throw new SecurityException("Requires permission "
14582 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014583 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014584
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014585 if (start && fd == null) {
14586 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014587 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014588
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014589 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014590 if (process != null) {
14591 try {
14592 int pid = Integer.parseInt(process);
14593 synchronized (mPidsSelfLocked) {
14594 proc = mPidsSelfLocked.get(pid);
14595 }
14596 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014597 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014598
14599 if (proc == null) {
14600 HashMap<String, SparseArray<ProcessRecord>> all
14601 = mProcessNames.getMap();
14602 SparseArray<ProcessRecord> procs = all.get(process);
14603 if (procs != null && procs.size() > 0) {
14604 proc = procs.valueAt(0);
14605 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014606 }
14607 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014608
14609 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014610 throw new IllegalArgumentException("Unknown process: " + process);
14611 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014612
14613 if (start) {
14614 stopProfilerLocked(null, null, 0);
14615 setProfileApp(proc.info, proc.processName, path, fd, false);
14616 mProfileProc = proc;
14617 mProfileType = profileType;
14618 try {
14619 fd = fd.dup();
14620 } catch (IOException e) {
14621 fd = null;
14622 }
14623 proc.thread.profilerControl(start, path, fd, profileType);
14624 fd = null;
14625 mProfileFd = null;
14626 } else {
14627 stopProfilerLocked(proc, path, profileType);
14628 if (fd != null) {
14629 try {
14630 fd.close();
14631 } catch (IOException e) {
14632 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014633 }
14634 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014635
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014636 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014637 }
14638 } catch (RemoteException e) {
14639 throw new IllegalStateException("Process disappeared");
14640 } finally {
14641 if (fd != null) {
14642 try {
14643 fd.close();
14644 } catch (IOException e) {
14645 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014646 }
14647 }
14648 }
Andy McFadden824c5102010-07-09 16:26:57 -070014649
14650 public boolean dumpHeap(String process, boolean managed,
14651 String path, ParcelFileDescriptor fd) throws RemoteException {
14652
14653 try {
14654 synchronized (this) {
14655 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14656 // its own permission (same as profileControl).
14657 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14658 != PackageManager.PERMISSION_GRANTED) {
14659 throw new SecurityException("Requires permission "
14660 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
14661 }
14662
14663 if (fd == null) {
14664 throw new IllegalArgumentException("null fd");
14665 }
14666
14667 ProcessRecord proc = null;
14668 try {
14669 int pid = Integer.parseInt(process);
14670 synchronized (mPidsSelfLocked) {
14671 proc = mPidsSelfLocked.get(pid);
14672 }
14673 } catch (NumberFormatException e) {
14674 }
14675
14676 if (proc == null) {
14677 HashMap<String, SparseArray<ProcessRecord>> all
14678 = mProcessNames.getMap();
14679 SparseArray<ProcessRecord> procs = all.get(process);
14680 if (procs != null && procs.size() > 0) {
14681 proc = procs.valueAt(0);
14682 }
14683 }
14684
14685 if (proc == null || proc.thread == null) {
14686 throw new IllegalArgumentException("Unknown process: " + process);
14687 }
14688
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080014689 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
14690 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070014691 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
14692 throw new SecurityException("Process not debuggable: " + proc);
14693 }
14694 }
14695
14696 proc.thread.dumpHeap(managed, path, fd);
14697 fd = null;
14698 return true;
14699 }
14700 } catch (RemoteException e) {
14701 throw new IllegalStateException("Process disappeared");
14702 } finally {
14703 if (fd != null) {
14704 try {
14705 fd.close();
14706 } catch (IOException e) {
14707 }
14708 }
14709 }
14710 }
14711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014712 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
14713 public void monitor() {
14714 synchronized (this) { }
14715 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014716
Dianne Hackborna573f6a2012-02-09 16:12:18 -080014717 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080014718 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
14719 ProcessRecord processRecord = mLruProcesses.get(i);
14720 try {
14721 if (processRecord.thread != null) {
14722 processRecord.thread.setCoreSettings(settings);
14723 }
14724 } catch (RemoteException re) {
14725 /* ignore */
14726 }
14727 }
14728 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014729
14730 // Multi-user methods
14731
Amith Yamasani742a6712011-05-04 14:49:28 -070014732 private int mCurrentUserId;
14733 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
14734
14735 public boolean switchUser(int userId) {
14736 final int callingUid = Binder.getCallingUid();
14737 if (callingUid != 0 && callingUid != Process.myUid()) {
14738 Slog.e(TAG, "Trying to switch user from unauthorized app");
14739 return false;
14740 }
14741 if (mCurrentUserId == userId)
14742 return true;
14743
14744 synchronized (this) {
14745 // Check if user is already logged in, otherwise check if user exists first before
14746 // adding to the list of logged in users.
14747 if (mLoggedInUsers.indexOfKey(userId) < 0) {
14748 if (!userExists(userId)) {
14749 return false;
14750 }
14751 mLoggedInUsers.append(userId, userId);
14752 }
14753
14754 mCurrentUserId = userId;
14755 boolean haveActivities = mMainStack.switchUser(userId);
14756 if (!haveActivities) {
14757 startHomeActivityLocked(userId);
14758 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014759
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014760 }
Amith Yamasani13593602012-03-22 16:16:17 -070014761
14762 // Inform of user switch
14763 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
14764 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
14765 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
14766
Amith Yamasani4b2e9342011-03-31 12:38:53 -070014767 return true;
14768 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014769
Amith Yamasani52f1d752012-03-28 18:19:29 -070014770 @Override
14771 public UserInfo getCurrentUser() throws RemoteException {
14772 final int callingUid = Binder.getCallingUid();
14773 if (callingUid != 0 && callingUid != Process.myUid()) {
14774 Slog.e(TAG, "Trying to get user from unauthorized app");
14775 return null;
14776 }
14777 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
14778 }
14779
Amith Yamasani13593602012-03-22 16:16:17 -070014780 private void onUserRemoved(Intent intent) {
14781 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
14782 if (extraUserId < 1) return;
14783
14784 // Kill all the processes for the user
14785 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
14786 synchronized (this) {
14787 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
14788 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
14789 SparseArray<ProcessRecord> uids = uidMap.getValue();
14790 for (int i = 0; i < uids.size(); i++) {
14791 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
14792 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
14793 }
14794 }
14795 }
14796
14797 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
14798 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
14799 false, false, true, true, extraUserId);
14800 }
14801 }
14802 }
14803
Amith Yamasani742a6712011-05-04 14:49:28 -070014804 private boolean userExists(int userId) {
14805 try {
Amith Yamasani13593602012-03-22 16:16:17 -070014806 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
14807 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014808 } catch (RemoteException re) {
14809 // Won't happen, in same process
14810 }
14811
14812 return false;
14813 }
14814
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014815 private void checkValidCaller(int uid, int userId) {
14816 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
14817
14818 throw new SecurityException("Caller uid=" + uid
14819 + " is not privileged to communicate with user=" + userId);
14820 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014821
14822 private int applyUserId(int uid, int userId) {
14823 return UserId.getUid(userId, uid);
14824 }
14825
14826 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014827 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014828 ApplicationInfo newInfo = new ApplicationInfo(info);
14829 newInfo.uid = applyUserId(info.uid, userId);
14830 if (newInfo.uid >= Process.FIRST_APPLICATION_UID) {
14831 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14832 + info.packageName;
14833 }
14834 return newInfo;
14835 }
14836
14837 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014838 if (aInfo == null || aInfo.applicationInfo.uid < Process.FIRST_APPLICATION_UID
Amith Yamasani742a6712011-05-04 14:49:28 -070014839 || userId < 1) {
14840 return aInfo;
14841 }
14842
14843 ActivityInfo info = new ActivityInfo(aInfo);
14844 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14845 return info;
14846 }
14847
14848 static class ServiceMap {
14849
14850 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
14851 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
14852 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
14853 mServicesByIntentPerUser = new SparseArray<
14854 HashMap<Intent.FilterComparison, ServiceRecord>>();
14855
14856 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
14857 // TODO: Deal with global services
14858 if (DEBUG_MU)
14859 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
14860 return getServices(callingUser).get(name);
14861 }
14862
14863 ServiceRecord getServiceByName(ComponentName name) {
14864 return getServiceByName(name, -1);
14865 }
14866
14867 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14868 // TODO: Deal with global services
14869 if (DEBUG_MU)
14870 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
14871 return getServicesByIntent(callingUser).get(filter);
14872 }
14873
14874 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
14875 return getServiceByIntent(filter, -1);
14876 }
14877
14878 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
14879 // TODO: Deal with global services
14880 getServices(callingUser).put(name, value);
14881 }
14882
14883 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
14884 ServiceRecord value) {
14885 // TODO: Deal with global services
14886 getServicesByIntent(callingUser).put(filter, value);
14887 }
14888
14889 void removeServiceByName(ComponentName name, int callingUser) {
14890 // TODO: Deal with global services
14891 ServiceRecord removed = getServices(callingUser).remove(name);
14892 if (DEBUG_MU)
14893 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
14894 + " removed=" + removed);
14895 }
14896
14897 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
14898 // TODO: Deal with global services
14899 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
14900 if (DEBUG_MU)
14901 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
14902 + " removed=" + removed);
14903 }
14904
14905 Collection<ServiceRecord> getAllServices(int callingUser) {
14906 // TODO: Deal with global services
14907 return getServices(callingUser).values();
14908 }
14909
14910 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
14911 HashMap map = mServicesByNamePerUser.get(callingUser);
14912 if (map == null) {
14913 map = new HashMap<ComponentName, ServiceRecord>();
14914 mServicesByNamePerUser.put(callingUser, map);
14915 }
14916 return map;
14917 }
14918
14919 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
14920 int callingUser) {
14921 HashMap map = mServicesByIntentPerUser.get(callingUser);
14922 if (map == null) {
14923 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
14924 mServicesByIntentPerUser.put(callingUser, map);
14925 }
14926 return map;
14927 }
14928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014929}